repo
string | commit
string | message
string | diff
string |
---|---|---|---|
Elleo/gst-opencv
|
e8320947b938fc07b8195eab82be45c3c35f9b82
|
cvsmooth: Add support for video/x-raw-gray
|
diff --git a/src/basicfilters/gstcvsmooth.c b/src/basicfilters/gstcvsmooth.c
index 4a3fba7..ec24b2c 100644
--- a/src/basicfilters/gstcvsmooth.c
+++ b/src/basicfilters/gstcvsmooth.c
@@ -1,336 +1,338 @@
/*
* GStreamer
* Copyright (C) 2010 Thiago Santos <thiago.sousa.santos@collabora.co.uk>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <gst/gst.h>
#include "gstcvsmooth.h"
GST_DEBUG_CATEGORY_STATIC (gst_cv_smooth_debug);
#define GST_CAT_DEFAULT gst_cv_smooth_debug
static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
GST_PAD_SINK,
GST_PAD_ALWAYS,
- GST_STATIC_CAPS ("video/x-raw-rgb, depth=(int)24, bpp=(int)24")
+ GST_STATIC_CAPS ("video/x-raw-rgb, depth=(int)24, bpp=(int)24;"
+ "video/x-raw-gray, depth=(int)8, bpp=(int)8")
);
static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
GST_PAD_SRC,
GST_PAD_ALWAYS,
- GST_STATIC_CAPS ("video/x-raw-rgb, depth=(int)24, bpp=(int)24")
+ GST_STATIC_CAPS ("video/x-raw-rgb, depth=(int)24, bpp=(int)24;"
+ "video/x-raw-gray, depth=(int)8, bpp=(int)8")
);
/* Filter signals and args */
enum
{
/* FILL ME */
LAST_SIGNAL
};
enum
{
PROP_0,
PROP_SMOOTH_TYPE,
PROP_PARAM1,
PROP_PARAM2,
PROP_PARAM3,
PROP_PARAM4
};
#define GST_TYPE_CV_SMOOTH_TYPE (gst_cv_smooth_type_get_type ())
static GType
gst_cv_smooth_type_get_type (void)
{
static GType cv_smooth_type_type = 0;
static const GEnumValue smooth_types[] = {
{CV_BLUR_NO_SCALE, "CV Blur No Scale", "blur-no-scale"},
{CV_BLUR, "CV Blur", "blur"},
{CV_GAUSSIAN, "CV Gaussian", "gaussian"},
{CV_MEDIAN, "CV Median", "median"},
{CV_BILATERAL, "CV Bilateral", "bilateral"},
{0, NULL, NULL},
};
if (!cv_smooth_type_type) {
cv_smooth_type_type =
g_enum_register_static ("GstCvSmoothTypeType", smooth_types);
}
return cv_smooth_type_type;
}
#define DEFAULT_CV_SMOOTH_TYPE CV_GAUSSIAN
#define DEFAULT_PARAM1 3
#define DEFAULT_PARAM2 0.0
#define DEFAULT_PARAM3 0.0
#define DEFAULT_PARAM4 0.0
GST_BOILERPLATE (GstCvSmooth, gst_cv_smooth, GstOpencvBaseTransform,
GST_TYPE_OPENCV_BASE_TRANSFORM);
static void gst_cv_smooth_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec);
static void gst_cv_smooth_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec);
static GstFlowReturn gst_cv_smooth_transform_ip (GstOpencvBaseTransform * filter,
GstBuffer * buf, IplImage * img);
static GstFlowReturn gst_cv_smooth_transform (GstOpencvBaseTransform * filter,
GstBuffer * buf, IplImage * img, GstBuffer * outbuf, IplImage * outimg);
/* Clean up */
static void
gst_cv_smooth_finalize (GObject * obj)
{
G_OBJECT_CLASS (parent_class)->finalize (obj);
}
/* GObject vmethod implementations */
static void
gst_cv_smooth_base_init (gpointer gclass)
{
GstElementClass *element_class = GST_ELEMENT_CLASS (gclass);
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&src_factory));
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&sink_factory));
gst_element_class_set_details_simple (element_class,
"cvsmooth",
"Transform/Effect/Video",
"Applies cvSmooth OpenCV function to the image",
"Thiago Santos<thiago.sousa.santos@collabora.co.uk>");
}
/* initialize the cvsmooth's class */
static void
gst_cv_smooth_class_init (GstCvSmoothClass * klass)
{
GObjectClass *gobject_class;
GstOpencvBaseTransformClass *gstopencvbasefilter_class;
GstElementClass *gstelement_class;
gobject_class = (GObjectClass *) klass;
gstelement_class = (GstElementClass *) klass;
gstopencvbasefilter_class = (GstOpencvBaseTransformClass *) klass;
parent_class = g_type_class_peek_parent (klass);
gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_cv_smooth_finalize);
gobject_class->set_property = gst_cv_smooth_set_property;
gobject_class->get_property = gst_cv_smooth_get_property;
gstopencvbasefilter_class->cv_trans_ip_func = gst_cv_smooth_transform_ip;
gstopencvbasefilter_class->cv_trans_func = gst_cv_smooth_transform;
g_object_class_install_property (gobject_class, PROP_SMOOTH_TYPE,
g_param_spec_enum ("type",
"type",
"Smooth Type",
GST_TYPE_CV_SMOOTH_TYPE,
DEFAULT_CV_SMOOTH_TYPE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)
);
g_object_class_install_property (gobject_class, PROP_PARAM1,
g_param_spec_int ("param1", "param1",
"Param1 (Check cvSmooth OpenCV docs)", 1, G_MAXINT, DEFAULT_PARAM1,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
g_object_class_install_property (gobject_class, PROP_PARAM2,
g_param_spec_int ("param2", "param2",
"Param2 (Check cvSmooth OpenCV docs)", 0, G_MAXINT, DEFAULT_PARAM2,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
g_object_class_install_property (gobject_class, PROP_PARAM3,
g_param_spec_double ("param3", "param3",
"Param3 (Check cvSmooth OpenCV docs)", 0, G_MAXDOUBLE, DEFAULT_PARAM3,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
g_object_class_install_property (gobject_class, PROP_PARAM4,
g_param_spec_double ("param4", "param4",
"Param4 (Check cvSmooth OpenCV docs)", 0, G_MAXDOUBLE, DEFAULT_PARAM4,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
}
/* initialize the new element
* instantiate pads and add them to element
* set pad calback functions
* initialize instance structure
*/
static void
gst_cv_smooth_init (GstCvSmooth * filter, GstCvSmoothClass * gclass)
{
filter->type = DEFAULT_CV_SMOOTH_TYPE;
filter->param1 = DEFAULT_PARAM1;
filter->param2 = DEFAULT_PARAM2;
filter->param3 = DEFAULT_PARAM3;
filter->param4 = DEFAULT_PARAM4;
gst_base_transform_set_in_place (GST_BASE_TRANSFORM (filter), FALSE);
}
static void
gst_cv_smooth_change_type (GstCvSmooth * filter, gint value)
{
GST_DEBUG_OBJECT (filter, "Changing type from %d to %d", filter->type, value);
if (filter->type == value)
return;
filter->type = value;
switch (value) {
case CV_GAUSSIAN:
case CV_BLUR:
gst_base_transform_set_in_place (GST_BASE_TRANSFORM (filter), TRUE);
break;
default:
gst_base_transform_set_in_place (GST_BASE_TRANSFORM (filter), FALSE);
break;
}
}
static void
gst_cv_smooth_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec)
{
GstCvSmooth *filter = GST_CV_SMOOTH (object);
switch (prop_id) {
case PROP_SMOOTH_TYPE:
gst_cv_smooth_change_type (filter, g_value_get_enum (value));
break;
case PROP_PARAM1:{
gint prop = g_value_get_int (value);
if (prop % 2 == 1) {
filter->param1 = prop;
} else {
GST_WARNING_OBJECT (filter, "Ignoring value for param1, not odd"
"(%d)", prop);
}
}
break;
case PROP_PARAM2:{
gint prop = g_value_get_int (value);
if (prop % 2 == 1 || prop == 0) {
filter->param1 = prop;
} else {
GST_WARNING_OBJECT (filter, "Ignoring value for param2, not odd"
" nor zero (%d)", prop);
}
}
break;
case PROP_PARAM3:
filter->param3 = g_value_get_double (value);
break;
case PROP_PARAM4:
filter->param4 = g_value_get_double (value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gst_cv_smooth_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec)
{
GstCvSmooth *filter = GST_CV_SMOOTH (object);
switch (prop_id) {
case PROP_SMOOTH_TYPE:
g_value_set_enum (value, filter->type);
break;
case PROP_PARAM1:
g_value_set_int (value, filter->param1);
break;
case PROP_PARAM2:
g_value_set_int (value, filter->param2);
break;
case PROP_PARAM3:
g_value_set_double (value, filter->param3);
break;
case PROP_PARAM4:
g_value_set_double (value, filter->param4);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static GstFlowReturn
gst_cv_smooth_transform (GstOpencvBaseTransform * base, GstBuffer * buf,
IplImage * img, GstBuffer * outbuf, IplImage * outimg)
{
GstCvSmooth *filter = GST_CV_SMOOTH (base);
cvSmooth (img, outimg, filter->type, filter->param1, filter->param2,
filter->param3, filter->param4);
return GST_FLOW_OK;
}
static GstFlowReturn
gst_cv_smooth_transform_ip (GstOpencvBaseTransform * base, GstBuffer * buf,
IplImage * img)
{
GstCvSmooth *filter = GST_CV_SMOOTH (base);
cvSmooth (img, img, filter->type, filter->param1, filter->param2,
filter->param3, filter->param4);
return GST_FLOW_OK;
}
gboolean
gst_cv_smooth_plugin_init (GstPlugin * plugin)
{
GST_DEBUG_CATEGORY_INIT (gst_cv_smooth_debug, "cvsmooth", 0, "cvsmooth");
return gst_element_register (plugin, "cvsmooth", GST_RANK_NONE,
GST_TYPE_CV_SMOOTH);
}
diff --git a/src/gstopencvbasetrans.c b/src/gstopencvbasetrans.c
index 4dfd586..747d250 100644
--- a/src/gstopencvbasetrans.c
+++ b/src/gstopencvbasetrans.c
@@ -1,301 +1,301 @@
/*
* GStreamer
* Copyright (C) 2010 Thiago Santos <thiago.sousa.santos@collabora.co.uk>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/* TODO opencv can do scaling for some cases */
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <gst/gst.h>
#include "gstopencvbasetrans.h"
#include "gstopencvutils.h"
GST_DEBUG_CATEGORY_STATIC (gst_opencv_base_transform_debug);
#define GST_CAT_DEFAULT gst_opencv_base_transform_debug
/* Filter signals and args */
enum
{
/* FILL ME */
LAST_SIGNAL
};
enum
{
PROP_0
};
static GstElementClass *parent_class = NULL;
static void gst_opencv_base_transform_class_init (GstOpencvBaseTransformClass *
klass);
static void gst_opencv_base_transform_init (GstOpencvBaseTransform * trans,
GstOpencvBaseTransformClass * klass);
static void gst_opencv_base_transform_base_init (gpointer gclass);
static gboolean gst_opencv_base_transform_set_caps (GstBaseTransform * trans,
GstCaps * incaps, GstCaps * outcaps);
static GstFlowReturn gst_opencv_base_transform_transform_ip (GstBaseTransform *
trans, GstBuffer * buf);
static GstFlowReturn gst_opencv_base_transform_transform (GstBaseTransform * trans,
GstBuffer * inbuf, GstBuffer * outbuf);
static gboolean gst_opencv_base_transform_get_unit_size (GstBaseTransform * trans,
GstCaps * caps, guint * size);
static void gst_opencv_base_transform_set_property (GObject * object,
guint prop_id, const GValue * value, GParamSpec * pspec);
static void gst_opencv_base_transform_get_property (GObject * object,
guint prop_id, GValue * value, GParamSpec * pspec);
GType
gst_opencv_base_transform_get_type (void)
{
static volatile gsize opencv_base_transform_type = 0;
if (g_once_init_enter (&opencv_base_transform_type)) {
GType _type;
static const GTypeInfo opencv_base_transform_info = {
sizeof (GstOpencvBaseTransformClass),
(GBaseInitFunc) gst_opencv_base_transform_base_init,
NULL,
(GClassInitFunc) gst_opencv_base_transform_class_init,
NULL,
NULL,
sizeof (GstOpencvBaseTransform),
0,
(GInstanceInitFunc) gst_opencv_base_transform_init,
};
_type = g_type_register_static (GST_TYPE_BASE_TRANSFORM,
"GstOpencvBaseTransform", &opencv_base_transform_info, G_TYPE_FLAG_ABSTRACT);
g_once_init_leave (&opencv_base_transform_type, _type);
}
return opencv_base_transform_type;
}
/* Clean up */
static void
gst_opencv_base_transform_finalize (GObject * obj)
{
GstOpencvBaseTransform *transform = GST_OPENCV_BASE_TRANSFORM (obj);
if (transform->cvImage)
cvReleaseImage (&transform->cvImage);
G_OBJECT_CLASS (parent_class)->finalize (obj);
}
/* GObject vmethod implementations */
static void
gst_opencv_base_transform_base_init (gpointer gclass)
{
}
static void
gst_opencv_base_transform_class_init (GstOpencvBaseTransformClass * klass)
{
GObjectClass *gobject_class;
GstElementClass *gstelement_class;
GstBaseTransformClass *basetrans_class;
gobject_class = (GObjectClass *) klass;
gstelement_class = (GstElementClass *) klass;
basetrans_class = (GstBaseTransformClass *) klass;
parent_class = g_type_class_peek_parent (klass);
GST_DEBUG_CATEGORY_INIT (gst_opencv_base_transform_debug, "opencvbasetransform", 0,
"opencvbasetransform element");
gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_opencv_base_transform_finalize);
gobject_class->set_property = gst_opencv_base_transform_set_property;
gobject_class->get_property = gst_opencv_base_transform_get_property;
basetrans_class->transform = gst_opencv_base_transform_transform;
basetrans_class->transform_ip = gst_opencv_base_transform_transform_ip;
basetrans_class->set_caps = gst_opencv_base_transform_set_caps;
basetrans_class->get_unit_size = gst_opencv_base_transform_get_unit_size;
}
static void
gst_opencv_base_transform_init (GstOpencvBaseTransform * transform,
GstOpencvBaseTransformClass * bclass)
{
}
static GstFlowReturn
gst_opencv_base_transform_transform (GstBaseTransform * trans, GstBuffer * inbuf,
GstBuffer * outbuf)
{
GstOpencvBaseTransform *transform;
GstOpencvBaseTransformClass *fclass;
transform = GST_OPENCV_BASE_TRANSFORM (trans);
fclass = GST_OPENCV_BASE_TRANSFORM_GET_CLASS (transform);
g_return_val_if_fail (fclass->cv_trans_func != NULL, GST_FLOW_ERROR);
g_return_val_if_fail (transform->cvImage != NULL, GST_FLOW_ERROR);
g_return_val_if_fail (transform->out_cvImage != NULL, GST_FLOW_ERROR);
transform->cvImage->imageData = (char *) GST_BUFFER_DATA (inbuf);
transform->out_cvImage->imageData = (char *) GST_BUFFER_DATA (outbuf);
return fclass->cv_trans_func (transform, inbuf, transform->cvImage, outbuf,
transform->out_cvImage);
}
static GstFlowReturn
gst_opencv_base_transform_transform_ip (GstBaseTransform * trans,
GstBuffer * buffer)
{
GstOpencvBaseTransform *transform;
GstOpencvBaseTransformClass *fclass;
transform = GST_OPENCV_BASE_TRANSFORM (trans);
fclass = GST_OPENCV_BASE_TRANSFORM_GET_CLASS (transform);
g_return_val_if_fail (fclass->cv_trans_ip_func != NULL, GST_FLOW_ERROR);
g_return_val_if_fail (transform->cvImage != NULL, GST_FLOW_ERROR);
buffer = gst_buffer_make_writable (buffer);
transform->cvImage->imageData = (char *) GST_BUFFER_DATA (buffer);
/* FIXME how to release buffer? */
return fclass->cv_trans_ip_func (transform, buffer, transform->cvImage);
}
static gboolean
gst_opencv_base_transform_set_caps (GstBaseTransform * trans, GstCaps * incaps,
GstCaps * outcaps)
{
GstOpencvBaseTransform *transform = GST_OPENCV_BASE_TRANSFORM (trans);
gint in_width, in_height;
- gint in_depth, in_type, in_channels;
+ gint in_depth, in_channels;
gint out_width, out_height;
- gint out_depth, out_type, out_channels;
+ gint out_depth, out_channels;
GError *in_err = NULL;
GError *out_err = NULL;
if (!gst_opencv_parse_iplimage_params_from_caps (incaps, &in_width,
- &in_height, &in_depth, &in_type, &in_channels, &in_err)) {
+ &in_height, &in_depth, &in_channels, &in_err)) {
GST_WARNING_OBJECT (transform, "Failed to parse input caps: %s",
in_err->message);
g_error_free (in_err);
return FALSE;
}
if (!gst_opencv_parse_iplimage_params_from_caps (outcaps, &out_width,
- &out_height, &out_depth, &out_type, &out_channels, &out_err)) {
+ &out_height, &out_depth, &out_channels, &out_err)) {
GST_WARNING_OBJECT (transform, "Failed to parse output caps: %s",
out_err->message);
g_error_free (out_err);
return FALSE;
}
if (transform->cvImage) {
cvReleaseImage (&transform->cvImage);
}
if (transform->out_cvImage) {
cvReleaseImage (&transform->out_cvImage);
}
transform->cvImage =
cvCreateImageHeader (cvSize (in_width, in_height), in_depth, in_channels);
transform->out_cvImage =
cvCreateImageHeader (cvSize (out_width, out_height), out_depth,
out_channels);
gst_base_transform_set_in_place (GST_BASE_TRANSFORM (transform),
transform->in_place);
return TRUE;
}
static gboolean
gst_opencv_base_transform_get_unit_size (GstBaseTransform * trans,
GstCaps * caps, guint * size)
{
gint width, height;
gint bpp;
GstStructure *structure;
structure = gst_caps_get_structure (caps, 0);
if (!gst_structure_get_int (structure, "width", &width) ||
!gst_structure_get_int (structure, "height", &height) ||
!gst_structure_get_int (structure, "bpp", &bpp)) {
return FALSE;
}
*size = width * height * bpp / 8;
return TRUE;
}
static void
gst_opencv_base_transform_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec)
{
switch (prop_id) {
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gst_opencv_base_transform_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec)
{
switch (prop_id) {
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
void
gst_opencv_base_transform_set_in_place (GstOpencvBaseTransform * transform, gboolean ip)
{
transform->in_place = ip;
gst_base_transform_set_in_place (GST_BASE_TRANSFORM (transform), ip);
}
diff --git a/src/gstopencvutils.c b/src/gstopencvutils.c
index 653e3c7..0b58397 100644
--- a/src/gstopencvutils.c
+++ b/src/gstopencvutils.c
@@ -1,82 +1,91 @@
/* GStreamer
* Copyright (C) <2010> Thiago Santos <thiago.sousa.santos@collabora.co.uk>
*
* gstopencvutils.c: miscellaneous utility functions
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#include "gstopencvutils.h"
gboolean
gst_opencv_get_ipl_depth_and_channels (GstStructure * structure,
gint * ipldepth, gint * channels, GError ** err)
{
gint depth, bpp;
- if (gst_structure_has_name (structure, "video/x-raw-rgb")) {
- *channels = 3;
-
- if (!gst_structure_get_int (structure, "depth", &depth) ||
- !gst_structure_get_int (structure, "bpp", &bpp)) {
- g_set_error (err, GST_CORE_ERROR, GST_CORE_ERROR_NEGOTIATION,
- "No depth/bpp in caps");
- return FALSE;
- }
-
- if (depth != bpp) {
- g_set_error (err, GST_CORE_ERROR, GST_CORE_ERROR_NEGOTIATION,
- "Depth and bpp should be equal");
- return FALSE;
- }
+ if (!gst_structure_get_int (structure, "depth", &depth) ||
+ !gst_structure_get_int (structure, "bpp", &bpp)) {
+ g_set_error (err, GST_CORE_ERROR, GST_CORE_ERROR_NEGOTIATION,
+ "No depth/bpp in caps");
+ return FALSE;
+ }
- if (depth == 24) {
- /* TODO signdness? */
- *ipldepth = IPL_DEPTH_8U;
- } else {
- g_set_error (err, GST_CORE_ERROR, GST_CORE_ERROR_NEGOTIATION,
- "Unsupported depth: %d", depth);
- return FALSE;
- }
+ if (depth != bpp) {
+ g_set_error (err, GST_CORE_ERROR, GST_CORE_ERROR_NEGOTIATION,
+ "Depth and bpp should be equal");
+ return FALSE;
+ }
- return TRUE;
+ if (gst_structure_has_name (structure, "video/x-raw-rgb")) {
+ *channels = 3;
+ } else if (gst_structure_has_name (structure, "video/x-raw-gray")) {
+ *channels = 1;
} else {
g_set_error (err, GST_CORE_ERROR, GST_CORE_ERROR_NEGOTIATION,
"Unsupported caps %s", gst_structure_get_name (structure));
return FALSE;
}
+
+ if (depth / *channels == 8) {
+ /* TODO signdness? */
+ *ipldepth = IPL_DEPTH_8U;
+ } else {
+ g_set_error (err, GST_CORE_ERROR, GST_CORE_ERROR_NEGOTIATION,
+ "Unsupported depth/channels %d/%d", depth, *channels);
+ return FALSE;
+ }
+
+ return TRUE;
}
gboolean
-gst_opencv_parse_iplimage_params_from_caps (GstCaps * caps, gint * width,
- gint * height, gint * ipldepth, gint * type, gint * channels, GError ** err)
+gst_opencv_parse_iplimage_params_from_structure (GstStructure * structure,
+ gint * width, gint * height, gint * ipldepth, gint * channels,
+ GError ** err)
{
- GstStructure *structure = gst_caps_get_structure (caps, 0);
-
if (!gst_opencv_get_ipl_depth_and_channels (structure, ipldepth, channels,
err)) {
return FALSE;
}
if (!gst_structure_get_int (structure, "width", width) ||
!gst_structure_get_int (structure, "height", height)) {
g_set_error (err, GST_CORE_ERROR, GST_CORE_ERROR_NEGOTIATION,
"No width/height in caps");
return FALSE;
}
return TRUE;
}
+
+gboolean
+gst_opencv_parse_iplimage_params_from_caps (GstCaps * caps, gint * width,
+ gint * height, gint * ipldepth, gint * channels, GError ** err)
+{
+ return gst_opencv_parse_iplimage_params_from_structure (
+ gst_caps_get_structure (caps, 0), width, height, ipldepth, channels, err);
+}
diff --git a/src/gstopencvutils.h b/src/gstopencvutils.h
index 3438600..d4602a7 100644
--- a/src/gstopencvutils.h
+++ b/src/gstopencvutils.h
@@ -1,39 +1,42 @@
/* GStreamer
* Copyright (C) <2010> Thiago Santos <thiago.sousa.santos@collabora.co.uk>
*
* gstopencvutils.h: miscellaneous utility functions
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#ifndef __GST_OPENCV_UTILS__
#define __GST_OPENCV_UTILS__
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <gst/gst.h>
#include <cv.h>
gboolean
gst_opencv_get_ipldepth (gint depth, gint bpp, gint * ipldepth);
gboolean gst_opencv_parse_iplimage_params_from_caps
- (GstCaps * caps, gint * width, gint * height, gint * depth, gint * type,
+ (GstCaps * caps, gint * width, gint * height, gint * depth,
+ gint * channels, GError ** err);
+gboolean gst_opencv_parse_iplimage_params_from_structure
+ (GstStructure * structure, gint * width, gint * height, gint * depth,
gint * channels, GError ** err);
#endif /* __GST_OPENCV_UTILS__ */
|
Elleo/gst-opencv
|
b1572d22875dbc1828df9e9a327fd39cce5518b7
|
Adding gstopencvutils
|
diff --git a/src/Makefile.am b/src/Makefile.am
index 17c8ddb..739d6e4 100644
--- a/src/Makefile.am
+++ b/src/Makefile.am
@@ -1,43 +1,43 @@
SUBDIRS = basicfilters edgedetect faceblur facedetect pyramidsegment templatematch textwrite
# plugindir is set in configure
plugin_LTLIBRARIES = libgstopencv.la
# sources used to compile this plug-in
-libgstopencv_la_SOURCES = gstopencv.c gstopencvbasetrans.c
+libgstopencv_la_SOURCES = gstopencv.c gstopencvbasetrans.c gstopencvutils.c
# flags used to compile this facedetect
# add other _CFLAGS and _LIBS as needed
libgstopencv_la_CFLAGS = $(GST_CFLAGS) $(GST_BASE_CFLAGS) $(OPENCV_CFLAGS) \
-I${top_srcdir}/src \
-I${top_srcdir}/src/basicfilters \
-I${top_srcdir}/src/edgedetect \
-I${top_srcdir}/src/faceblur \
-I${top_srcdir}/src/facedetect \
-I${top_srcdir}/src/pyramidsegment \
-I${top_srcdir}/src/templatematch \
-I${top_srcdir}/src/textwrite
libgstopencv_la_LIBADD = $(GST_LIBS) $(GST_BASE_LIBS) $(OPENCV_LIBS) \
$(top_builddir)/src/basicfilters/libgstbasicfilters.la \
$(top_builddir)/src/edgedetect/libgstedgedetect.la \
$(top_builddir)/src/faceblur/libgstfaceblur.la \
$(top_builddir)/src/facedetect/libgstfacedetect.la \
$(top_builddir)/src/pyramidsegment/libgstpyramidsegment.la \
$(top_builddir)/src/templatematch/libgsttemplatematch.la \
$(top_builddir)/src/textwrite/libgsttextwrite.la
libgstopencv_la_LDFLAGS = $(GST_PLUGIN_LDFLAGS)
libgstopencv_la_DEPENDENCIES = \
$(top_builddir)/src/basicfilters/libgstbasicfilters.la \
$(top_builddir)/src/edgedetect/libgstedgedetect.la \
$(top_builddir)/src/faceblur/libgstfaceblur.la \
$(top_builddir)/src/facedetect/libgstfacedetect.la \
$(top_builddir)/src/pyramidsegment/libgstpyramidsegment.la \
$(top_builddir)/src/templatematch/libgsttemplatematch.la \
$(top_builddir)/src/textwrite/libgsttextwrite.la
# headers we need but don't want installed
-noinst_HEADERS = gstopencvbasetrans.h
+noinst_HEADERS = gstopencvbasetrans.h gstopencvutils.h
diff --git a/src/gstopencvbasetrans.c b/src/gstopencvbasetrans.c
index 2c85d2b..4dfd586 100644
--- a/src/gstopencvbasetrans.c
+++ b/src/gstopencvbasetrans.c
@@ -1,287 +1,301 @@
/*
* GStreamer
* Copyright (C) 2010 Thiago Santos <thiago.sousa.santos@collabora.co.uk>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/* TODO opencv can do scaling for some cases */
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <gst/gst.h>
#include "gstopencvbasetrans.h"
+#include "gstopencvutils.h"
GST_DEBUG_CATEGORY_STATIC (gst_opencv_base_transform_debug);
#define GST_CAT_DEFAULT gst_opencv_base_transform_debug
/* Filter signals and args */
enum
{
/* FILL ME */
LAST_SIGNAL
};
enum
{
PROP_0
};
static GstElementClass *parent_class = NULL;
static void gst_opencv_base_transform_class_init (GstOpencvBaseTransformClass *
klass);
static void gst_opencv_base_transform_init (GstOpencvBaseTransform * trans,
GstOpencvBaseTransformClass * klass);
static void gst_opencv_base_transform_base_init (gpointer gclass);
static gboolean gst_opencv_base_transform_set_caps (GstBaseTransform * trans,
GstCaps * incaps, GstCaps * outcaps);
static GstFlowReturn gst_opencv_base_transform_transform_ip (GstBaseTransform *
trans, GstBuffer * buf);
static GstFlowReturn gst_opencv_base_transform_transform (GstBaseTransform * trans,
GstBuffer * inbuf, GstBuffer * outbuf);
static gboolean gst_opencv_base_transform_get_unit_size (GstBaseTransform * trans,
GstCaps * caps, guint * size);
static void gst_opencv_base_transform_set_property (GObject * object,
guint prop_id, const GValue * value, GParamSpec * pspec);
static void gst_opencv_base_transform_get_property (GObject * object,
guint prop_id, GValue * value, GParamSpec * pspec);
GType
gst_opencv_base_transform_get_type (void)
{
static volatile gsize opencv_base_transform_type = 0;
if (g_once_init_enter (&opencv_base_transform_type)) {
GType _type;
static const GTypeInfo opencv_base_transform_info = {
sizeof (GstOpencvBaseTransformClass),
(GBaseInitFunc) gst_opencv_base_transform_base_init,
NULL,
(GClassInitFunc) gst_opencv_base_transform_class_init,
NULL,
NULL,
sizeof (GstOpencvBaseTransform),
0,
(GInstanceInitFunc) gst_opencv_base_transform_init,
};
_type = g_type_register_static (GST_TYPE_BASE_TRANSFORM,
"GstOpencvBaseTransform", &opencv_base_transform_info, G_TYPE_FLAG_ABSTRACT);
g_once_init_leave (&opencv_base_transform_type, _type);
}
return opencv_base_transform_type;
}
/* Clean up */
static void
gst_opencv_base_transform_finalize (GObject * obj)
{
GstOpencvBaseTransform *transform = GST_OPENCV_BASE_TRANSFORM (obj);
if (transform->cvImage)
cvReleaseImage (&transform->cvImage);
G_OBJECT_CLASS (parent_class)->finalize (obj);
}
/* GObject vmethod implementations */
static void
gst_opencv_base_transform_base_init (gpointer gclass)
{
}
static void
gst_opencv_base_transform_class_init (GstOpencvBaseTransformClass * klass)
{
GObjectClass *gobject_class;
GstElementClass *gstelement_class;
GstBaseTransformClass *basetrans_class;
gobject_class = (GObjectClass *) klass;
gstelement_class = (GstElementClass *) klass;
basetrans_class = (GstBaseTransformClass *) klass;
parent_class = g_type_class_peek_parent (klass);
GST_DEBUG_CATEGORY_INIT (gst_opencv_base_transform_debug, "opencvbasetransform", 0,
"opencvbasetransform element");
gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_opencv_base_transform_finalize);
gobject_class->set_property = gst_opencv_base_transform_set_property;
gobject_class->get_property = gst_opencv_base_transform_get_property;
basetrans_class->transform = gst_opencv_base_transform_transform;
basetrans_class->transform_ip = gst_opencv_base_transform_transform_ip;
basetrans_class->set_caps = gst_opencv_base_transform_set_caps;
basetrans_class->get_unit_size = gst_opencv_base_transform_get_unit_size;
}
static void
gst_opencv_base_transform_init (GstOpencvBaseTransform * transform,
GstOpencvBaseTransformClass * bclass)
{
}
static GstFlowReturn
gst_opencv_base_transform_transform (GstBaseTransform * trans, GstBuffer * inbuf,
GstBuffer * outbuf)
{
GstOpencvBaseTransform *transform;
GstOpencvBaseTransformClass *fclass;
transform = GST_OPENCV_BASE_TRANSFORM (trans);
fclass = GST_OPENCV_BASE_TRANSFORM_GET_CLASS (transform);
g_return_val_if_fail (fclass->cv_trans_func != NULL, GST_FLOW_ERROR);
g_return_val_if_fail (transform->cvImage != NULL, GST_FLOW_ERROR);
g_return_val_if_fail (transform->out_cvImage != NULL, GST_FLOW_ERROR);
transform->cvImage->imageData = (char *) GST_BUFFER_DATA (inbuf);
transform->out_cvImage->imageData = (char *) GST_BUFFER_DATA (outbuf);
return fclass->cv_trans_func (transform, inbuf, transform->cvImage, outbuf,
transform->out_cvImage);
}
static GstFlowReturn
gst_opencv_base_transform_transform_ip (GstBaseTransform * trans,
GstBuffer * buffer)
{
GstOpencvBaseTransform *transform;
GstOpencvBaseTransformClass *fclass;
transform = GST_OPENCV_BASE_TRANSFORM (trans);
fclass = GST_OPENCV_BASE_TRANSFORM_GET_CLASS (transform);
g_return_val_if_fail (fclass->cv_trans_ip_func != NULL, GST_FLOW_ERROR);
g_return_val_if_fail (transform->cvImage != NULL, GST_FLOW_ERROR);
buffer = gst_buffer_make_writable (buffer);
transform->cvImage->imageData = (char *) GST_BUFFER_DATA (buffer);
/* FIXME how to release buffer? */
return fclass->cv_trans_ip_func (transform, buffer, transform->cvImage);
}
static gboolean
gst_opencv_base_transform_set_caps (GstBaseTransform * trans, GstCaps * incaps,
GstCaps * outcaps)
{
GstOpencvBaseTransform *transform = GST_OPENCV_BASE_TRANSFORM (trans);
- GstStructure *structure;
- gint width, height;
+ gint in_width, in_height;
+ gint in_depth, in_type, in_channels;
+ gint out_width, out_height;
+ gint out_depth, out_type, out_channels;
+ GError *in_err = NULL;
+ GError *out_err = NULL;
+
+ if (!gst_opencv_parse_iplimage_params_from_caps (incaps, &in_width,
+ &in_height, &in_depth, &in_type, &in_channels, &in_err)) {
+ GST_WARNING_OBJECT (transform, "Failed to parse input caps: %s",
+ in_err->message);
+ g_error_free (in_err);
+ return FALSE;
+ }
- structure = gst_caps_get_structure (incaps, 0);
- if (!gst_structure_get_int (structure, "width", &width) ||
- !gst_structure_get_int (structure, "height", &height)) {
- GST_WARNING_OBJECT (transform, "No width/height on caps");
+ if (!gst_opencv_parse_iplimage_params_from_caps (outcaps, &out_width,
+ &out_height, &out_depth, &out_type, &out_channels, &out_err)) {
+ GST_WARNING_OBJECT (transform, "Failed to parse output caps: %s",
+ out_err->message);
+ g_error_free (out_err);
return FALSE;
}
if (transform->cvImage) {
cvReleaseImage (&transform->cvImage);
}
if (transform->out_cvImage) {
cvReleaseImage (&transform->out_cvImage);
}
- /* FIXME - how do we know it is IPL_DEPTH_8U? */
transform->cvImage =
- cvCreateImageHeader (cvSize (width, height), IPL_DEPTH_8U, 3);
+ cvCreateImageHeader (cvSize (in_width, in_height), in_depth, in_channels);
transform->out_cvImage =
- cvCreateImageHeader (cvSize (width, height), IPL_DEPTH_8U, 3);
+ cvCreateImageHeader (cvSize (out_width, out_height), out_depth,
+ out_channels);
gst_base_transform_set_in_place (GST_BASE_TRANSFORM (transform),
transform->in_place);
return TRUE;
}
static gboolean
gst_opencv_base_transform_get_unit_size (GstBaseTransform * trans,
GstCaps * caps, guint * size)
{
gint width, height;
gint bpp;
GstStructure *structure;
structure = gst_caps_get_structure (caps, 0);
if (!gst_structure_get_int (structure, "width", &width) ||
!gst_structure_get_int (structure, "height", &height) ||
!gst_structure_get_int (structure, "bpp", &bpp)) {
return FALSE;
}
*size = width * height * bpp / 8;
return TRUE;
}
static void
gst_opencv_base_transform_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec)
{
switch (prop_id) {
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gst_opencv_base_transform_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec)
{
switch (prop_id) {
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
void
gst_opencv_base_transform_set_in_place (GstOpencvBaseTransform * transform, gboolean ip)
{
transform->in_place = ip;
gst_base_transform_set_in_place (GST_BASE_TRANSFORM (transform), ip);
}
diff --git a/src/gstopencvutils.c b/src/gstopencvutils.c
new file mode 100644
index 0000000..653e3c7
--- /dev/null
+++ b/src/gstopencvutils.c
@@ -0,0 +1,82 @@
+/* GStreamer
+ * Copyright (C) <2010> Thiago Santos <thiago.sousa.santos@collabora.co.uk>
+ *
+ * gstopencvutils.c: miscellaneous utility functions
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+#include "gstopencvutils.h"
+
+gboolean
+gst_opencv_get_ipl_depth_and_channels (GstStructure * structure,
+ gint * ipldepth, gint * channels, GError ** err)
+{
+ gint depth, bpp;
+
+ if (gst_structure_has_name (structure, "video/x-raw-rgb")) {
+ *channels = 3;
+
+ if (!gst_structure_get_int (structure, "depth", &depth) ||
+ !gst_structure_get_int (structure, "bpp", &bpp)) {
+ g_set_error (err, GST_CORE_ERROR, GST_CORE_ERROR_NEGOTIATION,
+ "No depth/bpp in caps");
+ return FALSE;
+ }
+
+ if (depth != bpp) {
+ g_set_error (err, GST_CORE_ERROR, GST_CORE_ERROR_NEGOTIATION,
+ "Depth and bpp should be equal");
+ return FALSE;
+ }
+
+ if (depth == 24) {
+ /* TODO signdness? */
+ *ipldepth = IPL_DEPTH_8U;
+ } else {
+ g_set_error (err, GST_CORE_ERROR, GST_CORE_ERROR_NEGOTIATION,
+ "Unsupported depth: %d", depth);
+ return FALSE;
+ }
+
+ return TRUE;
+ } else {
+ g_set_error (err, GST_CORE_ERROR, GST_CORE_ERROR_NEGOTIATION,
+ "Unsupported caps %s", gst_structure_get_name (structure));
+ return FALSE;
+ }
+}
+
+gboolean
+gst_opencv_parse_iplimage_params_from_caps (GstCaps * caps, gint * width,
+ gint * height, gint * ipldepth, gint * type, gint * channels, GError ** err)
+{
+ GstStructure *structure = gst_caps_get_structure (caps, 0);
+
+ if (!gst_opencv_get_ipl_depth_and_channels (structure, ipldepth, channels,
+ err)) {
+ return FALSE;
+ }
+
+ if (!gst_structure_get_int (structure, "width", width) ||
+ !gst_structure_get_int (structure, "height", height)) {
+ g_set_error (err, GST_CORE_ERROR, GST_CORE_ERROR_NEGOTIATION,
+ "No width/height in caps");
+ return FALSE;
+ }
+
+ return TRUE;
+}
diff --git a/src/gstopencvutils.h b/src/gstopencvutils.h
new file mode 100644
index 0000000..3438600
--- /dev/null
+++ b/src/gstopencvutils.h
@@ -0,0 +1,39 @@
+/* GStreamer
+ * Copyright (C) <2010> Thiago Santos <thiago.sousa.santos@collabora.co.uk>
+ *
+ * gstopencvutils.h: miscellaneous utility functions
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+#ifndef __GST_OPENCV_UTILS__
+#define __GST_OPENCV_UTILS__
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <gst/gst.h>
+#include <cv.h>
+
+gboolean
+gst_opencv_get_ipldepth (gint depth, gint bpp, gint * ipldepth);
+
+gboolean gst_opencv_parse_iplimage_params_from_caps
+ (GstCaps * caps, gint * width, gint * height, gint * depth, gint * type,
+ gint * channels, GError ** err);
+
+#endif /* __GST_OPENCV_UTILS__ */
|
Elleo/gst-opencv
|
b8f1ced0499ca4c696a3afabc12fa0a16c843d32
|
Adding .gitignore files
|
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..27c306f
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,25 @@
+*~
+*.swp
+*.la
+*.lo
+*.o
+.deps/
+.libs/
+aclocal.m4
+autom4te.cache/
+autoregen.sh
+config.guess
+config.h
+config.h.in
+config.log
+config.status
+config.sub
+configure
+depcomp
+install-sh
+libtool
+ltmain.sh
+Makefile
+Makefile.in
+missing
+stamp-h1
|
Elleo/gst-opencv
|
ee213b627eb05ccaef73a924d8c90de2fff78dd3
|
cvsmooth: Adds new element cvsmooth
|
diff --git a/src/Makefile.am b/src/Makefile.am
index 83b4633..17c8ddb 100644
--- a/src/Makefile.am
+++ b/src/Makefile.am
@@ -1,39 +1,43 @@
-SUBDIRS = edgedetect faceblur facedetect pyramidsegment templatematch textwrite
+SUBDIRS = basicfilters edgedetect faceblur facedetect pyramidsegment templatematch textwrite
# plugindir is set in configure
plugin_LTLIBRARIES = libgstopencv.la
# sources used to compile this plug-in
libgstopencv_la_SOURCES = gstopencv.c gstopencvbasetrans.c
# flags used to compile this facedetect
# add other _CFLAGS and _LIBS as needed
libgstopencv_la_CFLAGS = $(GST_CFLAGS) $(GST_BASE_CFLAGS) $(OPENCV_CFLAGS) \
-I${top_srcdir}/src \
+ -I${top_srcdir}/src/basicfilters \
-I${top_srcdir}/src/edgedetect \
-I${top_srcdir}/src/faceblur \
-I${top_srcdir}/src/facedetect \
-I${top_srcdir}/src/pyramidsegment \
-I${top_srcdir}/src/templatematch \
-I${top_srcdir}/src/textwrite
libgstopencv_la_LIBADD = $(GST_LIBS) $(GST_BASE_LIBS) $(OPENCV_LIBS) \
+ $(top_builddir)/src/basicfilters/libgstbasicfilters.la \
+ $(top_builddir)/src/edgedetect/libgstedgedetect.la \
$(top_builddir)/src/faceblur/libgstfaceblur.la \
$(top_builddir)/src/facedetect/libgstfacedetect.la \
$(top_builddir)/src/pyramidsegment/libgstpyramidsegment.la \
$(top_builddir)/src/templatematch/libgsttemplatematch.la \
$(top_builddir)/src/textwrite/libgsttextwrite.la
libgstopencv_la_LDFLAGS = $(GST_PLUGIN_LDFLAGS)
libgstopencv_la_DEPENDENCIES = \
+ $(top_builddir)/src/basicfilters/libgstbasicfilters.la \
$(top_builddir)/src/edgedetect/libgstedgedetect.la \
$(top_builddir)/src/faceblur/libgstfaceblur.la \
$(top_builddir)/src/facedetect/libgstfacedetect.la \
$(top_builddir)/src/pyramidsegment/libgstpyramidsegment.la \
$(top_builddir)/src/templatematch/libgsttemplatematch.la \
$(top_builddir)/src/textwrite/libgsttextwrite.la
# headers we need but don't want installed
noinst_HEADERS = gstopencvbasetrans.h
diff --git a/src/basicfilters/gstcvsmooth.c b/src/basicfilters/gstcvsmooth.c
new file mode 100644
index 0000000..4a3fba7
--- /dev/null
+++ b/src/basicfilters/gstcvsmooth.c
@@ -0,0 +1,336 @@
+/*
+ * GStreamer
+ * Copyright (C) 2010 Thiago Santos <thiago.sousa.santos@collabora.co.uk>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ * Alternatively, the contents of this file may be used under the
+ * GNU Lesser General Public License Version 2.1 (the "LGPL"), in
+ * which case the following provisions apply instead of the ones
+ * mentioned above:
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+#ifdef HAVE_CONFIG_H
+# include <config.h>
+#endif
+
+#include <gst/gst.h>
+
+#include "gstcvsmooth.h"
+
+GST_DEBUG_CATEGORY_STATIC (gst_cv_smooth_debug);
+#define GST_CAT_DEFAULT gst_cv_smooth_debug
+
+static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
+ GST_PAD_SINK,
+ GST_PAD_ALWAYS,
+ GST_STATIC_CAPS ("video/x-raw-rgb, depth=(int)24, bpp=(int)24")
+ );
+
+static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
+ GST_PAD_SRC,
+ GST_PAD_ALWAYS,
+ GST_STATIC_CAPS ("video/x-raw-rgb, depth=(int)24, bpp=(int)24")
+ );
+
+/* Filter signals and args */
+enum
+{
+ /* FILL ME */
+ LAST_SIGNAL
+};
+enum
+{
+ PROP_0,
+ PROP_SMOOTH_TYPE,
+ PROP_PARAM1,
+ PROP_PARAM2,
+ PROP_PARAM3,
+ PROP_PARAM4
+};
+
+#define GST_TYPE_CV_SMOOTH_TYPE (gst_cv_smooth_type_get_type ())
+static GType
+gst_cv_smooth_type_get_type (void)
+{
+ static GType cv_smooth_type_type = 0;
+
+ static const GEnumValue smooth_types[] = {
+ {CV_BLUR_NO_SCALE, "CV Blur No Scale", "blur-no-scale"},
+ {CV_BLUR, "CV Blur", "blur"},
+ {CV_GAUSSIAN, "CV Gaussian", "gaussian"},
+ {CV_MEDIAN, "CV Median", "median"},
+ {CV_BILATERAL, "CV Bilateral", "bilateral"},
+ {0, NULL, NULL},
+ };
+
+ if (!cv_smooth_type_type) {
+ cv_smooth_type_type =
+ g_enum_register_static ("GstCvSmoothTypeType", smooth_types);
+ }
+ return cv_smooth_type_type;
+}
+
+#define DEFAULT_CV_SMOOTH_TYPE CV_GAUSSIAN
+#define DEFAULT_PARAM1 3
+#define DEFAULT_PARAM2 0.0
+#define DEFAULT_PARAM3 0.0
+#define DEFAULT_PARAM4 0.0
+
+GST_BOILERPLATE (GstCvSmooth, gst_cv_smooth, GstOpencvBaseTransform,
+ GST_TYPE_OPENCV_BASE_TRANSFORM);
+
+static void gst_cv_smooth_set_property (GObject * object, guint prop_id,
+ const GValue * value, GParamSpec * pspec);
+static void gst_cv_smooth_get_property (GObject * object, guint prop_id,
+ GValue * value, GParamSpec * pspec);
+
+static GstFlowReturn gst_cv_smooth_transform_ip (GstOpencvBaseTransform * filter,
+ GstBuffer * buf, IplImage * img);
+static GstFlowReturn gst_cv_smooth_transform (GstOpencvBaseTransform * filter,
+ GstBuffer * buf, IplImage * img, GstBuffer * outbuf, IplImage * outimg);
+
+/* Clean up */
+static void
+gst_cv_smooth_finalize (GObject * obj)
+{
+ G_OBJECT_CLASS (parent_class)->finalize (obj);
+}
+
+
+/* GObject vmethod implementations */
+
+static void
+gst_cv_smooth_base_init (gpointer gclass)
+{
+ GstElementClass *element_class = GST_ELEMENT_CLASS (gclass);
+
+ gst_element_class_add_pad_template (element_class,
+ gst_static_pad_template_get (&src_factory));
+ gst_element_class_add_pad_template (element_class,
+ gst_static_pad_template_get (&sink_factory));
+
+ gst_element_class_set_details_simple (element_class,
+ "cvsmooth",
+ "Transform/Effect/Video",
+ "Applies cvSmooth OpenCV function to the image",
+ "Thiago Santos<thiago.sousa.santos@collabora.co.uk>");
+}
+
+/* initialize the cvsmooth's class */
+static void
+gst_cv_smooth_class_init (GstCvSmoothClass * klass)
+{
+ GObjectClass *gobject_class;
+ GstOpencvBaseTransformClass *gstopencvbasefilter_class;
+ GstElementClass *gstelement_class;
+
+ gobject_class = (GObjectClass *) klass;
+ gstelement_class = (GstElementClass *) klass;
+ gstopencvbasefilter_class = (GstOpencvBaseTransformClass *) klass;
+
+ parent_class = g_type_class_peek_parent (klass);
+
+ gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_cv_smooth_finalize);
+ gobject_class->set_property = gst_cv_smooth_set_property;
+ gobject_class->get_property = gst_cv_smooth_get_property;
+
+ gstopencvbasefilter_class->cv_trans_ip_func = gst_cv_smooth_transform_ip;
+ gstopencvbasefilter_class->cv_trans_func = gst_cv_smooth_transform;
+
+ g_object_class_install_property (gobject_class, PROP_SMOOTH_TYPE,
+ g_param_spec_enum ("type",
+ "type",
+ "Smooth Type",
+ GST_TYPE_CV_SMOOTH_TYPE,
+ DEFAULT_CV_SMOOTH_TYPE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)
+ );
+ g_object_class_install_property (gobject_class, PROP_PARAM1,
+ g_param_spec_int ("param1", "param1",
+ "Param1 (Check cvSmooth OpenCV docs)", 1, G_MAXINT, DEFAULT_PARAM1,
+ G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+ g_object_class_install_property (gobject_class, PROP_PARAM2,
+ g_param_spec_int ("param2", "param2",
+ "Param2 (Check cvSmooth OpenCV docs)", 0, G_MAXINT, DEFAULT_PARAM2,
+ G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+ g_object_class_install_property (gobject_class, PROP_PARAM3,
+ g_param_spec_double ("param3", "param3",
+ "Param3 (Check cvSmooth OpenCV docs)", 0, G_MAXDOUBLE, DEFAULT_PARAM3,
+ G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+ g_object_class_install_property (gobject_class, PROP_PARAM4,
+ g_param_spec_double ("param4", "param4",
+ "Param4 (Check cvSmooth OpenCV docs)", 0, G_MAXDOUBLE, DEFAULT_PARAM4,
+ G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+}
+
+/* initialize the new element
+ * instantiate pads and add them to element
+ * set pad calback functions
+ * initialize instance structure
+ */
+static void
+gst_cv_smooth_init (GstCvSmooth * filter, GstCvSmoothClass * gclass)
+{
+ filter->type = DEFAULT_CV_SMOOTH_TYPE;
+ filter->param1 = DEFAULT_PARAM1;
+ filter->param2 = DEFAULT_PARAM2;
+ filter->param3 = DEFAULT_PARAM3;
+ filter->param4 = DEFAULT_PARAM4;
+
+ gst_base_transform_set_in_place (GST_BASE_TRANSFORM (filter), FALSE);
+}
+
+static void
+gst_cv_smooth_change_type (GstCvSmooth * filter, gint value)
+{
+ GST_DEBUG_OBJECT (filter, "Changing type from %d to %d", filter->type, value);
+ if (filter->type == value)
+ return;
+
+ filter->type = value;
+ switch (value) {
+ case CV_GAUSSIAN:
+ case CV_BLUR:
+ gst_base_transform_set_in_place (GST_BASE_TRANSFORM (filter), TRUE);
+ break;
+ default:
+ gst_base_transform_set_in_place (GST_BASE_TRANSFORM (filter), FALSE);
+ break;
+ }
+}
+
+static void
+gst_cv_smooth_set_property (GObject * object, guint prop_id,
+ const GValue * value, GParamSpec * pspec)
+{
+ GstCvSmooth *filter = GST_CV_SMOOTH (object);
+
+ switch (prop_id) {
+ case PROP_SMOOTH_TYPE:
+ gst_cv_smooth_change_type (filter, g_value_get_enum (value));
+ break;
+ case PROP_PARAM1:{
+ gint prop = g_value_get_int (value);
+
+ if (prop % 2 == 1) {
+ filter->param1 = prop;
+ } else {
+ GST_WARNING_OBJECT (filter, "Ignoring value for param1, not odd"
+ "(%d)", prop);
+ }
+ }
+ break;
+ case PROP_PARAM2:{
+ gint prop = g_value_get_int (value);
+
+ if (prop % 2 == 1 || prop == 0) {
+ filter->param1 = prop;
+ } else {
+ GST_WARNING_OBJECT (filter, "Ignoring value for param2, not odd"
+ " nor zero (%d)", prop);
+ }
+ }
+ break;
+ case PROP_PARAM3:
+ filter->param3 = g_value_get_double (value);
+ break;
+ case PROP_PARAM4:
+ filter->param4 = g_value_get_double (value);
+ break;
+ default:
+ G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
+ break;
+ }
+}
+
+static void
+gst_cv_smooth_get_property (GObject * object, guint prop_id,
+ GValue * value, GParamSpec * pspec)
+{
+ GstCvSmooth *filter = GST_CV_SMOOTH (object);
+
+ switch (prop_id) {
+ case PROP_SMOOTH_TYPE:
+ g_value_set_enum (value, filter->type);
+ break;
+ case PROP_PARAM1:
+ g_value_set_int (value, filter->param1);
+ break;
+ case PROP_PARAM2:
+ g_value_set_int (value, filter->param2);
+ break;
+ case PROP_PARAM3:
+ g_value_set_double (value, filter->param3);
+ break;
+ case PROP_PARAM4:
+ g_value_set_double (value, filter->param4);
+ break;
+ default:
+ G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
+ break;
+ }
+}
+
+static GstFlowReturn
+gst_cv_smooth_transform (GstOpencvBaseTransform * base, GstBuffer * buf,
+ IplImage * img, GstBuffer * outbuf, IplImage * outimg)
+{
+ GstCvSmooth *filter = GST_CV_SMOOTH (base);
+
+ cvSmooth (img, outimg, filter->type, filter->param1, filter->param2,
+ filter->param3, filter->param4);
+
+ return GST_FLOW_OK;
+}
+
+static GstFlowReturn
+gst_cv_smooth_transform_ip (GstOpencvBaseTransform * base, GstBuffer * buf,
+ IplImage * img)
+{
+ GstCvSmooth *filter = GST_CV_SMOOTH (base);
+
+ cvSmooth (img, img, filter->type, filter->param1, filter->param2,
+ filter->param3, filter->param4);
+
+ return GST_FLOW_OK;
+}
+
+gboolean
+gst_cv_smooth_plugin_init (GstPlugin * plugin)
+{
+ GST_DEBUG_CATEGORY_INIT (gst_cv_smooth_debug, "cvsmooth", 0, "cvsmooth");
+
+ return gst_element_register (plugin, "cvsmooth", GST_RANK_NONE,
+ GST_TYPE_CV_SMOOTH);
+}
diff --git a/src/basicfilters/gstcvsmooth.h b/src/basicfilters/gstcvsmooth.h
new file mode 100644
index 0000000..448b4b0
--- /dev/null
+++ b/src/basicfilters/gstcvsmooth.h
@@ -0,0 +1,91 @@
+/*
+ * GStreamer
+ * Copyright (C) 2010 Thiago Santos <thiago.sousa.santos@collabora.co.uk>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ * Alternatively, the contents of this file may be used under the
+ * GNU Lesser General Public License Version 2.1 (the "LGPL"), in
+ * which case the following provisions apply instead of the ones
+ * mentioned above:
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+#ifndef __GST_CV_SMOOTH_H__
+#define __GST_CV_SMOOTH_H__
+
+#include <gst/gst.h>
+#include <cv.h>
+#include <gstopencvbasetrans.h>
+
+G_BEGIN_DECLS
+
+/* #defines don't like whitespacey bits */
+#define GST_TYPE_CV_SMOOTH \
+ (gst_cv_smooth_get_type())
+#define GST_CV_SMOOTH(obj) \
+ (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_CV_SMOOTH,GstCvSmooth))
+#define GST_CV_SMOOTH_CLASS(klass) \
+ (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_CV_SMOOTH,GstCvSmoothClass))
+#define GST_IS_CV_SMOOTH(obj) \
+ (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_CV_SMOOTH))
+#define GST_IS_CV_SMOOTH_CLASS(klass) \
+ (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_CV_SMOOTH))
+
+typedef struct _GstCvSmooth GstCvSmooth;
+typedef struct _GstCvSmoothClass GstCvSmoothClass;
+
+struct _GstCvSmooth
+{
+ GstOpencvBaseTransform element;
+
+ gint type;
+
+ gint param1;
+ gint param2;
+ gdouble param3;
+ gdouble param4;
+};
+
+struct _GstCvSmoothClass
+{
+ GstOpencvBaseTransformClass parent_class;
+};
+
+GType gst_cv_smooth_get_type (void);
+
+gboolean gst_cv_smooth_plugin_init (GstPlugin * plugin);
+
+G_END_DECLS
+
+#endif /* __GST_CV_SMOOTH_H__ */
diff --git a/src/gstopencv.c b/src/gstopencv.c
index 120efd8..1c31f29 100644
--- a/src/gstopencv.c
+++ b/src/gstopencv.c
@@ -1,62 +1,65 @@
/* GStreamer
* Copyright (C) <2009> Kapil Agrawal <kapil@mediamagictechnologies.com>
*
* gstopencv.c: plugin registering
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
+#include "gstcvsmooth.h"
#include "gstedgedetect.h"
#include "gstfaceblur.h"
#include "gstfacedetect.h"
#include "gstpyramidsegment.h"
#include "gsttemplatematch.h"
#include "gsttextwrite.h"
static gboolean
plugin_init (GstPlugin * plugin)
{
+ if (!gst_cv_smooth_plugin_init (plugin))
+ return FALSE;
if (!gst_edgedetect_plugin_init (plugin))
return FALSE;
if (!gst_faceblur_plugin_init (plugin))
return FALSE;
if (!gst_facedetect_plugin_init (plugin))
return FALSE;
if (!gst_pyramidsegment_plugin_init (plugin))
return FALSE;
if (!gst_templatematch_plugin_init (plugin))
return FALSE;
if (!gst_textwrite_plugin_init (plugin))
return FALSE;
return TRUE;
}
GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
GST_VERSION_MINOR,
"opencv",
"GStreamer OpenCV Plugins",
plugin_init, VERSION, "LGPL", "OpenCv", "http://opencv.willowgarage.com")
|
Elleo/gst-opencv
|
4962b83afaf49a40576d8caefee54eaea92c2310
|
gstopencvbasetrans: Adds this new base class
|
diff --git a/configure.ac b/configure.ac
index 73c418e..a9eb5f2 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1,165 +1,165 @@
AC_INIT
dnl versions of gstreamer and plugins-base
GST_MAJORMINOR=0.10
GST_REQUIRED=0.10.0
GSTPB_REQUIRED=0.10.0
dnl fill in your package name and version here
dnl the fourth (nano) number should be 0 for a release, 1 for CVS,
dnl and 2... for a prerelease
dnl when going to/from release please set the nano correctly !
dnl releases only do Wall, cvs and prerelease does Werror too
AS_VERSION(gst-opencv, GST_PLUGIN_VERSION, 0, 10, 0, 1,
GST_PLUGIN_CVS="no", GST_PLUGIN_CVS="yes")
dnl AM_MAINTAINER_MODE provides the option to enable maintainer mode
AM_MAINTAINER_MODE
AM_INIT_AUTOMAKE($PACKAGE, $VERSION)
dnl make aclocal work in maintainer mode
AC_SUBST(ACLOCAL_AMFLAGS, "-I m4")
AM_CONFIG_HEADER(config.h)
dnl check for tools
AC_PROG_CC
AC_PROG_LIBTOOL
dnl decide on error flags
AS_COMPILER_FLAG(-Wall, GST_WALL="yes", GST_WALL="no")
if test "x$GST_WALL" = "xyes"; then
GST_ERROR="$GST_ERROR -Wall"
fi
if test "x$GST_PLUGIN_CVS" = "xyes"; then
AS_COMPILER_FLAG(-Werror,GST_ERROR="$GST_ERROR -Werror",GST_ERROR="$GST_ERROR")
fi
dnl Check for pkgconfig first
AC_CHECK_PROG(HAVE_PKGCONFIG, pkg-config, yes, no)
dnl Give error and exit if we don't have pkgconfig
if test "x$HAVE_PKGCONFIG" = "xno"; then
AC_MSG_ERROR(you need to have pkgconfig installed !)
fi
dnl Now we're ready to ask for gstreamer libs and cflags
dnl And we can also ask for the right version of gstreamer
PKG_CHECK_MODULES(GST, \
gstreamer-$GST_MAJORMINOR >= $GST_REQUIRED,
HAVE_GST=yes,HAVE_GST=no)
dnl Give error and exit if we don't have gstreamer
if test "x$HAVE_GST" = "xno"; then
AC_MSG_ERROR(you need gstreamer development packages installed !)
fi
dnl append GST_ERROR cflags to GST_CFLAGS
GST_CFLAGS="$GST_CFLAGS $GST_ERROR"
dnl make GST_CFLAGS and GST_LIBS available
AC_SUBST(GST_CFLAGS)
AC_SUBST(GST_LIBS)
dnl make GST_MAJORMINOR available in Makefile.am
AC_SUBST(GST_MAJORMINOR)
dnl If we need them, we can also use the base class libraries
PKG_CHECK_MODULES(GST_BASE, gstreamer-base-$GST_MAJORMINOR >= $GST_REQUIRED,
HAVE_GST_BASE=yes, HAVE_GST_BASE=no)
dnl Give a warning if we don't have gstreamer libs
dnl you can turn this into an error if you need them
if test "x$HAVE_GST_BASE" = "xno"; then
AC_MSG_NOTICE(no GStreamer base class libraries found (gstreamer-base-$GST_MAJORMINOR))
fi
dnl make _CFLAGS and _LIBS available
AC_SUBST(GST_BASE_CFLAGS)
AC_SUBST(GST_BASE_LIBS)
PKG_CHECK_MODULES(OPENCV,
opencv,
HAVE_OPENCV=yes, HAVE_OPENCV=no)
AC_SUBST(OPENCV_CFLAGS)
AC_SUBST(OPENCV_LIBS)
if test "x$HAVE_OPENCV" = "xno"; then
AC_MSG_ERROR(OpenCV libraries could not be found)
fi
PKG_CHECK_MODULES(SWSCALE,
libswscale,
HAVE_LIBSWSCALE=yes, HAVE_LIBSWSCALE=no)
if test "x$HAVE_LIBSWSCALE" = "xno"; then
AC_MSG_ERROR(libswscale could not be found)
fi
dnl If we need them, we can also use the gstreamer-plugins-base libraries
PKG_CHECK_MODULES(GSTPB_BASE,
gstreamer-plugins-base-$GST_MAJORMINOR >= $GSTPB_REQUIRED,
HAVE_GSTPB_BASE=yes, HAVE_GSTPB_BASE=no)
dnl Give a warning if we don't have gstreamer libs
dnl you can turn this into an error if you need them
if test "x$HAVE_GSTPB_BASE" = "xno"; then
AC_MSG_NOTICE(no GStreamer Plugins Base libraries found (gstreamer-plugins-base-$GST_MAJORMINOR))
fi
dnl make _CFLAGS and _LIBS available
AC_SUBST(GSTPB_BASE_CFLAGS)
AC_SUBST(GSTPB_BASE_LIBS)
dnl If we need them, we can also use the gstreamer-controller libraries
PKG_CHECK_MODULES(GSTCTRL,
gstreamer-controller-$GST_MAJORMINOR >= $GSTPB_REQUIRED,
HAVE_GSTCTRL=yes, HAVE_GSTCTRL=no)
dnl Give a warning if we don't have gstreamer-controller
dnl you can turn this into an error if you need them
if test "x$HAVE_GSTCTRL" = "xno"; then
AC_MSG_NOTICE(no GStreamer Controller libraries found (gstreamer-controller-$GST_MAJORMINOR))
fi
AC_PROG_CXX
AC_LANG_CPLUSPLUS
OLD_CPPFLAGS=$CPPFLAGS
CPPFLAGS=$OPENCV_CFLAGS
AC_CHECK_HEADER(highgui.h, HAVE_HIGHGUI="yes", HAVE_HIGHGUI="no")
if test "x$HAVE_HIGHGUI" = "xno"; then
AC_MSG_ERROR(highgui.h could not be found.)
fi
AC_CHECK_HEADER(cvaux.h, HAVE_CVAUX="yes", HAVE_CVAUX="no")
if test "x$HAVE_CVAUX" = "xno"; then
AC_MSG_ERROR(cvaux.h could not be found.)
fi
CPPFLAGS=$OLD_CPPFLAGS
AC_LANG_C
dnl make _CFLAGS and _LIBS available
AC_SUBST(GSTCTRL_CFLAGS)
AC_SUBST(GSTCTRL_LIBS)
dnl set the plugindir where plugins should be installed
if test "x${prefix}" = "x$HOME"; then
plugindir="$HOME/.gstreamer-$GST_MAJORMINOR/plugins"
else
plugindir="\$(libdir)/gstreamer-$GST_MAJORMINOR"
fi
AC_SUBST(plugindir)
dnl set proper LDFLAGS for plugins
GST_PLUGIN_LDFLAGS='-module -avoid-version -export-symbols-regex [_]*\(gst_\|Gst\|GST_\).*'
AC_SUBST(GST_PLUGIN_LDFLAGS)
-AC_OUTPUT(Makefile m4/Makefile src/Makefile src/edgedetect/Makefile src/faceblur/Makefile src/facedetect/Makefile src/pyramidsegment/Makefile src/templatematch/Makefile src/textwrite/Makefile)
+AC_OUTPUT(Makefile m4/Makefile src/Makefile src/basicfilters/Makefile src/edgedetect/Makefile src/faceblur/Makefile src/facedetect/Makefile src/pyramidsegment/Makefile src/templatematch/Makefile src/textwrite/Makefile)
diff --git a/src/Makefile.am b/src/Makefile.am
index 4c9e575..83b4633 100644
--- a/src/Makefile.am
+++ b/src/Makefile.am
@@ -1,39 +1,39 @@
SUBDIRS = edgedetect faceblur facedetect pyramidsegment templatematch textwrite
# plugindir is set in configure
plugin_LTLIBRARIES = libgstopencv.la
# sources used to compile this plug-in
-libgstopencv_la_SOURCES = gstopencv.c
+libgstopencv_la_SOURCES = gstopencv.c gstopencvbasetrans.c
# flags used to compile this facedetect
# add other _CFLAGS and _LIBS as needed
-libgstopencv_la_CFLAGS = $(GST_CFLAGS) $(OPENCV_CFLAGS) \
+libgstopencv_la_CFLAGS = $(GST_CFLAGS) $(GST_BASE_CFLAGS) $(OPENCV_CFLAGS) \
+ -I${top_srcdir}/src \
-I${top_srcdir}/src/edgedetect \
-I${top_srcdir}/src/faceblur \
-I${top_srcdir}/src/facedetect \
-I${top_srcdir}/src/pyramidsegment \
-I${top_srcdir}/src/templatematch \
-I${top_srcdir}/src/textwrite
-libgstopencv_la_LIBADD = $(GST_LIBS) $(OPENCV_LIBS) \
- $(top_builddir)/src/edgedetect/libgstedgedetect.la \
+libgstopencv_la_LIBADD = $(GST_LIBS) $(GST_BASE_LIBS) $(OPENCV_LIBS) \
$(top_builddir)/src/faceblur/libgstfaceblur.la \
$(top_builddir)/src/facedetect/libgstfacedetect.la \
$(top_builddir)/src/pyramidsegment/libgstpyramidsegment.la \
$(top_builddir)/src/templatematch/libgsttemplatematch.la \
$(top_builddir)/src/textwrite/libgsttextwrite.la
libgstopencv_la_LDFLAGS = $(GST_PLUGIN_LDFLAGS)
libgstopencv_la_DEPENDENCIES = \
$(top_builddir)/src/edgedetect/libgstedgedetect.la \
$(top_builddir)/src/faceblur/libgstfaceblur.la \
$(top_builddir)/src/facedetect/libgstfacedetect.la \
$(top_builddir)/src/pyramidsegment/libgstpyramidsegment.la \
$(top_builddir)/src/templatematch/libgsttemplatematch.la \
$(top_builddir)/src/textwrite/libgsttextwrite.la
# headers we need but don't want installed
-noinst_HEADERS =
+noinst_HEADERS = gstopencvbasetrans.h
diff --git a/src/basicfilters/Makefile.am b/src/basicfilters/Makefile.am
new file mode 100644
index 0000000..fba6ba6
--- /dev/null
+++ b/src/basicfilters/Makefile.am
@@ -0,0 +1,13 @@
+noinst_LTLIBRARIES = libgstbasicfilters.la
+
+# sources used to compile this plug-in
+libgstbasicfilters_la_SOURCES = gstcvsmooth.c
+
+# flags used to compile this pyramidsegment
+# add other _CFLAGS and _LIBS as needed
+libgstbasicfilters_la_CFLAGS = $(GST_CFLAGS) $(OPENCV_CFLAGS) -I..
+libgstbasicfilters_la_LIBADD = $(GST_LIBS) $(OPENCV_LIBS)
+libgstbasicfilters_la_LDFLAGS = $(GST_PLUGIN_LDFLAGS)
+
+# headers we need but don't want installed
+noinst_HEADERS = gstcvsmooth.h
diff --git a/src/gstopencvbasetrans.c b/src/gstopencvbasetrans.c
new file mode 100644
index 0000000..2c85d2b
--- /dev/null
+++ b/src/gstopencvbasetrans.c
@@ -0,0 +1,287 @@
+/*
+ * GStreamer
+ * Copyright (C) 2010 Thiago Santos <thiago.sousa.santos@collabora.co.uk>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ * Alternatively, the contents of this file may be used under the
+ * GNU Lesser General Public License Version 2.1 (the "LGPL"), in
+ * which case the following provisions apply instead of the ones
+ * mentioned above:
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+/* TODO opencv can do scaling for some cases */
+
+#ifdef HAVE_CONFIG_H
+# include <config.h>
+#endif
+
+#include <gst/gst.h>
+
+#include "gstopencvbasetrans.h"
+
+GST_DEBUG_CATEGORY_STATIC (gst_opencv_base_transform_debug);
+#define GST_CAT_DEFAULT gst_opencv_base_transform_debug
+
+/* Filter signals and args */
+enum
+{
+ /* FILL ME */
+ LAST_SIGNAL
+};
+
+enum
+{
+ PROP_0
+};
+
+static GstElementClass *parent_class = NULL;
+
+static void gst_opencv_base_transform_class_init (GstOpencvBaseTransformClass *
+ klass);
+static void gst_opencv_base_transform_init (GstOpencvBaseTransform * trans,
+ GstOpencvBaseTransformClass * klass);
+static void gst_opencv_base_transform_base_init (gpointer gclass);
+
+static gboolean gst_opencv_base_transform_set_caps (GstBaseTransform * trans,
+ GstCaps * incaps, GstCaps * outcaps);
+static GstFlowReturn gst_opencv_base_transform_transform_ip (GstBaseTransform *
+ trans, GstBuffer * buf);
+static GstFlowReturn gst_opencv_base_transform_transform (GstBaseTransform * trans,
+ GstBuffer * inbuf, GstBuffer * outbuf);
+static gboolean gst_opencv_base_transform_get_unit_size (GstBaseTransform * trans,
+ GstCaps * caps, guint * size);
+
+static void gst_opencv_base_transform_set_property (GObject * object,
+ guint prop_id, const GValue * value, GParamSpec * pspec);
+static void gst_opencv_base_transform_get_property (GObject * object,
+ guint prop_id, GValue * value, GParamSpec * pspec);
+
+GType
+gst_opencv_base_transform_get_type (void)
+{
+ static volatile gsize opencv_base_transform_type = 0;
+
+ if (g_once_init_enter (&opencv_base_transform_type)) {
+ GType _type;
+ static const GTypeInfo opencv_base_transform_info = {
+ sizeof (GstOpencvBaseTransformClass),
+ (GBaseInitFunc) gst_opencv_base_transform_base_init,
+ NULL,
+ (GClassInitFunc) gst_opencv_base_transform_class_init,
+ NULL,
+ NULL,
+ sizeof (GstOpencvBaseTransform),
+ 0,
+ (GInstanceInitFunc) gst_opencv_base_transform_init,
+ };
+
+ _type = g_type_register_static (GST_TYPE_BASE_TRANSFORM,
+ "GstOpencvBaseTransform", &opencv_base_transform_info, G_TYPE_FLAG_ABSTRACT);
+ g_once_init_leave (&opencv_base_transform_type, _type);
+ }
+ return opencv_base_transform_type;
+}
+
+/* Clean up */
+static void
+gst_opencv_base_transform_finalize (GObject * obj)
+{
+ GstOpencvBaseTransform *transform = GST_OPENCV_BASE_TRANSFORM (obj);
+
+ if (transform->cvImage)
+ cvReleaseImage (&transform->cvImage);
+
+ G_OBJECT_CLASS (parent_class)->finalize (obj);
+}
+
+/* GObject vmethod implementations */
+static void
+gst_opencv_base_transform_base_init (gpointer gclass)
+{
+}
+
+static void
+gst_opencv_base_transform_class_init (GstOpencvBaseTransformClass * klass)
+{
+ GObjectClass *gobject_class;
+ GstElementClass *gstelement_class;
+ GstBaseTransformClass *basetrans_class;
+
+ gobject_class = (GObjectClass *) klass;
+ gstelement_class = (GstElementClass *) klass;
+ basetrans_class = (GstBaseTransformClass *) klass;
+ parent_class = g_type_class_peek_parent (klass);
+
+ GST_DEBUG_CATEGORY_INIT (gst_opencv_base_transform_debug, "opencvbasetransform", 0,
+ "opencvbasetransform element");
+
+ gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_opencv_base_transform_finalize);
+ gobject_class->set_property = gst_opencv_base_transform_set_property;
+ gobject_class->get_property = gst_opencv_base_transform_get_property;
+
+ basetrans_class->transform = gst_opencv_base_transform_transform;
+ basetrans_class->transform_ip = gst_opencv_base_transform_transform_ip;
+ basetrans_class->set_caps = gst_opencv_base_transform_set_caps;
+ basetrans_class->get_unit_size = gst_opencv_base_transform_get_unit_size;
+}
+
+static void
+gst_opencv_base_transform_init (GstOpencvBaseTransform * transform,
+ GstOpencvBaseTransformClass * bclass)
+{
+}
+
+static GstFlowReturn
+gst_opencv_base_transform_transform (GstBaseTransform * trans, GstBuffer * inbuf,
+ GstBuffer * outbuf)
+{
+ GstOpencvBaseTransform *transform;
+ GstOpencvBaseTransformClass *fclass;
+
+ transform = GST_OPENCV_BASE_TRANSFORM (trans);
+ fclass = GST_OPENCV_BASE_TRANSFORM_GET_CLASS (transform);
+
+ g_return_val_if_fail (fclass->cv_trans_func != NULL, GST_FLOW_ERROR);
+ g_return_val_if_fail (transform->cvImage != NULL, GST_FLOW_ERROR);
+ g_return_val_if_fail (transform->out_cvImage != NULL, GST_FLOW_ERROR);
+
+ transform->cvImage->imageData = (char *) GST_BUFFER_DATA (inbuf);
+ transform->out_cvImage->imageData = (char *) GST_BUFFER_DATA (outbuf);
+ return fclass->cv_trans_func (transform, inbuf, transform->cvImage, outbuf,
+ transform->out_cvImage);
+}
+
+static GstFlowReturn
+gst_opencv_base_transform_transform_ip (GstBaseTransform * trans,
+ GstBuffer * buffer)
+{
+ GstOpencvBaseTransform *transform;
+ GstOpencvBaseTransformClass *fclass;
+
+ transform = GST_OPENCV_BASE_TRANSFORM (trans);
+ fclass = GST_OPENCV_BASE_TRANSFORM_GET_CLASS (transform);
+
+ g_return_val_if_fail (fclass->cv_trans_ip_func != NULL, GST_FLOW_ERROR);
+ g_return_val_if_fail (transform->cvImage != NULL, GST_FLOW_ERROR);
+
+ buffer = gst_buffer_make_writable (buffer);
+
+ transform->cvImage->imageData = (char *) GST_BUFFER_DATA (buffer);
+
+
+ /* FIXME how to release buffer? */
+ return fclass->cv_trans_ip_func (transform, buffer, transform->cvImage);
+}
+
+static gboolean
+gst_opencv_base_transform_set_caps (GstBaseTransform * trans, GstCaps * incaps,
+ GstCaps * outcaps)
+{
+ GstOpencvBaseTransform *transform = GST_OPENCV_BASE_TRANSFORM (trans);
+ GstStructure *structure;
+ gint width, height;
+
+ structure = gst_caps_get_structure (incaps, 0);
+ if (!gst_structure_get_int (structure, "width", &width) ||
+ !gst_structure_get_int (structure, "height", &height)) {
+ GST_WARNING_OBJECT (transform, "No width/height on caps");
+ return FALSE;
+ }
+
+ if (transform->cvImage) {
+ cvReleaseImage (&transform->cvImage);
+ }
+ if (transform->out_cvImage) {
+ cvReleaseImage (&transform->out_cvImage);
+ }
+
+ /* FIXME - how do we know it is IPL_DEPTH_8U? */
+ transform->cvImage =
+ cvCreateImageHeader (cvSize (width, height), IPL_DEPTH_8U, 3);
+ transform->out_cvImage =
+ cvCreateImageHeader (cvSize (width, height), IPL_DEPTH_8U, 3);
+
+ gst_base_transform_set_in_place (GST_BASE_TRANSFORM (transform),
+ transform->in_place);
+ return TRUE;
+}
+
+static gboolean
+gst_opencv_base_transform_get_unit_size (GstBaseTransform * trans,
+ GstCaps * caps, guint * size)
+{
+ gint width, height;
+ gint bpp;
+ GstStructure *structure;
+
+ structure = gst_caps_get_structure (caps, 0);
+
+ if (!gst_structure_get_int (structure, "width", &width) ||
+ !gst_structure_get_int (structure, "height", &height) ||
+ !gst_structure_get_int (structure, "bpp", &bpp)) {
+ return FALSE;
+ }
+ *size = width * height * bpp / 8;
+ return TRUE;
+}
+
+static void
+gst_opencv_base_transform_set_property (GObject * object, guint prop_id,
+ const GValue * value, GParamSpec * pspec)
+{
+ switch (prop_id) {
+ default:
+ G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
+ break;
+ }
+}
+
+static void
+gst_opencv_base_transform_get_property (GObject * object, guint prop_id,
+ GValue * value, GParamSpec * pspec)
+{
+ switch (prop_id) {
+ default:
+ G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
+ break;
+ }
+}
+
+void
+gst_opencv_base_transform_set_in_place (GstOpencvBaseTransform * transform, gboolean ip)
+{
+ transform->in_place = ip;
+ gst_base_transform_set_in_place (GST_BASE_TRANSFORM (transform), ip);
+}
diff --git a/src/gstopencvbasetrans.h b/src/gstopencvbasetrans.h
new file mode 100644
index 0000000..db808a8
--- /dev/null
+++ b/src/gstopencvbasetrans.h
@@ -0,0 +1,98 @@
+/*
+ * GStreamer
+ * Copyright (C) 2010 Thiago Santos <thiago.sousa.santos@collabora.co.uk>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ * Alternatively, the contents of this file may be used under the
+ * GNU Lesser General Public License Version 2.1 (the "LGPL"), in
+ * which case the following provisions apply instead of the ones
+ * mentioned above:
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+#ifndef __GST_OPENCV_BASE_TRANSFORM_H__
+#define __GST_OPENCV_BASE_TRANSFORM_H__
+
+#include <gst/gst.h>
+#include <gst/base/gstbasetransform.h>
+#include <cv.h>
+
+G_BEGIN_DECLS
+/* #defines don't like whitespacey bits */
+#define GST_TYPE_OPENCV_BASE_TRANSFORM \
+ (gst_opencv_base_transform_get_type())
+#define GST_OPENCV_BASE_TRANSFORM(obj) \
+ (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_OPENCV_BASE_TRANSFORM,GstOpencvBaseTransform))
+#define GST_OPENCV_BASE_TRANSFORM_CLASS(klass) \
+ (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_OPENCV_BASE_TRANSFORM,GstOpencvBaseTransformClass))
+#define GST_IS_OPENCV_BASE_TRANSFORM(obj) \
+ (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_OPENCV_BASE_TRANSFORM))
+#define GST_IS_OPENCV_BASE_TRANSFORM_CLASS(klass) \
+ (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_OPENCV_BASE_TRANSFORM))
+#define GST_OPENCV_BASE_TRANSFORM_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj),GST_TYPE_OPENCV_BASE_TRANSFORM,GstOpencvBaseTransformClass))
+
+typedef struct _GstOpencvBaseTransform GstOpencvBaseTransform;
+typedef struct _GstOpencvBaseTransformClass GstOpencvBaseTransformClass;
+
+typedef GstFlowReturn (*GstOpencvBaseTransformTransformIPFunc)
+ (GstOpencvBaseTransform * transform, GstBuffer * buffer, IplImage * img);
+typedef GstFlowReturn (*GstOpencvBaseTransformTransformFunc)
+ (GstOpencvBaseTransform * transform, GstBuffer * buffer, IplImage * img,
+ GstBuffer * outbuf, IplImage * outimg);
+
+struct _GstOpencvBaseTransform
+{
+ GstBaseTransform trans;
+
+ gboolean in_place;
+
+ IplImage *cvImage;
+ IplImage *out_cvImage;
+};
+
+struct _GstOpencvBaseTransformClass
+{
+ GstBaseTransformClass parent_class;
+
+ GstOpencvBaseTransformTransformFunc cv_trans_func;
+ GstOpencvBaseTransformTransformIPFunc cv_trans_ip_func;
+};
+
+GType gst_opencv_base_transform_get_type (void);
+
+void gst_opencv_base_transform_set_in_place (GstOpencvBaseTransform * transform,
+ gboolean ip);
+
+G_END_DECLS
+#endif /* __GST_OPENCV_BASE_TRANSFORM_H__ */
|
Elleo/gst-opencv
|
eecd808be02a6c564031da902a8e32d6ca144ca6
|
Add libcvaux and libhighgui dependencies to debian control file
|
diff --git a/debian/control b/debian/control
index 2b2f8df..496302e 100644
--- a/debian/control
+++ b/debian/control
@@ -1,13 +1,13 @@
Source: gst-opencv
Section: libs
Priority: extra
Maintainer: Noam Lewis <jones.noamle@gmail.com>
-Build-Depends: autoconf (>= 2.52), automake (>= 1.7), libtool (>= 1.5.0), pkg-config (>= 0.11.0), debhelper (>= 7), libcv-dev, libgstreamer-plugins-base0.10-dev, libswscale-dev
+Build-Depends: autoconf (>= 2.52), automake (>= 1.7), libtool (>= 1.5.0), pkg-config (>= 0.11.0), debhelper (>= 7), libcv-dev, libgstreamer-plugins-base0.10-dev, libswscale-dev, libcvaux-dev, libhighgui-dev
Standards-Version: 3.8.0
Homepage: https://launchpad.net/gst-opencv
Package: gst-opencv
Architecture: any
-Depends: ${shlibs:Depends}, ${misc:Depends}, libcv1, gstreamer0.10-plugins-base, libswscale0
+Depends: ${shlibs:Depends}, ${misc:Depends}, libcv1, gstreamer0.10-plugins-base, libswscale0, libcvaux4, libhighgui4
Description: Gstreamer plugins using opencv
A collection of Gstreamer plugins making computer vision techniques from OpenCV available to Gstreamer based applications.
|
Elleo/gst-opencv
|
aa8b8f2ae911f54f1990ac608ae96abd1540335a
|
Add check for highgui.h and cvaux.h (fixes lp:#577562)
|
diff --git a/ChangeLog b/ChangeLog
index 2f6c855..aa398fe 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,109 +1,114 @@
+2010-05-10 Mike Sheldon <mike@mikeasoft.com>
+
+ * configure.ac:
+ Add configure check for highgui.h and cvaux.h
+
2010-04-14 Mike Sheldon <mike@mikeasoft.com>
* configure.ac:
Add configure check for libswscale (patch from Thiago Santos)
2010-02-28 Mike Sheldon <mike@mikeasoft.com>
* AUTHORS:
Update list of contributors
* src/faceblur/gstfaceblur.c:
* src/facedetect/gstfacedetect.c:
Fix leaks which were crashing gst-inspect (patch from Stefan Kost)
2010-02-28 Sreerenj Balachandran <bsreerenj@gmail.com>
* src/textwrite/Makefile.am:
* src/textwrite/gsttextwrite.c:
* src/textwrite/gsttextwrite.h:
* src/gstopencv.c:
* src/Makefile.am:
Add a basic plugin to overlay text on to video streams
2009-12-18 Mike Sheldon <mike@mikeasoft.com>
* src/templatematch/gsttemplatematch.c:
Fix include statements to not include a hard-coded "opencv/" path
2009-05-26 Mike Sheldon <mike@mikeasoft.com>
* AUTHORS:
Add all current contributors to the authors list
* src/edgedetect/gstedgedetect.c:
* src/edgedetect/gstedgedetect.h:
* src/faceblur/gstfaceblur.c:
* src/faceblur/gstfaceblur.h:
* src/facedetect/gstfacedetect.c:
* src/facedetect/gstfacedetect.h:
* src/gstopencv.c:
* src/pyramidsegment/gstpyramidsegment.c:
* src/pyramidsegment/gstpyramidsegment.h:
* src/templatematch/gsttemplatematch.c:
* src/templatematch/gsttemplatematch.h:
Bring code in to line with general gstreamer standards
2009-05-25 Mike Sheldon <mike@mikeasoft.com>
* configure.ac:
* src/Makefile.am:
* src/gstopencv.c:
* src/faceblur/gstfaceblur.c:
* src/faceblur/gstfaceblur.h:
* src/faceblur/Makefile.am:
Add face blurring element
* debian/control:
* debian/changelog:
Fix dependencies and package section for debian package
* src/templatematch/gsttemplatematch.c:
Fix segfault when no template is loaded
Update example launch line to load a template
* examples/python/templatematch.py:
* examples/python/template.jpg:
Add example usage of the template matching element
2009-05-13 Noam Lewis <jones.noamle@gmail.com>
* configure.ac:
* src/Makefile.am:
* src/gstopencv.c:
* src/templatematch/gsttemplatematch.c:
* src/templatematch/gsttemplatematch.h:
* src/tempaltematch/Makefile.am:
Add template matching element
2009-05-08 Kapil Agrawal <kapil@mediamagictechnologies.com>
* configure.ac:
* src/Makefile.am:
* src/gstopencv.c:
* src/edgedetect/Makefile.am:
* src/edgedetect/gstedgedetect.c:
* src/facedetect/Makefile.am:
* src/facedetect/gstfacedetect.c:
* src/pyramidsegment/Makefile.am:
* src/pyramidsegment/gstpyramidsegment.c:
All elements will register as features of opencv plugin.
2009-05-06 Mike Sheldon <mike@mikeasoft.com>
* src/facedetect/gstfacedetect.c:
Fix "profile" parameter in face detect element to accept a string correctly
(was using char param instead of string param)
* src/edgedetect/gstedgedetect.c:
* src/pyramidsegment/gstpyramidsegment.c:
* src/facedetect/gstfacedetect.c:
Release OpenCV images when finalizing
2009-05-06 Kapil Agrawal <kapil@mediamagictechnologies.com>
* configure.ac: Added an error check for opencv.
* src/edgedetect/gstedgedetect.h:
* src/facedetect/gstfacedetect.h:
* src/pyramidsegment/gstpyramidsegment.h: Fixed the included path.
Fixed some compilation errors.
diff --git a/configure.ac b/configure.ac
index ea0da20..73c418e 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1,149 +1,165 @@
AC_INIT
dnl versions of gstreamer and plugins-base
GST_MAJORMINOR=0.10
GST_REQUIRED=0.10.0
GSTPB_REQUIRED=0.10.0
dnl fill in your package name and version here
dnl the fourth (nano) number should be 0 for a release, 1 for CVS,
dnl and 2... for a prerelease
dnl when going to/from release please set the nano correctly !
dnl releases only do Wall, cvs and prerelease does Werror too
AS_VERSION(gst-opencv, GST_PLUGIN_VERSION, 0, 10, 0, 1,
GST_PLUGIN_CVS="no", GST_PLUGIN_CVS="yes")
dnl AM_MAINTAINER_MODE provides the option to enable maintainer mode
AM_MAINTAINER_MODE
AM_INIT_AUTOMAKE($PACKAGE, $VERSION)
dnl make aclocal work in maintainer mode
AC_SUBST(ACLOCAL_AMFLAGS, "-I m4")
AM_CONFIG_HEADER(config.h)
dnl check for tools
AC_PROG_CC
AC_PROG_LIBTOOL
dnl decide on error flags
AS_COMPILER_FLAG(-Wall, GST_WALL="yes", GST_WALL="no")
if test "x$GST_WALL" = "xyes"; then
GST_ERROR="$GST_ERROR -Wall"
fi
if test "x$GST_PLUGIN_CVS" = "xyes"; then
AS_COMPILER_FLAG(-Werror,GST_ERROR="$GST_ERROR -Werror",GST_ERROR="$GST_ERROR")
fi
dnl Check for pkgconfig first
AC_CHECK_PROG(HAVE_PKGCONFIG, pkg-config, yes, no)
dnl Give error and exit if we don't have pkgconfig
if test "x$HAVE_PKGCONFIG" = "xno"; then
AC_MSG_ERROR(you need to have pkgconfig installed !)
fi
dnl Now we're ready to ask for gstreamer libs and cflags
dnl And we can also ask for the right version of gstreamer
PKG_CHECK_MODULES(GST, \
gstreamer-$GST_MAJORMINOR >= $GST_REQUIRED,
HAVE_GST=yes,HAVE_GST=no)
dnl Give error and exit if we don't have gstreamer
if test "x$HAVE_GST" = "xno"; then
AC_MSG_ERROR(you need gstreamer development packages installed !)
fi
dnl append GST_ERROR cflags to GST_CFLAGS
GST_CFLAGS="$GST_CFLAGS $GST_ERROR"
dnl make GST_CFLAGS and GST_LIBS available
AC_SUBST(GST_CFLAGS)
AC_SUBST(GST_LIBS)
dnl make GST_MAJORMINOR available in Makefile.am
AC_SUBST(GST_MAJORMINOR)
dnl If we need them, we can also use the base class libraries
PKG_CHECK_MODULES(GST_BASE, gstreamer-base-$GST_MAJORMINOR >= $GST_REQUIRED,
HAVE_GST_BASE=yes, HAVE_GST_BASE=no)
dnl Give a warning if we don't have gstreamer libs
dnl you can turn this into an error if you need them
if test "x$HAVE_GST_BASE" = "xno"; then
AC_MSG_NOTICE(no GStreamer base class libraries found (gstreamer-base-$GST_MAJORMINOR))
fi
dnl make _CFLAGS and _LIBS available
AC_SUBST(GST_BASE_CFLAGS)
AC_SUBST(GST_BASE_LIBS)
PKG_CHECK_MODULES(OPENCV,
opencv,
HAVE_OPENCV=yes, HAVE_OPENCV=no)
AC_SUBST(OPENCV_CFLAGS)
AC_SUBST(OPENCV_LIBS)
if test "x$HAVE_OPENCV" = "xno"; then
AC_MSG_ERROR(OpenCV libraries could not be found)
fi
PKG_CHECK_MODULES(SWSCALE,
libswscale,
HAVE_LIBSWSCALE=yes, HAVE_LIBSWSCALE=no)
if test "x$HAVE_LIBSWSCALE" = "xno"; then
AC_MSG_ERROR(libswscale could not be found)
fi
dnl If we need them, we can also use the gstreamer-plugins-base libraries
PKG_CHECK_MODULES(GSTPB_BASE,
gstreamer-plugins-base-$GST_MAJORMINOR >= $GSTPB_REQUIRED,
HAVE_GSTPB_BASE=yes, HAVE_GSTPB_BASE=no)
dnl Give a warning if we don't have gstreamer libs
dnl you can turn this into an error if you need them
if test "x$HAVE_GSTPB_BASE" = "xno"; then
AC_MSG_NOTICE(no GStreamer Plugins Base libraries found (gstreamer-plugins-base-$GST_MAJORMINOR))
fi
dnl make _CFLAGS and _LIBS available
AC_SUBST(GSTPB_BASE_CFLAGS)
AC_SUBST(GSTPB_BASE_LIBS)
dnl If we need them, we can also use the gstreamer-controller libraries
PKG_CHECK_MODULES(GSTCTRL,
gstreamer-controller-$GST_MAJORMINOR >= $GSTPB_REQUIRED,
HAVE_GSTCTRL=yes, HAVE_GSTCTRL=no)
dnl Give a warning if we don't have gstreamer-controller
dnl you can turn this into an error if you need them
if test "x$HAVE_GSTCTRL" = "xno"; then
AC_MSG_NOTICE(no GStreamer Controller libraries found (gstreamer-controller-$GST_MAJORMINOR))
fi
+AC_PROG_CXX
+AC_LANG_CPLUSPLUS
+OLD_CPPFLAGS=$CPPFLAGS
+CPPFLAGS=$OPENCV_CFLAGS
+AC_CHECK_HEADER(highgui.h, HAVE_HIGHGUI="yes", HAVE_HIGHGUI="no")
+if test "x$HAVE_HIGHGUI" = "xno"; then
+ AC_MSG_ERROR(highgui.h could not be found.)
+fi
+
+AC_CHECK_HEADER(cvaux.h, HAVE_CVAUX="yes", HAVE_CVAUX="no")
+if test "x$HAVE_CVAUX" = "xno"; then
+ AC_MSG_ERROR(cvaux.h could not be found.)
+fi
+CPPFLAGS=$OLD_CPPFLAGS
+AC_LANG_C
+
dnl make _CFLAGS and _LIBS available
AC_SUBST(GSTCTRL_CFLAGS)
AC_SUBST(GSTCTRL_LIBS)
dnl set the plugindir where plugins should be installed
if test "x${prefix}" = "x$HOME"; then
plugindir="$HOME/.gstreamer-$GST_MAJORMINOR/plugins"
else
plugindir="\$(libdir)/gstreamer-$GST_MAJORMINOR"
fi
AC_SUBST(plugindir)
dnl set proper LDFLAGS for plugins
GST_PLUGIN_LDFLAGS='-module -avoid-version -export-symbols-regex [_]*\(gst_\|Gst\|GST_\).*'
AC_SUBST(GST_PLUGIN_LDFLAGS)
AC_OUTPUT(Makefile m4/Makefile src/Makefile src/edgedetect/Makefile src/faceblur/Makefile src/facedetect/Makefile src/pyramidsegment/Makefile src/templatematch/Makefile src/textwrite/Makefile)
|
Elleo/gst-opencv
|
f4928d8e8936fe115714c7ba389d76ad72b07e2c
|
pyramidsegment: Allocate a new buffer for output
|
diff --git a/src/pyramidsegment/gstpyramidsegment.c b/src/pyramidsegment/gstpyramidsegment.c
index 7e3e8fe..f6a4793 100644
--- a/src/pyramidsegment/gstpyramidsegment.c
+++ b/src/pyramidsegment/gstpyramidsegment.c
@@ -1,325 +1,335 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2008 Michael Sheldon <mike@mikeasoft.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/**
* SECTION:element-pyramidsegment
*
* FIXME:Describe pyramidsegment here.
*
* <refsect2>
* <title>Example launch line</title>
* |[
* gst-launch -v -m fakesrc ! pyramidsegment ! fakesink silent=TRUE
* ]|
* </refsect2>
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <gst/gst.h>
#include "gstpyramidsegment.h"
#define BLOCK_SIZE 1000
GST_DEBUG_CATEGORY_STATIC (gst_pyramidsegment_debug);
#define GST_CAT_DEFAULT gst_pyramidsegment_debug
/* Filter signals and args */
enum
{
/* FILL ME */
LAST_SIGNAL
};
enum
{
PROP_0,
PROP_SILENT,
PROP_THRESHOLD1,
PROP_THRESHOLD2,
PROP_LEVEL
};
/* the capabilities of the inputs and outputs.
*
* describe the real formats here.
*/
static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
GST_PAD_SINK,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("video/x-raw-rgb")
);
static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
GST_PAD_SRC,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("video/x-raw-rgb")
);
GST_BOILERPLATE (Gstpyramidsegment, gst_pyramidsegment, GstElement,
GST_TYPE_ELEMENT);
static void gst_pyramidsegment_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec);
static void gst_pyramidsegment_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec);
static gboolean gst_pyramidsegment_set_caps (GstPad * pad, GstCaps * caps);
static GstFlowReturn gst_pyramidsegment_chain (GstPad * pad, GstBuffer * buf);
/* Clean up */
static void
gst_pyramidsegment_finalize (GObject * obj)
{
Gstpyramidsegment *filter = GST_PYRAMIDSEGMENT (obj);
if (filter->cvImage != NULL) {
cvReleaseImage (&filter->cvImage);
cvReleaseImage (&filter->cvSegmentedImage);
}
G_OBJECT_CLASS (parent_class)->finalize (obj);
}
/* GObject vmethod implementations */
static void
gst_pyramidsegment_base_init (gpointer gclass)
{
GstElementClass *element_class = GST_ELEMENT_CLASS (gclass);
gst_element_class_set_details_simple (element_class,
"pyramidsegment",
"Filter/Effect/Video",
"Applies pyramid segmentation to a video or image.",
"Michael Sheldon <mike@mikeasoft.com>");
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&src_factory));
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&sink_factory));
}
/* initialize the pyramidsegment's class */
static void
gst_pyramidsegment_class_init (GstpyramidsegmentClass * klass)
{
GObjectClass *gobject_class;
GstElementClass *gstelement_class;
gobject_class = (GObjectClass *) klass;
gstelement_class = (GstElementClass *) klass;
parent_class = g_type_class_peek_parent (klass);
gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_pyramidsegment_finalize);
gobject_class->set_property = gst_pyramidsegment_set_property;
gobject_class->get_property = gst_pyramidsegment_get_property;
g_object_class_install_property (gobject_class, PROP_SILENT,
g_param_spec_boolean ("silent", "Silent", "Produce verbose output ?",
FALSE, G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_THRESHOLD1,
g_param_spec_double ("threshold1", "Threshold1",
"Error threshold for establishing links", 0, 1000, 50,
G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_THRESHOLD2,
g_param_spec_double ("threshold2", "Threshold2",
"Error threshold for segment clustering", 0, 1000, 60,
G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_LEVEL,
g_param_spec_int ("level", "Level",
"Maximum level of the pyramid segmentation", 0, 4, 4,
G_PARAM_READWRITE));
}
/* initialize the new element
* instantiate pads and add them to element
* set pad calback functions
* initialize instance structure
*/
static void
gst_pyramidsegment_init (Gstpyramidsegment * filter,
GstpyramidsegmentClass * gclass)
{
filter->sinkpad = gst_pad_new_from_static_template (&sink_factory, "sink");
gst_pad_set_setcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR (gst_pyramidsegment_set_caps));
gst_pad_set_getcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR (gst_pad_proxy_getcaps));
gst_pad_set_chain_function (filter->sinkpad,
GST_DEBUG_FUNCPTR (gst_pyramidsegment_chain));
filter->srcpad = gst_pad_new_from_static_template (&src_factory, "src");
gst_pad_set_getcaps_function (filter->srcpad,
GST_DEBUG_FUNCPTR (gst_pad_proxy_getcaps));
gst_element_add_pad (GST_ELEMENT (filter), filter->sinkpad);
gst_element_add_pad (GST_ELEMENT (filter), filter->srcpad);
filter->storage = cvCreateMemStorage (BLOCK_SIZE);
filter->comp =
cvCreateSeq (0, sizeof (CvSeq), sizeof (CvPoint), filter->storage);
filter->silent = FALSE;
filter->threshold1 = 50.0;
filter->threshold2 = 60.0;
filter->level = 4;
}
static void
gst_pyramidsegment_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec)
{
Gstpyramidsegment *filter = GST_PYRAMIDSEGMENT (object);
switch (prop_id) {
case PROP_SILENT:
filter->silent = g_value_get_boolean (value);
break;
case PROP_THRESHOLD1:
filter->threshold1 = g_value_get_double (value);
break;
case PROP_THRESHOLD2:
filter->threshold2 = g_value_get_double (value);
break;
case PROP_LEVEL:
filter->level = g_value_get_int (value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gst_pyramidsegment_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec)
{
Gstpyramidsegment *filter = GST_PYRAMIDSEGMENT (object);
switch (prop_id) {
case PROP_SILENT:
g_value_set_boolean (value, filter->silent);
break;
case PROP_THRESHOLD1:
g_value_set_double (value, filter->threshold1);
break;
case PROP_THRESHOLD2:
g_value_set_double (value, filter->threshold2);
break;
case PROP_LEVEL:
g_value_set_int (value, filter->level);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
/* GstElement vmethod implementations */
/* this function handles the link with other elements */
static gboolean
gst_pyramidsegment_set_caps (GstPad * pad, GstCaps * caps)
{
Gstpyramidsegment *filter;
GstPad *otherpad;
GstStructure *structure;
gint width, height;
filter = GST_PYRAMIDSEGMENT (gst_pad_get_parent (pad));
structure = gst_caps_get_structure (caps, 0);
gst_structure_get_int (structure, "width", &width);
gst_structure_get_int (structure, "height", &height);
filter->cvImage = cvCreateImage (cvSize (width, height), IPL_DEPTH_8U, 3);
otherpad = (pad == filter->srcpad) ? filter->sinkpad : filter->srcpad;
gst_object_unref (filter);
return gst_pad_set_caps (otherpad, caps);
}
/* chain function
* this function does the actual processing
*/
static GstFlowReturn
gst_pyramidsegment_chain (GstPad * pad, GstBuffer * buf)
{
Gstpyramidsegment *filter;
+ GstBuffer *outbuf;
filter = GST_PYRAMIDSEGMENT (GST_OBJECT_PARENT (pad));
filter->cvImage->imageData = (char *) GST_BUFFER_DATA (buf);
filter->cvSegmentedImage = cvCloneImage (filter->cvImage);
cvPyrSegmentation (filter->cvImage, filter->cvSegmentedImage, filter->storage,
&(filter->comp), filter->level, filter->threshold1, filter->threshold2);
- gst_buffer_set_data (buf, (guint8 *) filter->cvSegmentedImage->imageData,
- filter->cvSegmentedImage->imageSize);
+ /* TODO look if there is a way in opencv to reuse the image data and
+ * delete only the struct headers. Would avoid a memcpy here */
- return gst_pad_push (filter->srcpad, buf);
+ outbuf = gst_buffer_new_and_alloc (filter->cvSegmentedImage->imageSize);
+ gst_buffer_copy_metadata (outbuf, buf, GST_BUFFER_COPY_ALL);
+ memcpy (GST_BUFFER_DATA (outbuf), filter->cvSegmentedImage->imageData,
+ GST_BUFFER_SIZE (outbuf));
+
+ gst_buffer_unref (buf);
+ cvReleaseImage (&filter->cvSegmentedImage);
+ g_assert (filter->cvSegmentedImage == NULL);
+
+ return gst_pad_push (filter->srcpad, outbuf);
}
/* entry point to initialize the plug-in
* initialize the plug-in itself
* register the element factories and other features
*/
gboolean
gst_pyramidsegment_plugin_init (GstPlugin * plugin)
{
/* debug category for fltering log messages */
GST_DEBUG_CATEGORY_INIT (gst_pyramidsegment_debug, "pyramidsegment",
0, "Applies pyramid segmentation to a video or image");
return gst_element_register (plugin, "pyramidsegment", GST_RANK_NONE,
GST_TYPE_PYRAMIDSEGMENT);
}
|
Elleo/gst-opencv
|
efe98eb21b32420e8ef510a8c639a8020e76f23b
|
faceblur: facedetect: templatematch: textwrite: Set buffer to writable
|
diff --git a/src/faceblur/gstfaceblur.c b/src/faceblur/gstfaceblur.c
index a33a708..bceb068 100644
--- a/src/faceblur/gstfaceblur.c
+++ b/src/faceblur/gstfaceblur.c
@@ -1,316 +1,317 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2008 Michael Sheldon <mike@mikeasoft.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/**
* SECTION:element-faceblur
*
* FIXME:Describe faceblur here.
*
* <refsect2>
* <title>Example launch line</title>
* |[
* gst-launch-0.10 videotestsrc ! decodebin ! ffmpegcolorspace ! faceblur ! ffmpegcolorspace ! xvimagesink
* ]|
* </refsect2>
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <gst/gst.h>
#include "gstfaceblur.h"
GST_DEBUG_CATEGORY_STATIC (gst_faceblur_debug);
#define GST_CAT_DEFAULT gst_faceblur_debug
#define DEFAULT_PROFILE "/usr/share/opencv/haarcascades/haarcascade_frontalface_default.xml"
/* Filter signals and args */
enum
{
/* FILL ME */
LAST_SIGNAL
};
enum
{
PROP_0,
PROP_PROFILE
};
/* the capabilities of the inputs and outputs.
*/
static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
GST_PAD_SINK,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("video/x-raw-rgb")
);
static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
GST_PAD_SRC,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("video/x-raw-rgb")
);
GST_BOILERPLATE (Gstfaceblur, gst_faceblur, GstElement, GST_TYPE_ELEMENT);
static void gst_faceblur_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec);
static void gst_faceblur_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec);
static gboolean gst_faceblur_set_caps (GstPad * pad, GstCaps * caps);
static GstFlowReturn gst_faceblur_chain (GstPad * pad, GstBuffer * buf);
static void gst_faceblur_load_profile (Gstfaceblur * filter);
/* Clean up */
static void
gst_faceblur_finalize (GObject * obj)
{
Gstfaceblur *filter = GST_FACEBLUR (obj);
if (filter->cvImage) {
cvReleaseImage (&filter->cvImage);
cvReleaseImage (&filter->cvGray);
}
g_free (filter->profile);
G_OBJECT_CLASS (parent_class)->finalize (obj);
}
/* GObject vmethod implementations */
static void
gst_faceblur_base_init (gpointer gclass)
{
GstElementClass *element_class = GST_ELEMENT_CLASS (gclass);
gst_element_class_set_details_simple (element_class,
"faceblur",
"Filter/Effect/Video",
"Blurs faces in images and videos",
"Michael Sheldon <mike@mikeasoft.com>");
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&src_factory));
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&sink_factory));
}
/* initialize the faceblur's class */
static void
gst_faceblur_class_init (GstfaceblurClass * klass)
{
GObjectClass *gobject_class;
GstElementClass *gstelement_class;
gobject_class = (GObjectClass *) klass;
gstelement_class = (GstElementClass *) klass;
parent_class = g_type_class_peek_parent (klass);
gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_faceblur_finalize);
gobject_class->set_property = gst_faceblur_set_property;
gobject_class->get_property = gst_faceblur_get_property;
g_object_class_install_property (gobject_class, PROP_PROFILE,
g_param_spec_string ("profile", "Profile",
"Location of Haar cascade file to use for face blurion",
DEFAULT_PROFILE, G_PARAM_READWRITE));
}
/* initialize the new element
* instantiate pads and add them to element
* set pad calback functions
* initialize instance structure
*/
static void
gst_faceblur_init (Gstfaceblur * filter, GstfaceblurClass * gclass)
{
filter->sinkpad = gst_pad_new_from_static_template (&sink_factory, "sink");
gst_pad_set_setcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR (gst_faceblur_set_caps));
gst_pad_set_getcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR (gst_pad_proxy_getcaps));
gst_pad_set_chain_function (filter->sinkpad,
GST_DEBUG_FUNCPTR (gst_faceblur_chain));
filter->srcpad = gst_pad_new_from_static_template (&src_factory, "src");
gst_pad_set_getcaps_function (filter->srcpad,
GST_DEBUG_FUNCPTR (gst_pad_proxy_getcaps));
gst_element_add_pad (GST_ELEMENT (filter), filter->sinkpad);
gst_element_add_pad (GST_ELEMENT (filter), filter->srcpad);
filter->profile = g_strdup (DEFAULT_PROFILE);
gst_faceblur_load_profile (filter);
}
static void
gst_faceblur_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec)
{
Gstfaceblur *filter = GST_FACEBLUR (object);
switch (prop_id) {
case PROP_PROFILE:
g_free (filter->profile);
filter->profile = g_value_dup_string (value);
gst_faceblur_load_profile (filter);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gst_faceblur_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec)
{
Gstfaceblur *filter = GST_FACEBLUR (object);
switch (prop_id) {
case PROP_PROFILE:
g_value_set_string (value, filter->profile);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
/* GstElement vmethod implementations */
/* this function handles the link with other elements */
static gboolean
gst_faceblur_set_caps (GstPad * pad, GstCaps * caps)
{
Gstfaceblur *filter;
GstPad *otherpad;
gint width, height;
GstStructure *structure;
filter = GST_FACEBLUR (gst_pad_get_parent (pad));
structure = gst_caps_get_structure (caps, 0);
gst_structure_get_int (structure, "width", &width);
gst_structure_get_int (structure, "height", &height);
filter->cvImage = cvCreateImage (cvSize (width, height), IPL_DEPTH_8U, 3);
filter->cvGray = cvCreateImage (cvSize (width, height), IPL_DEPTH_8U, 1);
filter->cvStorage = cvCreateMemStorage (0);
otherpad = (pad == filter->srcpad) ? filter->sinkpad : filter->srcpad;
gst_object_unref (filter);
return gst_pad_set_caps (otherpad, caps);
}
/* chain function
* this function does the actual processing
*/
static GstFlowReturn
gst_faceblur_chain (GstPad * pad, GstBuffer * buf)
{
Gstfaceblur *filter;
CvSeq *faces;
int i;
filter = GST_FACEBLUR (GST_OBJECT_PARENT (pad));
filter->cvImage->imageData = (char *) GST_BUFFER_DATA (buf);
cvCvtColor (filter->cvImage, filter->cvGray, CV_RGB2GRAY);
cvClearMemStorage (filter->cvStorage);
if (filter->cvCascade) {
faces =
cvHaarDetectObjects (filter->cvGray, filter->cvCascade,
filter->cvStorage, 1.1, 2, 0, cvSize (30, 30));
+ if (faces && faces->total > 0) {
+ buf = gst_buffer_make_writable (buf);
+ }
for (i = 0; i < (faces ? faces->total : 0); i++) {
CvRect *r = (CvRect *) cvGetSeqElem (faces, i);
cvSetImageROI (filter->cvImage, *r);
cvSmooth (filter->cvImage, filter->cvImage, CV_BLUR, 11, 11, 0, 0);
cvSmooth (filter->cvImage, filter->cvImage, CV_GAUSSIAN, 11, 11, 0, 0);
cvResetImageROI (filter->cvImage);
}
-
}
- gst_buffer_set_data (buf, (guint8 *) filter->cvImage->imageData,
- filter->cvImage->imageSize);
+ /* these filters operate in place, so we push the same buffer */
return gst_pad_push (filter->srcpad, buf);
}
static void
gst_faceblur_load_profile (Gstfaceblur * filter)
{
filter->cvCascade =
(CvHaarClassifierCascade *) cvLoad (filter->profile, 0, 0, 0);
if (!filter->cvCascade) {
GST_WARNING ("Couldn't load Haar classifier cascade: %s.", filter->profile);
}
}
/* entry point to initialize the plug-in
* initialize the plug-in itself
* register the element factories and other features
*/
gboolean
gst_faceblur_plugin_init (GstPlugin * plugin)
{
/* debug category for filtering log messages */
GST_DEBUG_CATEGORY_INIT (gst_faceblur_debug, "faceblur",
0, "Blurs faces in images and videos");
return gst_element_register (plugin, "faceblur", GST_RANK_NONE,
GST_TYPE_FACEBLUR);
}
diff --git a/src/facedetect/gstfacedetect.c b/src/facedetect/gstfacedetect.c
index 6494e43..660add6 100644
--- a/src/facedetect/gstfacedetect.c
+++ b/src/facedetect/gstfacedetect.c
@@ -1,345 +1,346 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2008 Michael Sheldon <mike@mikeasoft.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/**
* SECTION:element-facedetect
*
* FIXME:Describe facedetect here.
*
* <refsect2>
* <title>Example launch line</title>
* |[
* gst-launch-0.10 videotestsrc ! decodebin ! ffmpegcolorspace ! facedetect ! ffmpegcolorspace ! xvimagesink
* ]|
* </refsect2>
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <gst/gst.h>
#include "gstfacedetect.h"
GST_DEBUG_CATEGORY_STATIC (gst_facedetect_debug);
#define GST_CAT_DEFAULT gst_facedetect_debug
#define DEFAULT_PROFILE "/usr/share/opencv/haarcascades/haarcascade_frontalface_default.xml"
/* Filter signals and args */
enum
{
/* FILL ME */
LAST_SIGNAL
};
enum
{
PROP_0,
PROP_DISPLAY,
PROP_PROFILE
};
/* the capabilities of the inputs and outputs.
*/
static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
GST_PAD_SINK,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("video/x-raw-rgb")
);
static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
GST_PAD_SRC,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("video/x-raw-rgb")
);
GST_BOILERPLATE (Gstfacedetect, gst_facedetect, GstElement, GST_TYPE_ELEMENT);
static void gst_facedetect_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec);
static void gst_facedetect_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec);
static gboolean gst_facedetect_set_caps (GstPad * pad, GstCaps * caps);
static GstFlowReturn gst_facedetect_chain (GstPad * pad, GstBuffer * buf);
static void gst_facedetect_load_profile (Gstfacedetect * filter);
/* Clean up */
static void
gst_facedetect_finalize (GObject * obj)
{
Gstfacedetect *filter = GST_FACEDETECT (obj);
if (filter->cvImage) {
cvReleaseImage (&filter->cvImage);
cvReleaseImage (&filter->cvGray);
}
g_free (filter->profile);
G_OBJECT_CLASS (parent_class)->finalize (obj);
}
/* GObject vmethod implementations */
static void
gst_facedetect_base_init (gpointer gclass)
{
GstElementClass *element_class = GST_ELEMENT_CLASS (gclass);
gst_element_class_set_details_simple (element_class,
"facedetect",
"Filter/Effect/Video",
"Performs face detection on videos and images, providing detected positions via bus messages",
"Michael Sheldon <mike@mikeasoft.com>");
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&src_factory));
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&sink_factory));
}
/* initialize the facedetect's class */
static void
gst_facedetect_class_init (GstfacedetectClass * klass)
{
GObjectClass *gobject_class;
GstElementClass *gstelement_class;
gobject_class = (GObjectClass *) klass;
gstelement_class = (GstElementClass *) klass;
parent_class = g_type_class_peek_parent (klass);
gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_facedetect_finalize);
gobject_class->set_property = gst_facedetect_set_property;
gobject_class->get_property = gst_facedetect_get_property;
g_object_class_install_property (gobject_class, PROP_DISPLAY,
g_param_spec_boolean ("display", "Display",
"Sets whether the detected faces should be highlighted in the output",
TRUE, G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_PROFILE,
g_param_spec_string ("profile", "Profile",
"Location of Haar cascade file to use for face detection",
DEFAULT_PROFILE, G_PARAM_READWRITE));
}
/* initialize the new element
* instantiate pads and add them to element
* set pad calback functions
* initialize instance structure
*/
static void
gst_facedetect_init (Gstfacedetect * filter, GstfacedetectClass * gclass)
{
filter->sinkpad = gst_pad_new_from_static_template (&sink_factory, "sink");
gst_pad_set_setcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR (gst_facedetect_set_caps));
gst_pad_set_getcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR (gst_pad_proxy_getcaps));
gst_pad_set_chain_function (filter->sinkpad,
GST_DEBUG_FUNCPTR (gst_facedetect_chain));
filter->srcpad = gst_pad_new_from_static_template (&src_factory, "src");
gst_pad_set_getcaps_function (filter->srcpad,
GST_DEBUG_FUNCPTR (gst_pad_proxy_getcaps));
gst_element_add_pad (GST_ELEMENT (filter), filter->sinkpad);
gst_element_add_pad (GST_ELEMENT (filter), filter->srcpad);
filter->profile = g_strdup(DEFAULT_PROFILE);
filter->display = TRUE;
gst_facedetect_load_profile (filter);
}
static void
gst_facedetect_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec)
{
Gstfacedetect *filter = GST_FACEDETECT (object);
switch (prop_id) {
case PROP_PROFILE:
g_free (filter->profile);
filter->profile = g_value_dup_string (value);
gst_facedetect_load_profile (filter);
break;
case PROP_DISPLAY:
filter->display = g_value_get_boolean (value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gst_facedetect_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec)
{
Gstfacedetect *filter = GST_FACEDETECT (object);
switch (prop_id) {
case PROP_PROFILE:
g_value_set_string (value, filter->profile);
break;
case PROP_DISPLAY:
g_value_set_boolean (value, filter->display);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
/* GstElement vmethod implementations */
/* this function handles the link with other elements */
static gboolean
gst_facedetect_set_caps (GstPad * pad, GstCaps * caps)
{
Gstfacedetect *filter;
GstPad *otherpad;
gint width, height;
GstStructure *structure;
filter = GST_FACEDETECT (gst_pad_get_parent (pad));
structure = gst_caps_get_structure (caps, 0);
gst_structure_get_int (structure, "width", &width);
gst_structure_get_int (structure, "height", &height);
filter->cvImage = cvCreateImage (cvSize (width, height), IPL_DEPTH_8U, 3);
filter->cvGray = cvCreateImage (cvSize (width, height), IPL_DEPTH_8U, 1);
filter->cvStorage = cvCreateMemStorage (0);
otherpad = (pad == filter->srcpad) ? filter->sinkpad : filter->srcpad;
gst_object_unref (filter);
return gst_pad_set_caps (otherpad, caps);
}
/* chain function
* this function does the actual processing
*/
static GstFlowReturn
gst_facedetect_chain (GstPad * pad, GstBuffer * buf)
{
Gstfacedetect *filter;
CvSeq *faces;
int i;
filter = GST_FACEDETECT (GST_OBJECT_PARENT (pad));
filter->cvImage->imageData = (char *) GST_BUFFER_DATA (buf);
cvCvtColor (filter->cvImage, filter->cvGray, CV_RGB2GRAY);
cvClearMemStorage (filter->cvStorage);
if (filter->cvCascade) {
faces =
cvHaarDetectObjects (filter->cvGray, filter->cvCascade,
filter->cvStorage, 1.1, 2, 0, cvSize (30, 30));
+ if (filter->display && faces && faces->total > 0) {
+ buf = gst_buffer_make_writable (buf);
+ }
+
for (i = 0; i < (faces ? faces->total : 0); i++) {
CvRect *r = (CvRect *) cvGetSeqElem (faces, i);
GstStructure *s = gst_structure_new ("face",
"x", G_TYPE_UINT, r->x,
"y", G_TYPE_UINT, r->y,
"width", G_TYPE_UINT, r->width,
"height", G_TYPE_UINT, r->height, NULL);
GstMessage *m = gst_message_new_element (GST_OBJECT (filter), s);
gst_element_post_message (GST_ELEMENT (filter), m);
if (filter->display) {
CvPoint center;
int radius;
center.x = cvRound ((r->x + r->width * 0.5));
center.y = cvRound ((r->y + r->height * 0.5));
radius = cvRound ((r->width + r->height) * 0.25);
cvCircle (filter->cvImage, center, radius, CV_RGB (255, 32, 32), 3, 8,
0);
}
}
}
- gst_buffer_set_data (buf, (guint8 *) filter->cvImage->imageData,
- filter->cvImage->imageSize);
-
return gst_pad_push (filter->srcpad, buf);
}
static void
gst_facedetect_load_profile (Gstfacedetect * filter)
{
filter->cvCascade =
(CvHaarClassifierCascade *) cvLoad (filter->profile, 0, 0, 0);
if (!filter->cvCascade) {
GST_WARNING ("Couldn't load Haar classifier cascade: %s.", filter->profile);
}
}
/* entry point to initialize the plug-in
* initialize the plug-in itself
* register the element factories and other features
*/
gboolean
gst_facedetect_plugin_init (GstPlugin * plugin)
{
/* debug category for fltering log messages */
GST_DEBUG_CATEGORY_INIT (gst_facedetect_debug, "facedetect",
0,
"Performs face detection on videos and images, providing detected positions via bus messages");
return gst_element_register (plugin, "facedetect", GST_RANK_NONE,
GST_TYPE_FACEDETECT);
}
diff --git a/src/templatematch/gsttemplatematch.c b/src/templatematch/gsttemplatematch.c
index 6dad35b..3821020 100644
--- a/src/templatematch/gsttemplatematch.c
+++ b/src/templatematch/gsttemplatematch.c
@@ -1,412 +1,412 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2008 Michael Sheldon <mike@mikeasoft.com>
* Copyright (C) 2009 Noam Lewis <jones.noamle@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/**
* SECTION:element-templatematch
*
* FIXME:Describe templatematch here.
*
* <refsect2>
* <title>Example launch line</title>
* |[
* gst-launch-0.10 videotestsrc ! decodebin ! ffmpegcolorspace ! templatematch template=/path/to/file.jpg ! ffmpegcolorspace ! xvimagesink
* ]|
* </refsect2>
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <gst/gst.h>
#include "gsttemplatematch.h"
GST_DEBUG_CATEGORY_STATIC (gst_templatematch_debug);
#define GST_CAT_DEFAULT gst_templatematch_debug
#define DEFAULT_METHOD (3)
/* Filter signals and args */
enum
{
/* FILL ME */
LAST_SIGNAL
};
enum
{
PROP_0,
PROP_METHOD,
PROP_TEMPLATE,
PROP_DISPLAY,
};
/* the capabilities of the inputs and outputs.
*/
static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
GST_PAD_SINK,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("video/x-raw-rgb")
);
static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
GST_PAD_SRC,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("video/x-raw-rgb")
);
GST_BOILERPLATE (GstTemplateMatch, gst_templatematch, GstElement,
GST_TYPE_ELEMENT);
static void gst_templatematch_finalize (GObject * object);
static void gst_templatematch_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec);
static void gst_templatematch_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec);
static gboolean gst_templatematch_set_caps (GstPad * pad, GstCaps * caps);
static GstFlowReturn gst_templatematch_chain (GstPad * pad, GstBuffer * buf);
static void gst_templatematch_load_template (GstTemplateMatch * filter);
static void gst_templatematch_match (IplImage * input, IplImage * template,
IplImage * dist_image, double *best_res, CvPoint * best_pos, int method);
/* GObject vmethod implementations */
static void
gst_templatematch_base_init (gpointer gclass)
{
GstElementClass *element_class = GST_ELEMENT_CLASS (gclass);
gst_element_class_set_details_simple (element_class,
"templatematch",
"Filter/Effect/Video",
"Performs template matching on videos and images, providing detected positions via bus messages",
"Noam Lewis <jones.noamle@gmail.com>");
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&src_factory));
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&sink_factory));
}
/* initialize the templatematch's class */
static void
gst_templatematch_class_init (GstTemplateMatchClass * klass)
{
GObjectClass *gobject_class;
GstElementClass *gstelement_class;
gobject_class = (GObjectClass *) klass;
gstelement_class = (GstElementClass *) klass;
gobject_class->finalize = gst_templatematch_finalize;
gobject_class->set_property = gst_templatematch_set_property;
gobject_class->get_property = gst_templatematch_get_property;
g_object_class_install_property (gobject_class, PROP_METHOD,
g_param_spec_int ("method", "Method",
"Specifies the way the template must be compared with image regions. 0=SQDIFF, 1=SQDIFF_NORMED, 2=CCOR, 3=CCOR_NORMED, 4=CCOEFF, 5=CCOEFF_NORMED.",
0, 5, DEFAULT_METHOD, G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_TEMPLATE,
g_param_spec_string ("template", "Template", "Filename of template image",
NULL, G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_DISPLAY,
g_param_spec_boolean ("display", "Display",
"Sets whether the detected template should be highlighted in the output",
TRUE, G_PARAM_READWRITE));
}
/* initialize the new element
* instantiate pads and add them to element
* set pad calback functions
* initialize instance structure
*/
static void
gst_templatematch_init (GstTemplateMatch * filter,
GstTemplateMatchClass * gclass)
{
filter->sinkpad = gst_pad_new_from_static_template (&sink_factory, "sink");
gst_pad_set_setcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR (gst_templatematch_set_caps));
gst_pad_set_getcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR (gst_pad_proxy_getcaps));
gst_pad_set_chain_function (filter->sinkpad,
GST_DEBUG_FUNCPTR (gst_templatematch_chain));
filter->srcpad = gst_pad_new_from_static_template (&src_factory, "src");
gst_pad_set_getcaps_function (filter->srcpad,
GST_DEBUG_FUNCPTR (gst_pad_proxy_getcaps));
gst_element_add_pad (GST_ELEMENT (filter), filter->sinkpad);
gst_element_add_pad (GST_ELEMENT (filter), filter->srcpad);
filter->template = NULL;
filter->display = TRUE;
filter->cvTemplateImage = NULL;
filter->cvDistImage = NULL;
filter->cvImage = NULL;
filter->method = DEFAULT_METHOD;
gst_templatematch_load_template (filter);
}
static void
gst_templatematch_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec)
{
GstTemplateMatch *filter = GST_TEMPLATEMATCH (object);
switch (prop_id) {
case PROP_METHOD:
switch (g_value_get_int (value)) {
case 0:
filter->method = CV_TM_SQDIFF;
break;
case 1:
filter->method = CV_TM_SQDIFF_NORMED;
break;
case 2:
filter->method = CV_TM_CCORR;
break;
case 3:
filter->method = CV_TM_CCORR_NORMED;
break;
case 4:
filter->method = CV_TM_CCOEFF;
break;
case 5:
filter->method = CV_TM_CCOEFF_NORMED;
break;
}
break;
case PROP_TEMPLATE:
filter->template = (char *) g_value_get_string (value);
gst_templatematch_load_template (filter);
break;
case PROP_DISPLAY:
filter->display = g_value_get_boolean (value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gst_templatematch_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec)
{
GstTemplateMatch *filter = GST_TEMPLATEMATCH (object);
switch (prop_id) {
case PROP_METHOD:
g_value_set_int (value, filter->method);
break;
case PROP_TEMPLATE:
g_value_set_string (value, filter->template);
break;
case PROP_DISPLAY:
g_value_set_boolean (value, filter->display);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
/* GstElement vmethod implementations */
/* this function handles the link with other elements */
static gboolean
gst_templatematch_set_caps (GstPad * pad, GstCaps * caps)
{
GstTemplateMatch *filter;
GstPad *otherpad;
gint width, height;
GstStructure *structure;
filter = GST_TEMPLATEMATCH (gst_pad_get_parent (pad));
structure = gst_caps_get_structure (caps, 0);
gst_structure_get_int (structure, "width", &width);
gst_structure_get_int (structure, "height", &height);
filter->cvImage =
cvCreateImageHeader (cvSize (width, height), IPL_DEPTH_8U, 3);
otherpad = (pad == filter->srcpad) ? filter->sinkpad : filter->srcpad;
gst_object_unref (filter);
return gst_pad_set_caps (otherpad, caps);
}
static void
gst_templatematch_finalize (GObject * object)
{
GstTemplateMatch *filter;
filter = GST_TEMPLATEMATCH (object);
if (filter->cvImage) {
cvReleaseImageHeader (&filter->cvImage);
}
if (filter->cvDistImage) {
cvReleaseImage (&filter->cvDistImage);
}
if (filter->cvTemplateImage) {
cvReleaseImage (&filter->cvTemplateImage);
}
}
/* chain function
* this function does the actual processing
*/
static GstFlowReturn
gst_templatematch_chain (GstPad * pad, GstBuffer * buf)
{
GstTemplateMatch *filter;
CvPoint best_pos;
double best_res;
filter = GST_TEMPLATEMATCH (GST_OBJECT_PARENT (pad));
- buf = gst_buffer_make_writable (buf);
+
+ /* FIXME Why template == NULL returns OK?
+ * shouldn't it be a passthrough instead? */
if ((!filter) || (!buf) || filter->template == NULL) {
return GST_FLOW_OK;
}
filter->cvImage->imageData = (char *) GST_BUFFER_DATA (buf);
-
if (!filter->cvDistImage) {
filter->cvDistImage =
cvCreateImage (cvSize (filter->cvImage->width -
filter->cvTemplateImage->width + 1,
filter->cvImage->height - filter->cvTemplateImage->height + 1),
IPL_DEPTH_32F, 1);
if (!filter->cvDistImage) {
GST_WARNING ("Couldn't create dist image.");
}
}
if (filter->cvTemplateImage) {
gst_templatematch_match (filter->cvImage, filter->cvTemplateImage,
filter->cvDistImage, &best_res, &best_pos, filter->method);
GstStructure *s = gst_structure_new ("template_match",
"x", G_TYPE_UINT, best_pos.x,
"y", G_TYPE_UINT, best_pos.y,
"width", G_TYPE_UINT, filter->cvTemplateImage->width,
"height", G_TYPE_UINT, filter->cvTemplateImage->height,
"result", G_TYPE_DOUBLE, best_res,
NULL);
GstMessage *m = gst_message_new_element (GST_OBJECT (filter), s);
gst_element_post_message (GST_ELEMENT (filter), m);
if (filter->display) {
CvPoint corner = best_pos;
+
+ buf = gst_buffer_make_writable (buf);
+
corner.x += filter->cvTemplateImage->width;
corner.y += filter->cvTemplateImage->height;
cvRectangle (filter->cvImage, best_pos, corner, CV_RGB (255, 32, 32), 3,
8, 0);
}
}
-
- gst_buffer_set_data (buf, (guint8 *) filter->cvImage->imageData,
- filter->cvImage->imageSize);
-
return gst_pad_push (filter->srcpad, buf);
}
static void
gst_templatematch_match (IplImage * input, IplImage * template,
IplImage * dist_image, double *best_res, CvPoint * best_pos, int method)
{
double dist_min = 0, dist_max = 0;
CvPoint min_pos, max_pos;
cvMatchTemplate (input, template, dist_image, method);
cvMinMaxLoc (dist_image, &dist_min, &dist_max, &min_pos, &max_pos, NULL);
if ((CV_TM_SQDIFF_NORMED == method) || (CV_TM_SQDIFF == method)) {
*best_res = dist_min;
*best_pos = min_pos;
if (CV_TM_SQDIFF_NORMED == method) {
*best_res = 1 - *best_res;
}
} else {
*best_res = dist_max;
*best_pos = max_pos;
}
}
static void
gst_templatematch_load_template (GstTemplateMatch * filter)
{
if (filter->template) {
filter->cvTemplateImage =
cvLoadImage (filter->template, CV_LOAD_IMAGE_COLOR);
if (!filter->cvTemplateImage) {
GST_WARNING ("Couldn't load template image: %s.", filter->template);
}
}
}
/* entry point to initialize the plug-in
* initialize the plug-in itself
* register the element factories and other features
*/
gboolean
gst_templatematch_plugin_init (GstPlugin * templatematch)
{
/* debug category for fltering log messages */
GST_DEBUG_CATEGORY_INIT (gst_templatematch_debug, "templatematch",
0,
"Performs template matching on videos and images, providing detected positions via bus messages");
return gst_element_register (templatematch, "templatematch", GST_RANK_NONE,
GST_TYPE_TEMPLATEMATCH);
}
diff --git a/src/textwrite/gsttextwrite.c b/src/textwrite/gsttextwrite.c
index 7e56846..287de3f 100644
--- a/src/textwrite/gsttextwrite.c
+++ b/src/textwrite/gsttextwrite.c
@@ -1,414 +1,412 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2010 Sreerenj Balachandran <bsreerenj@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/**
* SECTION:element-textwrite
*
* FIXME:Describe textwrite here.
*
* <refsect2>
* <title>Example launch line</title>
* |[
* gst-launch -v -m fakesrc ! textwrite ! fakesink silent=TRUE
* ]|
* </refsect2>
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <gst/gst.h>
#include "gsttextwrite.h"
GST_DEBUG_CATEGORY_STATIC (gst_textwrite_debug);
#define GST_CAT_DEFAULT gst_textwrite_debug
#define DEFAULT_PROP_TEXT ""
#define DEFAULT_PROP_WIDTH 1
#define DEFAULT_PROP_HEIGHT 1
#define DEFAULT_PROP_XPOS 50
#define DEFAULT_PROP_YPOS 50
#define DEFAULT_PROP_THICKNESS 2
#define DEFAULT_PROP_COLOR 0
/* Filter signals and args */
enum
{
/* FILL ME */
LAST_SIGNAL
};
#define DEFAULT_WIDTH 1.0
#define DEFAULT_HEIGHT 1.0
enum
{
PROP_0,
PROP_XPOS,
PROP_YPOS,
PROP_THICKNESS,
PROP_COLOR_R,
PROP_COLOR_G,
PROP_COLOR_B,
PROP_TEXT,
PROP_HEIGHT,
PROP_WIDTH
};
/* the capabilities of the inputs and outputs.
*
* describe the real formats here.
*/
static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
GST_PAD_SINK,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("video/x-raw-rgb")
);
static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
GST_PAD_SRC,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("ANY")
);
GST_BOILERPLATE (Gsttextwrite, gst_textwrite, GstElement,GST_TYPE_ELEMENT);
static void gst_textwrite_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec);
static void gst_textwrite_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec);
static gboolean gst_textwrite_set_caps (GstPad * pad, GstCaps * caps);
static GstFlowReturn gst_textwrite_chain (GstPad * pad, GstBuffer * buf);
/* Clean up */
static void
gst_textwrite_finalize (GObject * obj)
{
Gsttextwrite *filter = GST_textwrite (obj);
if (filter->cvImage) {
cvReleaseImage (&filter->cvImage);
}
G_OBJECT_CLASS (parent_class)->finalize (obj);
}
/* GObject vmethod implementations */
static void
gst_textwrite_base_init (gpointer gclass)
{
GstElementClass *element_class = GST_ELEMENT_CLASS (gclass);
gst_element_class_set_details_simple(element_class,
"textwrite",
"Filter/Effect/Video",
"Performs text writing to the video",
"sreerenj<bsreerenj@gmail.com>");
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&src_factory));
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&sink_factory));
}
/* initialize the textwrite's class */
static void
gst_textwrite_class_init (GsttextwriteClass * klass)
{
GObjectClass *gobject_class;
GstElementClass *gstelement_class;
gobject_class = (GObjectClass *) klass;
gstelement_class = (GstElementClass *) klass;
parent_class = g_type_class_peek_parent (klass);
gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_textwrite_finalize);
gobject_class->set_property = gst_textwrite_set_property;
gobject_class->get_property = gst_textwrite_get_property;
g_object_class_install_property (gobject_class, PROP_TEXT,
g_param_spec_string ("text", "text",
"Text to be display.", DEFAULT_PROP_TEXT,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
g_object_class_install_property (gobject_class, PROP_XPOS,
g_param_spec_int ("xpos", "horizontal position",
"Sets the Horizontal position", 0, G_MAXINT,
DEFAULT_PROP_XPOS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
g_object_class_install_property (gobject_class, PROP_YPOS,
g_param_spec_int ("ypos", "vertical position",
"Sets the Vertical position", 0, G_MAXINT,
DEFAULT_PROP_YPOS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
g_object_class_install_property (gobject_class, PROP_THICKNESS,
g_param_spec_int ("thickness", "font thickness",
"Sets the Thickness of Font", 0, G_MAXINT,
DEFAULT_PROP_THICKNESS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
g_object_class_install_property (gobject_class, PROP_COLOR_R,
g_param_spec_int ("colorR", "color -Red ",
"Sets the color -R", 0, 255,
DEFAULT_PROP_COLOR, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
g_object_class_install_property (gobject_class, PROP_COLOR_G,
g_param_spec_int ("colorG", "color -Green",
"Sets the color -G", 0, 255,
DEFAULT_PROP_COLOR, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
g_object_class_install_property (gobject_class, PROP_COLOR_B,
g_param_spec_int ("colorB", "color -Blue",
"Sets the color -B", 0, 255,
DEFAULT_PROP_COLOR, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
g_object_class_install_property (gobject_class, PROP_HEIGHT,
g_param_spec_double ("height", "Height",
"Sets the height of fonts",1.0,5.0,
DEFAULT_HEIGHT, G_PARAM_READWRITE|G_PARAM_STATIC_STRINGS));
g_object_class_install_property (gobject_class, PROP_WIDTH,
g_param_spec_double ("width", "Width",
"Sets the width of fonts",1.0,5.0,
DEFAULT_WIDTH, G_PARAM_READWRITE| G_PARAM_STATIC_STRINGS));
}
/* initialize the new element
* instantiate pads and add them to element
* set pad calback functions
* initialize instance structure
*/
static void
gst_textwrite_init (Gsttextwrite * filter,
GsttextwriteClass * gclass)
{
filter->sinkpad = gst_pad_new_from_static_template (&sink_factory, "sink");
gst_pad_set_setcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR(gst_textwrite_set_caps));
gst_pad_set_getcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR(gst_pad_proxy_getcaps));
gst_pad_set_chain_function (filter->sinkpad,
GST_DEBUG_FUNCPTR(gst_textwrite_chain));
filter->srcpad = gst_pad_new_from_static_template (&src_factory, "src");
gst_pad_set_getcaps_function (filter->srcpad,
GST_DEBUG_FUNCPTR(gst_pad_proxy_getcaps));
gst_element_add_pad (GST_ELEMENT (filter), filter->sinkpad);
gst_element_add_pad (GST_ELEMENT (filter), filter->srcpad);
filter->textbuf = g_strdup (DEFAULT_PROP_TEXT);
filter->width = DEFAULT_PROP_WIDTH;
filter->height = DEFAULT_PROP_HEIGHT;
filter->xpos = DEFAULT_PROP_XPOS;
filter->ypos = DEFAULT_PROP_YPOS;
filter->thickness = DEFAULT_PROP_THICKNESS;
filter->colorR = DEFAULT_PROP_COLOR;
filter->colorG = DEFAULT_PROP_COLOR;
filter->colorB = DEFAULT_PROP_COLOR;
}
static void
gst_textwrite_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec)
{
Gsttextwrite *filter = GST_textwrite (object);
switch (prop_id) {
case PROP_TEXT:
g_free (filter->textbuf);
filter->textbuf = g_value_dup_string (value);
break;
case PROP_XPOS:
filter->xpos = g_value_get_int(value);
break;
case PROP_YPOS:
filter->ypos = g_value_get_int(value);
break;
case PROP_THICKNESS:
filter->thickness = g_value_get_int(value);
break;
case PROP_COLOR_R:
filter->colorR = g_value_get_int(value);
break;
case PROP_COLOR_G:
filter->colorG = g_value_get_int(value);
break;
case PROP_COLOR_B:
filter->colorB = g_value_get_int(value);
break;
case PROP_HEIGHT:
filter->height = g_value_get_double(value);
break;
case PROP_WIDTH:
filter->width = g_value_get_double(value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gst_textwrite_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec)
{
Gsttextwrite *filter = GST_textwrite (object);
switch (prop_id) {
case PROP_TEXT:
g_value_set_string (value, filter->textbuf);
break;
case PROP_XPOS:
g_value_set_int (value, filter->xpos);
break;
case PROP_YPOS:
g_value_set_int (value, filter->ypos);
break;
case PROP_THICKNESS:
g_value_set_int (value, filter->thickness);
break;
case PROP_COLOR_R:
g_value_set_int (value, filter->colorR);
break;
case PROP_COLOR_G:
g_value_set_int (value, filter->colorG);
break;
case PROP_COLOR_B:
g_value_set_int (value, filter->colorB);
break;
case PROP_HEIGHT:
g_value_set_double (value, filter->height);
break;
case PROP_WIDTH:
g_value_set_double (value, filter->width);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
/* GstElement vmethod implementations */
/* this function handles the link with other elements */
static gboolean
gst_textwrite_set_caps (GstPad * pad, GstCaps * caps)
{
Gsttextwrite *filter;
GstPad *otherpad;
gint width, height;
GstStructure *structure;
filter = GST_textwrite (gst_pad_get_parent (pad));
structure = gst_caps_get_structure (caps, 0);
gst_structure_get_int (structure, "width", &width);
gst_structure_get_int (structure, "height", &height);
filter->cvImage = cvCreateImage (cvSize (width, height), IPL_DEPTH_8U, 3);
filter->cvStorage = cvCreateMemStorage (0);
otherpad = (pad == filter->srcpad) ? filter->sinkpad : filter->srcpad;
gst_object_unref (filter);
return gst_pad_set_caps (otherpad, caps);
}
/* chain function
* this function does the actual processing
*/
static GstFlowReturn
gst_textwrite_chain (GstPad * pad, GstBuffer * buf)
{
Gsttextwrite *filter;
filter = GST_textwrite (GST_OBJECT_PARENT (pad));
filter->cvImage->imageData = (char *) GST_BUFFER_DATA (buf);
cvInitFont(&(filter->font),CV_FONT_VECTOR0, filter->width,filter->height,0,filter->thickness,0);
+ buf = gst_buffer_make_writable (buf);
cvPutText (filter->cvImage,filter->textbuf,cvPoint(filter->xpos,filter->ypos), &(filter->font), cvScalar(filter->colorR,filter->colorG,filter->colorB,0));
- gst_buffer_set_data (buf, (guint8 *) filter->cvImage->imageData,
- filter->cvImage->imageSize);
-
return gst_pad_push (filter->srcpad, buf);
}
/* entry point to initialize the plug-in
* initialize the plug-in itself
* register the element factories and other features
*/
gboolean
gst_textwrite_plugin_init (GstPlugin * plugin)
{
/* debug category for fltering log messages
*
* exchange the string 'Template textwrite' with your description
*/
GST_DEBUG_CATEGORY_INIT (gst_textwrite_debug, "textwrite",
0, "Template textwrite");
return gst_element_register (plugin, "textwrite", GST_RANK_NONE,
GST_TYPE_textwrite);
}
|
Elleo/gst-opencv
|
da66bdf21f7ef943d8d0b865ebf9ca8b1c46819b
|
edgedetect: Fix chain buffer handling
|
diff --git a/src/edgedetect/gstedgedetect.c b/src/edgedetect/gstedgedetect.c
index aa7b377..77e1d62 100644
--- a/src/edgedetect/gstedgedetect.c
+++ b/src/edgedetect/gstedgedetect.c
@@ -1,330 +1,335 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2008 Michael Sheldon <mike@mikeasoft.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/**
* SECTION:element-edgedetect
*
* FIXME:Describe edgedetect here.
*
* <refsect2>
* <title>Example launch line</title>
* |[
* gst-launch-0.10 videotestsrc ! decodebin ! ffmpegcolorspace ! edgedetect ! ffmpegcolorspace ! xvimagesink
* ]|
* </refsect2>
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <gst/gst.h>
#include "gstedgedetect.h"
GST_DEBUG_CATEGORY_STATIC (gst_edgedetect_debug);
#define GST_CAT_DEFAULT gst_edgedetect_debug
/* Filter signals and args */
enum
{
/* FILL ME */
LAST_SIGNAL
};
enum
{
PROP_0,
PROP_THRESHOLD1,
PROP_THRESHOLD2,
PROP_APERTURE,
PROP_MASK
};
/* the capabilities of the inputs and outputs.
*
* describe the real formats here.
*/
static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
GST_PAD_SINK,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("video/x-raw-rgb")
);
static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
GST_PAD_SRC,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("video/x-raw-rgb")
);
GST_BOILERPLATE (Gstedgedetect, gst_edgedetect, GstElement, GST_TYPE_ELEMENT);
static void gst_edgedetect_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec);
static void gst_edgedetect_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec);
static gboolean gst_edgedetect_set_caps (GstPad * pad, GstCaps * caps);
static GstFlowReturn gst_edgedetect_chain (GstPad * pad, GstBuffer * buf);
/* Clean up */
static void
gst_edgedetect_finalize (GObject * obj)
{
Gstedgedetect *filter = GST_EDGEDETECT (obj);
if (filter->cvImage != NULL) {
cvReleaseImage (&filter->cvImage);
cvReleaseImage (&filter->cvCEdge);
cvReleaseImage (&filter->cvGray);
cvReleaseImage (&filter->cvEdge);
}
G_OBJECT_CLASS (parent_class)->finalize (obj);
}
/* GObject vmethod implementations */
static void
gst_edgedetect_base_init (gpointer gclass)
{
GstElementClass *element_class = GST_ELEMENT_CLASS (gclass);
gst_element_class_set_details_simple (element_class,
"edgedetect",
"Filter/Effect/Video",
"Performs canny edge detection on videos and images.",
"Michael Sheldon <mike@mikeasoft.com>");
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&src_factory));
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&sink_factory));
}
/* initialize the edgedetect's class */
static void
gst_edgedetect_class_init (GstedgedetectClass * klass)
{
GObjectClass *gobject_class;
GstElementClass *gstelement_class;
gobject_class = (GObjectClass *) klass;
gstelement_class = (GstElementClass *) klass;
parent_class = g_type_class_peek_parent (klass);
gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_edgedetect_finalize);
gobject_class->set_property = gst_edgedetect_set_property;
gobject_class->get_property = gst_edgedetect_get_property;
g_object_class_install_property (gobject_class, PROP_MASK,
g_param_spec_boolean ("mask", "Mask",
"Sets whether the detected edges should be used as a mask on the original input or not",
TRUE, G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_THRESHOLD1,
g_param_spec_int ("threshold1", "Threshold1",
"Threshold value for canny edge detection", 0, 1000, 50,
G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_THRESHOLD2,
g_param_spec_int ("threshold2", "Threshold2",
"Second threshold value for canny edge detection", 0, 1000, 150,
G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_APERTURE,
g_param_spec_int ("aperture", "Aperture",
"Aperture size for Sobel operator (Must be either 3, 5 or 7", 3, 7, 3,
G_PARAM_READWRITE));
}
/* initialize the new element
* instantiate pads and add them to element
* set pad calback functions
* initialize instance structure
*/
static void
gst_edgedetect_init (Gstedgedetect * filter, GstedgedetectClass * gclass)
{
filter->sinkpad = gst_pad_new_from_static_template (&sink_factory, "sink");
gst_pad_set_setcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR (gst_edgedetect_set_caps));
gst_pad_set_getcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR (gst_pad_proxy_getcaps));
gst_pad_set_chain_function (filter->sinkpad,
GST_DEBUG_FUNCPTR (gst_edgedetect_chain));
filter->srcpad = gst_pad_new_from_static_template (&src_factory, "src");
gst_pad_set_getcaps_function (filter->srcpad,
GST_DEBUG_FUNCPTR (gst_pad_proxy_getcaps));
gst_element_add_pad (GST_ELEMENT (filter), filter->sinkpad);
gst_element_add_pad (GST_ELEMENT (filter), filter->srcpad);
filter->mask = TRUE;
filter->threshold1 = 50;
filter->threshold2 = 150;
filter->aperture = 3;
}
static void
gst_edgedetect_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec)
{
Gstedgedetect *filter = GST_EDGEDETECT (object);
switch (prop_id) {
case PROP_MASK:
filter->mask = g_value_get_boolean (value);
break;
case PROP_THRESHOLD1:
filter->threshold1 = g_value_get_int (value);
break;
case PROP_THRESHOLD2:
filter->threshold2 = g_value_get_int (value);
break;
case PROP_APERTURE:
filter->aperture = g_value_get_int (value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gst_edgedetect_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec)
{
Gstedgedetect *filter = GST_EDGEDETECT (object);
switch (prop_id) {
case PROP_MASK:
g_value_set_boolean (value, filter->mask);
break;
case PROP_THRESHOLD1:
g_value_set_int (value, filter->threshold1);
break;
case PROP_THRESHOLD2:
g_value_set_int (value, filter->threshold2);
break;
case PROP_APERTURE:
g_value_set_int (value, filter->aperture);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
/* GstElement vmethod implementations */
/* this function handles the link with other elements */
static gboolean
gst_edgedetect_set_caps (GstPad * pad, GstCaps * caps)
{
Gstedgedetect *filter;
GstPad *otherpad;
gint width, height;
GstStructure *structure;
filter = GST_EDGEDETECT (gst_pad_get_parent (pad));
structure = gst_caps_get_structure (caps, 0);
gst_structure_get_int (structure, "width", &width);
gst_structure_get_int (structure, "height", &height);
filter->cvImage = cvCreateImage (cvSize (width, height), IPL_DEPTH_8U, 3);
filter->cvCEdge = cvCreateImage (cvSize (width, height), IPL_DEPTH_8U, 3);
filter->cvGray = cvCreateImage (cvSize (width, height), IPL_DEPTH_8U, 1);
filter->cvEdge = cvCreateImage (cvSize (width, height), IPL_DEPTH_8U, 1);
otherpad = (pad == filter->srcpad) ? filter->sinkpad : filter->srcpad;
gst_object_unref (filter);
return gst_pad_set_caps (otherpad, caps);
}
/* chain function
* this function does the actual processing
*/
static GstFlowReturn
gst_edgedetect_chain (GstPad * pad, GstBuffer * buf)
{
Gstedgedetect *filter;
+ GstBuffer *outbuf;
filter = GST_EDGEDETECT (GST_OBJECT_PARENT (pad));
filter->cvImage->imageData = (char *) GST_BUFFER_DATA (buf);
cvCvtColor (filter->cvImage, filter->cvGray, CV_RGB2GRAY);
cvSmooth (filter->cvGray, filter->cvEdge, CV_BLUR, 3, 3, 0, 0);
cvNot (filter->cvGray, filter->cvEdge);
cvCanny (filter->cvGray, filter->cvEdge, filter->threshold1,
filter->threshold2, filter->aperture);
cvZero (filter->cvCEdge);
if (filter->mask) {
cvCopy (filter->cvImage, filter->cvCEdge, filter->cvEdge);
} else {
cvCvtColor (filter->cvEdge, filter->cvCEdge, CV_GRAY2RGB);
}
- gst_buffer_set_data (buf, (guint8 *) filter->cvCEdge->imageData,
- filter->cvCEdge->imageSize);
- return gst_pad_push (filter->srcpad, buf);
+ outbuf = gst_buffer_new_and_alloc (filter->cvCEdge->imageSize);
+ gst_buffer_copy_metadata (outbuf, buf, GST_BUFFER_COPY_ALL);
+ memcpy (GST_BUFFER_DATA (outbuf), filter->cvCEdge->imageData,
+ GST_BUFFER_SIZE (outbuf));
+
+ gst_buffer_unref (buf);
+ return gst_pad_push (filter->srcpad, outbuf);
}
/* entry point to initialize the plug-in
* initialize the plug-in itself
* register the element factories and other features
*/
gboolean
gst_edgedetect_plugin_init (GstPlugin * plugin)
{
/* debug category for fltering log messages
*
* exchange the string 'Template edgedetect' with your description
*/
GST_DEBUG_CATEGORY_INIT (gst_edgedetect_debug, "edgedetect",
0, "Performs canny edge detection on videos and images");
return gst_element_register (plugin, "edgedetect", GST_RANK_NONE,
GST_TYPE_EDGEDETECT);
}
|
Elleo/gst-opencv
|
ae66681c90fe230ffd8924a6b091e63070ad4660
|
configure: enable -Werror to improve code
|
diff --git a/configure.ac b/configure.ac
index 9272730..ea0da20 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1,149 +1,149 @@
AC_INIT
dnl versions of gstreamer and plugins-base
GST_MAJORMINOR=0.10
GST_REQUIRED=0.10.0
GSTPB_REQUIRED=0.10.0
dnl fill in your package name and version here
dnl the fourth (nano) number should be 0 for a release, 1 for CVS,
dnl and 2... for a prerelease
dnl when going to/from release please set the nano correctly !
dnl releases only do Wall, cvs and prerelease does Werror too
AS_VERSION(gst-opencv, GST_PLUGIN_VERSION, 0, 10, 0, 1,
GST_PLUGIN_CVS="no", GST_PLUGIN_CVS="yes")
dnl AM_MAINTAINER_MODE provides the option to enable maintainer mode
AM_MAINTAINER_MODE
AM_INIT_AUTOMAKE($PACKAGE, $VERSION)
dnl make aclocal work in maintainer mode
AC_SUBST(ACLOCAL_AMFLAGS, "-I m4")
AM_CONFIG_HEADER(config.h)
dnl check for tools
AC_PROG_CC
AC_PROG_LIBTOOL
dnl decide on error flags
AS_COMPILER_FLAG(-Wall, GST_WALL="yes", GST_WALL="no")
if test "x$GST_WALL" = "xyes"; then
GST_ERROR="$GST_ERROR -Wall"
+fi
-# if test "x$GST_PLUGIN_CVS" = "xyes"; then
-# AS_COMPILER_FLAG(-Werror,GST_ERROR="$GST_ERROR -Werror",GST_ERROR="$GST_ERROR")
-# fi
+if test "x$GST_PLUGIN_CVS" = "xyes"; then
+ AS_COMPILER_FLAG(-Werror,GST_ERROR="$GST_ERROR -Werror",GST_ERROR="$GST_ERROR")
fi
dnl Check for pkgconfig first
AC_CHECK_PROG(HAVE_PKGCONFIG, pkg-config, yes, no)
dnl Give error and exit if we don't have pkgconfig
if test "x$HAVE_PKGCONFIG" = "xno"; then
AC_MSG_ERROR(you need to have pkgconfig installed !)
fi
dnl Now we're ready to ask for gstreamer libs and cflags
dnl And we can also ask for the right version of gstreamer
PKG_CHECK_MODULES(GST, \
gstreamer-$GST_MAJORMINOR >= $GST_REQUIRED,
HAVE_GST=yes,HAVE_GST=no)
dnl Give error and exit if we don't have gstreamer
if test "x$HAVE_GST" = "xno"; then
AC_MSG_ERROR(you need gstreamer development packages installed !)
fi
dnl append GST_ERROR cflags to GST_CFLAGS
GST_CFLAGS="$GST_CFLAGS $GST_ERROR"
dnl make GST_CFLAGS and GST_LIBS available
AC_SUBST(GST_CFLAGS)
AC_SUBST(GST_LIBS)
dnl make GST_MAJORMINOR available in Makefile.am
AC_SUBST(GST_MAJORMINOR)
dnl If we need them, we can also use the base class libraries
PKG_CHECK_MODULES(GST_BASE, gstreamer-base-$GST_MAJORMINOR >= $GST_REQUIRED,
HAVE_GST_BASE=yes, HAVE_GST_BASE=no)
dnl Give a warning if we don't have gstreamer libs
dnl you can turn this into an error if you need them
if test "x$HAVE_GST_BASE" = "xno"; then
AC_MSG_NOTICE(no GStreamer base class libraries found (gstreamer-base-$GST_MAJORMINOR))
fi
dnl make _CFLAGS and _LIBS available
AC_SUBST(GST_BASE_CFLAGS)
AC_SUBST(GST_BASE_LIBS)
PKG_CHECK_MODULES(OPENCV,
opencv,
HAVE_OPENCV=yes, HAVE_OPENCV=no)
AC_SUBST(OPENCV_CFLAGS)
AC_SUBST(OPENCV_LIBS)
if test "x$HAVE_OPENCV" = "xno"; then
AC_MSG_ERROR(OpenCV libraries could not be found)
fi
PKG_CHECK_MODULES(SWSCALE,
libswscale,
HAVE_LIBSWSCALE=yes, HAVE_LIBSWSCALE=no)
if test "x$HAVE_LIBSWSCALE" = "xno"; then
AC_MSG_ERROR(libswscale could not be found)
fi
dnl If we need them, we can also use the gstreamer-plugins-base libraries
PKG_CHECK_MODULES(GSTPB_BASE,
gstreamer-plugins-base-$GST_MAJORMINOR >= $GSTPB_REQUIRED,
HAVE_GSTPB_BASE=yes, HAVE_GSTPB_BASE=no)
dnl Give a warning if we don't have gstreamer libs
dnl you can turn this into an error if you need them
if test "x$HAVE_GSTPB_BASE" = "xno"; then
AC_MSG_NOTICE(no GStreamer Plugins Base libraries found (gstreamer-plugins-base-$GST_MAJORMINOR))
fi
dnl make _CFLAGS and _LIBS available
AC_SUBST(GSTPB_BASE_CFLAGS)
AC_SUBST(GSTPB_BASE_LIBS)
dnl If we need them, we can also use the gstreamer-controller libraries
PKG_CHECK_MODULES(GSTCTRL,
gstreamer-controller-$GST_MAJORMINOR >= $GSTPB_REQUIRED,
HAVE_GSTCTRL=yes, HAVE_GSTCTRL=no)
dnl Give a warning if we don't have gstreamer-controller
dnl you can turn this into an error if you need them
if test "x$HAVE_GSTCTRL" = "xno"; then
AC_MSG_NOTICE(no GStreamer Controller libraries found (gstreamer-controller-$GST_MAJORMINOR))
fi
dnl make _CFLAGS and _LIBS available
AC_SUBST(GSTCTRL_CFLAGS)
AC_SUBST(GSTCTRL_LIBS)
dnl set the plugindir where plugins should be installed
if test "x${prefix}" = "x$HOME"; then
plugindir="$HOME/.gstreamer-$GST_MAJORMINOR/plugins"
else
plugindir="\$(libdir)/gstreamer-$GST_MAJORMINOR"
fi
AC_SUBST(plugindir)
dnl set proper LDFLAGS for plugins
GST_PLUGIN_LDFLAGS='-module -avoid-version -export-symbols-regex [_]*\(gst_\|Gst\|GST_\).*'
AC_SUBST(GST_PLUGIN_LDFLAGS)
AC_OUTPUT(Makefile m4/Makefile src/Makefile src/edgedetect/Makefile src/faceblur/Makefile src/facedetect/Makefile src/pyramidsegment/Makefile src/templatematch/Makefile src/textwrite/Makefile)
diff --git a/src/edgedetect/gstedgedetect.c b/src/edgedetect/gstedgedetect.c
index c88d5e3..aa7b377 100644
--- a/src/edgedetect/gstedgedetect.c
+++ b/src/edgedetect/gstedgedetect.c
@@ -1,330 +1,330 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2008 Michael Sheldon <mike@mikeasoft.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/**
* SECTION:element-edgedetect
*
* FIXME:Describe edgedetect here.
*
* <refsect2>
* <title>Example launch line</title>
* |[
* gst-launch-0.10 videotestsrc ! decodebin ! ffmpegcolorspace ! edgedetect ! ffmpegcolorspace ! xvimagesink
* ]|
* </refsect2>
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <gst/gst.h>
#include "gstedgedetect.h"
GST_DEBUG_CATEGORY_STATIC (gst_edgedetect_debug);
#define GST_CAT_DEFAULT gst_edgedetect_debug
/* Filter signals and args */
enum
{
/* FILL ME */
LAST_SIGNAL
};
enum
{
PROP_0,
PROP_THRESHOLD1,
PROP_THRESHOLD2,
PROP_APERTURE,
PROP_MASK
};
/* the capabilities of the inputs and outputs.
*
* describe the real formats here.
*/
static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
GST_PAD_SINK,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("video/x-raw-rgb")
);
static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
GST_PAD_SRC,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("video/x-raw-rgb")
);
GST_BOILERPLATE (Gstedgedetect, gst_edgedetect, GstElement, GST_TYPE_ELEMENT);
static void gst_edgedetect_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec);
static void gst_edgedetect_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec);
static gboolean gst_edgedetect_set_caps (GstPad * pad, GstCaps * caps);
static GstFlowReturn gst_edgedetect_chain (GstPad * pad, GstBuffer * buf);
/* Clean up */
static void
gst_edgedetect_finalize (GObject * obj)
{
Gstedgedetect *filter = GST_EDGEDETECT (obj);
if (filter->cvImage != NULL) {
cvReleaseImage (&filter->cvImage);
cvReleaseImage (&filter->cvCEdge);
cvReleaseImage (&filter->cvGray);
cvReleaseImage (&filter->cvEdge);
}
G_OBJECT_CLASS (parent_class)->finalize (obj);
}
/* GObject vmethod implementations */
static void
gst_edgedetect_base_init (gpointer gclass)
{
GstElementClass *element_class = GST_ELEMENT_CLASS (gclass);
gst_element_class_set_details_simple (element_class,
"edgedetect",
"Filter/Effect/Video",
"Performs canny edge detection on videos and images.",
"Michael Sheldon <mike@mikeasoft.com>");
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&src_factory));
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&sink_factory));
}
/* initialize the edgedetect's class */
static void
gst_edgedetect_class_init (GstedgedetectClass * klass)
{
GObjectClass *gobject_class;
GstElementClass *gstelement_class;
gobject_class = (GObjectClass *) klass;
gstelement_class = (GstElementClass *) klass;
parent_class = g_type_class_peek_parent (klass);
gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_edgedetect_finalize);
gobject_class->set_property = gst_edgedetect_set_property;
gobject_class->get_property = gst_edgedetect_get_property;
g_object_class_install_property (gobject_class, PROP_MASK,
g_param_spec_boolean ("mask", "Mask",
"Sets whether the detected edges should be used as a mask on the original input or not",
TRUE, G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_THRESHOLD1,
g_param_spec_int ("threshold1", "Threshold1",
"Threshold value for canny edge detection", 0, 1000, 50,
G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_THRESHOLD2,
g_param_spec_int ("threshold2", "Threshold2",
"Second threshold value for canny edge detection", 0, 1000, 150,
G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_APERTURE,
g_param_spec_int ("aperture", "Aperture",
"Aperture size for Sobel operator (Must be either 3, 5 or 7", 3, 7, 3,
G_PARAM_READWRITE));
}
/* initialize the new element
* instantiate pads and add them to element
* set pad calback functions
* initialize instance structure
*/
static void
gst_edgedetect_init (Gstedgedetect * filter, GstedgedetectClass * gclass)
{
filter->sinkpad = gst_pad_new_from_static_template (&sink_factory, "sink");
gst_pad_set_setcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR (gst_edgedetect_set_caps));
gst_pad_set_getcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR (gst_pad_proxy_getcaps));
gst_pad_set_chain_function (filter->sinkpad,
GST_DEBUG_FUNCPTR (gst_edgedetect_chain));
filter->srcpad = gst_pad_new_from_static_template (&src_factory, "src");
gst_pad_set_getcaps_function (filter->srcpad,
GST_DEBUG_FUNCPTR (gst_pad_proxy_getcaps));
gst_element_add_pad (GST_ELEMENT (filter), filter->sinkpad);
gst_element_add_pad (GST_ELEMENT (filter), filter->srcpad);
filter->mask = TRUE;
filter->threshold1 = 50;
filter->threshold2 = 150;
filter->aperture = 3;
}
static void
gst_edgedetect_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec)
{
Gstedgedetect *filter = GST_EDGEDETECT (object);
switch (prop_id) {
case PROP_MASK:
filter->mask = g_value_get_boolean (value);
break;
case PROP_THRESHOLD1:
filter->threshold1 = g_value_get_int (value);
break;
case PROP_THRESHOLD2:
filter->threshold2 = g_value_get_int (value);
break;
case PROP_APERTURE:
filter->aperture = g_value_get_int (value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gst_edgedetect_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec)
{
Gstedgedetect *filter = GST_EDGEDETECT (object);
switch (prop_id) {
case PROP_MASK:
g_value_set_boolean (value, filter->mask);
break;
case PROP_THRESHOLD1:
g_value_set_int (value, filter->threshold1);
break;
case PROP_THRESHOLD2:
g_value_set_int (value, filter->threshold2);
break;
case PROP_APERTURE:
g_value_set_int (value, filter->aperture);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
/* GstElement vmethod implementations */
/* this function handles the link with other elements */
static gboolean
gst_edgedetect_set_caps (GstPad * pad, GstCaps * caps)
{
Gstedgedetect *filter;
GstPad *otherpad;
gint width, height;
GstStructure *structure;
filter = GST_EDGEDETECT (gst_pad_get_parent (pad));
structure = gst_caps_get_structure (caps, 0);
gst_structure_get_int (structure, "width", &width);
gst_structure_get_int (structure, "height", &height);
filter->cvImage = cvCreateImage (cvSize (width, height), IPL_DEPTH_8U, 3);
filter->cvCEdge = cvCreateImage (cvSize (width, height), IPL_DEPTH_8U, 3);
filter->cvGray = cvCreateImage (cvSize (width, height), IPL_DEPTH_8U, 1);
filter->cvEdge = cvCreateImage (cvSize (width, height), IPL_DEPTH_8U, 1);
otherpad = (pad == filter->srcpad) ? filter->sinkpad : filter->srcpad;
gst_object_unref (filter);
return gst_pad_set_caps (otherpad, caps);
}
/* chain function
* this function does the actual processing
*/
static GstFlowReturn
gst_edgedetect_chain (GstPad * pad, GstBuffer * buf)
{
Gstedgedetect *filter;
filter = GST_EDGEDETECT (GST_OBJECT_PARENT (pad));
filter->cvImage->imageData = (char *) GST_BUFFER_DATA (buf);
cvCvtColor (filter->cvImage, filter->cvGray, CV_RGB2GRAY);
cvSmooth (filter->cvGray, filter->cvEdge, CV_BLUR, 3, 3, 0, 0);
cvNot (filter->cvGray, filter->cvEdge);
cvCanny (filter->cvGray, filter->cvEdge, filter->threshold1,
filter->threshold2, filter->aperture);
cvZero (filter->cvCEdge);
if (filter->mask) {
cvCopy (filter->cvImage, filter->cvCEdge, filter->cvEdge);
} else {
cvCvtColor (filter->cvEdge, filter->cvCEdge, CV_GRAY2RGB);
}
- gst_buffer_set_data (buf, filter->cvCEdge->imageData,
+ gst_buffer_set_data (buf, (guint8 *) filter->cvCEdge->imageData,
filter->cvCEdge->imageSize);
return gst_pad_push (filter->srcpad, buf);
}
/* entry point to initialize the plug-in
* initialize the plug-in itself
* register the element factories and other features
*/
gboolean
gst_edgedetect_plugin_init (GstPlugin * plugin)
{
/* debug category for fltering log messages
*
* exchange the string 'Template edgedetect' with your description
*/
GST_DEBUG_CATEGORY_INIT (gst_edgedetect_debug, "edgedetect",
0, "Performs canny edge detection on videos and images");
return gst_element_register (plugin, "edgedetect", GST_RANK_NONE,
GST_TYPE_EDGEDETECT);
}
diff --git a/src/faceblur/gstfaceblur.c b/src/faceblur/gstfaceblur.c
index 5f1deb3..a33a708 100644
--- a/src/faceblur/gstfaceblur.c
+++ b/src/faceblur/gstfaceblur.c
@@ -1,316 +1,316 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2008 Michael Sheldon <mike@mikeasoft.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/**
* SECTION:element-faceblur
*
* FIXME:Describe faceblur here.
*
* <refsect2>
* <title>Example launch line</title>
* |[
* gst-launch-0.10 videotestsrc ! decodebin ! ffmpegcolorspace ! faceblur ! ffmpegcolorspace ! xvimagesink
* ]|
* </refsect2>
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <gst/gst.h>
#include "gstfaceblur.h"
GST_DEBUG_CATEGORY_STATIC (gst_faceblur_debug);
#define GST_CAT_DEFAULT gst_faceblur_debug
#define DEFAULT_PROFILE "/usr/share/opencv/haarcascades/haarcascade_frontalface_default.xml"
/* Filter signals and args */
enum
{
/* FILL ME */
LAST_SIGNAL
};
enum
{
PROP_0,
PROP_PROFILE
};
/* the capabilities of the inputs and outputs.
*/
static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
GST_PAD_SINK,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("video/x-raw-rgb")
);
static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
GST_PAD_SRC,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("video/x-raw-rgb")
);
GST_BOILERPLATE (Gstfaceblur, gst_faceblur, GstElement, GST_TYPE_ELEMENT);
static void gst_faceblur_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec);
static void gst_faceblur_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec);
static gboolean gst_faceblur_set_caps (GstPad * pad, GstCaps * caps);
static GstFlowReturn gst_faceblur_chain (GstPad * pad, GstBuffer * buf);
static void gst_faceblur_load_profile (Gstfaceblur * filter);
/* Clean up */
static void
gst_faceblur_finalize (GObject * obj)
{
Gstfaceblur *filter = GST_FACEBLUR (obj);
if (filter->cvImage) {
cvReleaseImage (&filter->cvImage);
cvReleaseImage (&filter->cvGray);
}
g_free (filter->profile);
G_OBJECT_CLASS (parent_class)->finalize (obj);
}
/* GObject vmethod implementations */
static void
gst_faceblur_base_init (gpointer gclass)
{
GstElementClass *element_class = GST_ELEMENT_CLASS (gclass);
gst_element_class_set_details_simple (element_class,
"faceblur",
"Filter/Effect/Video",
"Blurs faces in images and videos",
"Michael Sheldon <mike@mikeasoft.com>");
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&src_factory));
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&sink_factory));
}
/* initialize the faceblur's class */
static void
gst_faceblur_class_init (GstfaceblurClass * klass)
{
GObjectClass *gobject_class;
GstElementClass *gstelement_class;
gobject_class = (GObjectClass *) klass;
gstelement_class = (GstElementClass *) klass;
parent_class = g_type_class_peek_parent (klass);
gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_faceblur_finalize);
gobject_class->set_property = gst_faceblur_set_property;
gobject_class->get_property = gst_faceblur_get_property;
g_object_class_install_property (gobject_class, PROP_PROFILE,
g_param_spec_string ("profile", "Profile",
"Location of Haar cascade file to use for face blurion",
DEFAULT_PROFILE, G_PARAM_READWRITE));
}
/* initialize the new element
* instantiate pads and add them to element
* set pad calback functions
* initialize instance structure
*/
static void
gst_faceblur_init (Gstfaceblur * filter, GstfaceblurClass * gclass)
{
filter->sinkpad = gst_pad_new_from_static_template (&sink_factory, "sink");
gst_pad_set_setcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR (gst_faceblur_set_caps));
gst_pad_set_getcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR (gst_pad_proxy_getcaps));
gst_pad_set_chain_function (filter->sinkpad,
GST_DEBUG_FUNCPTR (gst_faceblur_chain));
filter->srcpad = gst_pad_new_from_static_template (&src_factory, "src");
gst_pad_set_getcaps_function (filter->srcpad,
GST_DEBUG_FUNCPTR (gst_pad_proxy_getcaps));
gst_element_add_pad (GST_ELEMENT (filter), filter->sinkpad);
gst_element_add_pad (GST_ELEMENT (filter), filter->srcpad);
filter->profile = g_strdup (DEFAULT_PROFILE);
gst_faceblur_load_profile (filter);
}
static void
gst_faceblur_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec)
{
Gstfaceblur *filter = GST_FACEBLUR (object);
switch (prop_id) {
case PROP_PROFILE:
g_free (filter->profile);
filter->profile = g_value_dup_string (value);
gst_faceblur_load_profile (filter);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gst_faceblur_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec)
{
Gstfaceblur *filter = GST_FACEBLUR (object);
switch (prop_id) {
case PROP_PROFILE:
g_value_set_string (value, filter->profile);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
/* GstElement vmethod implementations */
/* this function handles the link with other elements */
static gboolean
gst_faceblur_set_caps (GstPad * pad, GstCaps * caps)
{
Gstfaceblur *filter;
GstPad *otherpad;
gint width, height;
GstStructure *structure;
filter = GST_FACEBLUR (gst_pad_get_parent (pad));
structure = gst_caps_get_structure (caps, 0);
gst_structure_get_int (structure, "width", &width);
gst_structure_get_int (structure, "height", &height);
filter->cvImage = cvCreateImage (cvSize (width, height), IPL_DEPTH_8U, 3);
filter->cvGray = cvCreateImage (cvSize (width, height), IPL_DEPTH_8U, 1);
filter->cvStorage = cvCreateMemStorage (0);
otherpad = (pad == filter->srcpad) ? filter->sinkpad : filter->srcpad;
gst_object_unref (filter);
return gst_pad_set_caps (otherpad, caps);
}
/* chain function
* this function does the actual processing
*/
static GstFlowReturn
gst_faceblur_chain (GstPad * pad, GstBuffer * buf)
{
Gstfaceblur *filter;
CvSeq *faces;
int i;
filter = GST_FACEBLUR (GST_OBJECT_PARENT (pad));
filter->cvImage->imageData = (char *) GST_BUFFER_DATA (buf);
cvCvtColor (filter->cvImage, filter->cvGray, CV_RGB2GRAY);
cvClearMemStorage (filter->cvStorage);
if (filter->cvCascade) {
faces =
cvHaarDetectObjects (filter->cvGray, filter->cvCascade,
filter->cvStorage, 1.1, 2, 0, cvSize (30, 30));
for (i = 0; i < (faces ? faces->total : 0); i++) {
CvRect *r = (CvRect *) cvGetSeqElem (faces, i);
cvSetImageROI (filter->cvImage, *r);
cvSmooth (filter->cvImage, filter->cvImage, CV_BLUR, 11, 11, 0, 0);
cvSmooth (filter->cvImage, filter->cvImage, CV_GAUSSIAN, 11, 11, 0, 0);
cvResetImageROI (filter->cvImage);
}
}
- gst_buffer_set_data (buf, filter->cvImage->imageData,
+ gst_buffer_set_data (buf, (guint8 *) filter->cvImage->imageData,
filter->cvImage->imageSize);
return gst_pad_push (filter->srcpad, buf);
}
static void
gst_faceblur_load_profile (Gstfaceblur * filter)
{
filter->cvCascade =
(CvHaarClassifierCascade *) cvLoad (filter->profile, 0, 0, 0);
if (!filter->cvCascade) {
GST_WARNING ("Couldn't load Haar classifier cascade: %s.", filter->profile);
}
}
/* entry point to initialize the plug-in
* initialize the plug-in itself
* register the element factories and other features
*/
gboolean
gst_faceblur_plugin_init (GstPlugin * plugin)
{
/* debug category for filtering log messages */
GST_DEBUG_CATEGORY_INIT (gst_faceblur_debug, "faceblur",
0, "Blurs faces in images and videos");
return gst_element_register (plugin, "faceblur", GST_RANK_NONE,
GST_TYPE_FACEBLUR);
}
diff --git a/src/facedetect/gstfacedetect.c b/src/facedetect/gstfacedetect.c
index 0928b45..6494e43 100644
--- a/src/facedetect/gstfacedetect.c
+++ b/src/facedetect/gstfacedetect.c
@@ -1,345 +1,345 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2008 Michael Sheldon <mike@mikeasoft.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/**
* SECTION:element-facedetect
*
* FIXME:Describe facedetect here.
*
* <refsect2>
* <title>Example launch line</title>
* |[
* gst-launch-0.10 videotestsrc ! decodebin ! ffmpegcolorspace ! facedetect ! ffmpegcolorspace ! xvimagesink
* ]|
* </refsect2>
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <gst/gst.h>
#include "gstfacedetect.h"
GST_DEBUG_CATEGORY_STATIC (gst_facedetect_debug);
#define GST_CAT_DEFAULT gst_facedetect_debug
#define DEFAULT_PROFILE "/usr/share/opencv/haarcascades/haarcascade_frontalface_default.xml"
/* Filter signals and args */
enum
{
/* FILL ME */
LAST_SIGNAL
};
enum
{
PROP_0,
PROP_DISPLAY,
PROP_PROFILE
};
/* the capabilities of the inputs and outputs.
*/
static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
GST_PAD_SINK,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("video/x-raw-rgb")
);
static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
GST_PAD_SRC,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("video/x-raw-rgb")
);
GST_BOILERPLATE (Gstfacedetect, gst_facedetect, GstElement, GST_TYPE_ELEMENT);
static void gst_facedetect_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec);
static void gst_facedetect_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec);
static gboolean gst_facedetect_set_caps (GstPad * pad, GstCaps * caps);
static GstFlowReturn gst_facedetect_chain (GstPad * pad, GstBuffer * buf);
static void gst_facedetect_load_profile (Gstfacedetect * filter);
/* Clean up */
static void
gst_facedetect_finalize (GObject * obj)
{
Gstfacedetect *filter = GST_FACEDETECT (obj);
if (filter->cvImage) {
cvReleaseImage (&filter->cvImage);
cvReleaseImage (&filter->cvGray);
}
g_free (filter->profile);
G_OBJECT_CLASS (parent_class)->finalize (obj);
}
/* GObject vmethod implementations */
static void
gst_facedetect_base_init (gpointer gclass)
{
GstElementClass *element_class = GST_ELEMENT_CLASS (gclass);
gst_element_class_set_details_simple (element_class,
"facedetect",
"Filter/Effect/Video",
"Performs face detection on videos and images, providing detected positions via bus messages",
"Michael Sheldon <mike@mikeasoft.com>");
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&src_factory));
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&sink_factory));
}
/* initialize the facedetect's class */
static void
gst_facedetect_class_init (GstfacedetectClass * klass)
{
GObjectClass *gobject_class;
GstElementClass *gstelement_class;
gobject_class = (GObjectClass *) klass;
gstelement_class = (GstElementClass *) klass;
parent_class = g_type_class_peek_parent (klass);
gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_facedetect_finalize);
gobject_class->set_property = gst_facedetect_set_property;
gobject_class->get_property = gst_facedetect_get_property;
g_object_class_install_property (gobject_class, PROP_DISPLAY,
g_param_spec_boolean ("display", "Display",
"Sets whether the detected faces should be highlighted in the output",
TRUE, G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_PROFILE,
g_param_spec_string ("profile", "Profile",
"Location of Haar cascade file to use for face detection",
DEFAULT_PROFILE, G_PARAM_READWRITE));
}
/* initialize the new element
* instantiate pads and add them to element
* set pad calback functions
* initialize instance structure
*/
static void
gst_facedetect_init (Gstfacedetect * filter, GstfacedetectClass * gclass)
{
filter->sinkpad = gst_pad_new_from_static_template (&sink_factory, "sink");
gst_pad_set_setcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR (gst_facedetect_set_caps));
gst_pad_set_getcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR (gst_pad_proxy_getcaps));
gst_pad_set_chain_function (filter->sinkpad,
GST_DEBUG_FUNCPTR (gst_facedetect_chain));
filter->srcpad = gst_pad_new_from_static_template (&src_factory, "src");
gst_pad_set_getcaps_function (filter->srcpad,
GST_DEBUG_FUNCPTR (gst_pad_proxy_getcaps));
gst_element_add_pad (GST_ELEMENT (filter), filter->sinkpad);
gst_element_add_pad (GST_ELEMENT (filter), filter->srcpad);
filter->profile = g_strdup(DEFAULT_PROFILE);
filter->display = TRUE;
gst_facedetect_load_profile (filter);
}
static void
gst_facedetect_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec)
{
Gstfacedetect *filter = GST_FACEDETECT (object);
switch (prop_id) {
case PROP_PROFILE:
g_free (filter->profile);
filter->profile = g_value_dup_string (value);
gst_facedetect_load_profile (filter);
break;
case PROP_DISPLAY:
filter->display = g_value_get_boolean (value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gst_facedetect_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec)
{
Gstfacedetect *filter = GST_FACEDETECT (object);
switch (prop_id) {
case PROP_PROFILE:
g_value_set_string (value, filter->profile);
break;
case PROP_DISPLAY:
g_value_set_boolean (value, filter->display);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
/* GstElement vmethod implementations */
/* this function handles the link with other elements */
static gboolean
gst_facedetect_set_caps (GstPad * pad, GstCaps * caps)
{
Gstfacedetect *filter;
GstPad *otherpad;
gint width, height;
GstStructure *structure;
filter = GST_FACEDETECT (gst_pad_get_parent (pad));
structure = gst_caps_get_structure (caps, 0);
gst_structure_get_int (structure, "width", &width);
gst_structure_get_int (structure, "height", &height);
filter->cvImage = cvCreateImage (cvSize (width, height), IPL_DEPTH_8U, 3);
filter->cvGray = cvCreateImage (cvSize (width, height), IPL_DEPTH_8U, 1);
filter->cvStorage = cvCreateMemStorage (0);
otherpad = (pad == filter->srcpad) ? filter->sinkpad : filter->srcpad;
gst_object_unref (filter);
return gst_pad_set_caps (otherpad, caps);
}
/* chain function
* this function does the actual processing
*/
static GstFlowReturn
gst_facedetect_chain (GstPad * pad, GstBuffer * buf)
{
Gstfacedetect *filter;
CvSeq *faces;
int i;
filter = GST_FACEDETECT (GST_OBJECT_PARENT (pad));
filter->cvImage->imageData = (char *) GST_BUFFER_DATA (buf);
cvCvtColor (filter->cvImage, filter->cvGray, CV_RGB2GRAY);
cvClearMemStorage (filter->cvStorage);
if (filter->cvCascade) {
faces =
cvHaarDetectObjects (filter->cvGray, filter->cvCascade,
filter->cvStorage, 1.1, 2, 0, cvSize (30, 30));
for (i = 0; i < (faces ? faces->total : 0); i++) {
CvRect *r = (CvRect *) cvGetSeqElem (faces, i);
GstStructure *s = gst_structure_new ("face",
"x", G_TYPE_UINT, r->x,
"y", G_TYPE_UINT, r->y,
"width", G_TYPE_UINT, r->width,
"height", G_TYPE_UINT, r->height, NULL);
GstMessage *m = gst_message_new_element (GST_OBJECT (filter), s);
gst_element_post_message (GST_ELEMENT (filter), m);
if (filter->display) {
CvPoint center;
int radius;
center.x = cvRound ((r->x + r->width * 0.5));
center.y = cvRound ((r->y + r->height * 0.5));
radius = cvRound ((r->width + r->height) * 0.25);
cvCircle (filter->cvImage, center, radius, CV_RGB (255, 32, 32), 3, 8,
0);
}
}
}
- gst_buffer_set_data (buf, filter->cvImage->imageData,
+ gst_buffer_set_data (buf, (guint8 *) filter->cvImage->imageData,
filter->cvImage->imageSize);
return gst_pad_push (filter->srcpad, buf);
}
static void
gst_facedetect_load_profile (Gstfacedetect * filter)
{
filter->cvCascade =
(CvHaarClassifierCascade *) cvLoad (filter->profile, 0, 0, 0);
if (!filter->cvCascade) {
GST_WARNING ("Couldn't load Haar classifier cascade: %s.", filter->profile);
}
}
/* entry point to initialize the plug-in
* initialize the plug-in itself
* register the element factories and other features
*/
gboolean
gst_facedetect_plugin_init (GstPlugin * plugin)
{
/* debug category for fltering log messages */
GST_DEBUG_CATEGORY_INIT (gst_facedetect_debug, "facedetect",
0,
"Performs face detection on videos and images, providing detected positions via bus messages");
return gst_element_register (plugin, "facedetect", GST_RANK_NONE,
GST_TYPE_FACEDETECT);
}
diff --git a/src/pyramidsegment/gstpyramidsegment.c b/src/pyramidsegment/gstpyramidsegment.c
index e57a703..7e3e8fe 100644
--- a/src/pyramidsegment/gstpyramidsegment.c
+++ b/src/pyramidsegment/gstpyramidsegment.c
@@ -1,325 +1,325 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2008 Michael Sheldon <mike@mikeasoft.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/**
* SECTION:element-pyramidsegment
*
* FIXME:Describe pyramidsegment here.
*
* <refsect2>
* <title>Example launch line</title>
* |[
* gst-launch -v -m fakesrc ! pyramidsegment ! fakesink silent=TRUE
* ]|
* </refsect2>
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <gst/gst.h>
#include "gstpyramidsegment.h"
#define BLOCK_SIZE 1000
GST_DEBUG_CATEGORY_STATIC (gst_pyramidsegment_debug);
#define GST_CAT_DEFAULT gst_pyramidsegment_debug
/* Filter signals and args */
enum
{
/* FILL ME */
LAST_SIGNAL
};
enum
{
PROP_0,
PROP_SILENT,
PROP_THRESHOLD1,
PROP_THRESHOLD2,
PROP_LEVEL
};
/* the capabilities of the inputs and outputs.
*
* describe the real formats here.
*/
static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
GST_PAD_SINK,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("video/x-raw-rgb")
);
static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
GST_PAD_SRC,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("video/x-raw-rgb")
);
GST_BOILERPLATE (Gstpyramidsegment, gst_pyramidsegment, GstElement,
GST_TYPE_ELEMENT);
static void gst_pyramidsegment_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec);
static void gst_pyramidsegment_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec);
static gboolean gst_pyramidsegment_set_caps (GstPad * pad, GstCaps * caps);
static GstFlowReturn gst_pyramidsegment_chain (GstPad * pad, GstBuffer * buf);
/* Clean up */
static void
gst_pyramidsegment_finalize (GObject * obj)
{
Gstpyramidsegment *filter = GST_PYRAMIDSEGMENT (obj);
if (filter->cvImage != NULL) {
cvReleaseImage (&filter->cvImage);
cvReleaseImage (&filter->cvSegmentedImage);
}
G_OBJECT_CLASS (parent_class)->finalize (obj);
}
/* GObject vmethod implementations */
static void
gst_pyramidsegment_base_init (gpointer gclass)
{
GstElementClass *element_class = GST_ELEMENT_CLASS (gclass);
gst_element_class_set_details_simple (element_class,
"pyramidsegment",
"Filter/Effect/Video",
"Applies pyramid segmentation to a video or image.",
"Michael Sheldon <mike@mikeasoft.com>");
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&src_factory));
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&sink_factory));
}
/* initialize the pyramidsegment's class */
static void
gst_pyramidsegment_class_init (GstpyramidsegmentClass * klass)
{
GObjectClass *gobject_class;
GstElementClass *gstelement_class;
gobject_class = (GObjectClass *) klass;
gstelement_class = (GstElementClass *) klass;
parent_class = g_type_class_peek_parent (klass);
gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_pyramidsegment_finalize);
gobject_class->set_property = gst_pyramidsegment_set_property;
gobject_class->get_property = gst_pyramidsegment_get_property;
g_object_class_install_property (gobject_class, PROP_SILENT,
g_param_spec_boolean ("silent", "Silent", "Produce verbose output ?",
FALSE, G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_THRESHOLD1,
g_param_spec_double ("threshold1", "Threshold1",
"Error threshold for establishing links", 0, 1000, 50,
G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_THRESHOLD2,
g_param_spec_double ("threshold2", "Threshold2",
"Error threshold for segment clustering", 0, 1000, 60,
G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_LEVEL,
g_param_spec_int ("level", "Level",
"Maximum level of the pyramid segmentation", 0, 4, 4,
G_PARAM_READWRITE));
}
/* initialize the new element
* instantiate pads and add them to element
* set pad calback functions
* initialize instance structure
*/
static void
gst_pyramidsegment_init (Gstpyramidsegment * filter,
GstpyramidsegmentClass * gclass)
{
filter->sinkpad = gst_pad_new_from_static_template (&sink_factory, "sink");
gst_pad_set_setcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR (gst_pyramidsegment_set_caps));
gst_pad_set_getcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR (gst_pad_proxy_getcaps));
gst_pad_set_chain_function (filter->sinkpad,
GST_DEBUG_FUNCPTR (gst_pyramidsegment_chain));
filter->srcpad = gst_pad_new_from_static_template (&src_factory, "src");
gst_pad_set_getcaps_function (filter->srcpad,
GST_DEBUG_FUNCPTR (gst_pad_proxy_getcaps));
gst_element_add_pad (GST_ELEMENT (filter), filter->sinkpad);
gst_element_add_pad (GST_ELEMENT (filter), filter->srcpad);
filter->storage = cvCreateMemStorage (BLOCK_SIZE);
filter->comp =
cvCreateSeq (0, sizeof (CvSeq), sizeof (CvPoint), filter->storage);
filter->silent = FALSE;
filter->threshold1 = 50.0;
filter->threshold2 = 60.0;
filter->level = 4;
}
static void
gst_pyramidsegment_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec)
{
Gstpyramidsegment *filter = GST_PYRAMIDSEGMENT (object);
switch (prop_id) {
case PROP_SILENT:
filter->silent = g_value_get_boolean (value);
break;
case PROP_THRESHOLD1:
filter->threshold1 = g_value_get_double (value);
break;
case PROP_THRESHOLD2:
filter->threshold2 = g_value_get_double (value);
break;
case PROP_LEVEL:
filter->level = g_value_get_int (value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gst_pyramidsegment_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec)
{
Gstpyramidsegment *filter = GST_PYRAMIDSEGMENT (object);
switch (prop_id) {
case PROP_SILENT:
g_value_set_boolean (value, filter->silent);
break;
case PROP_THRESHOLD1:
g_value_set_double (value, filter->threshold1);
break;
case PROP_THRESHOLD2:
g_value_set_double (value, filter->threshold2);
break;
case PROP_LEVEL:
g_value_set_int (value, filter->level);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
/* GstElement vmethod implementations */
/* this function handles the link with other elements */
static gboolean
gst_pyramidsegment_set_caps (GstPad * pad, GstCaps * caps)
{
Gstpyramidsegment *filter;
GstPad *otherpad;
GstStructure *structure;
gint width, height;
filter = GST_PYRAMIDSEGMENT (gst_pad_get_parent (pad));
structure = gst_caps_get_structure (caps, 0);
gst_structure_get_int (structure, "width", &width);
gst_structure_get_int (structure, "height", &height);
filter->cvImage = cvCreateImage (cvSize (width, height), IPL_DEPTH_8U, 3);
otherpad = (pad == filter->srcpad) ? filter->sinkpad : filter->srcpad;
gst_object_unref (filter);
return gst_pad_set_caps (otherpad, caps);
}
/* chain function
* this function does the actual processing
*/
static GstFlowReturn
gst_pyramidsegment_chain (GstPad * pad, GstBuffer * buf)
{
Gstpyramidsegment *filter;
filter = GST_PYRAMIDSEGMENT (GST_OBJECT_PARENT (pad));
filter->cvImage->imageData = (char *) GST_BUFFER_DATA (buf);
filter->cvSegmentedImage = cvCloneImage (filter->cvImage);
cvPyrSegmentation (filter->cvImage, filter->cvSegmentedImage, filter->storage,
&(filter->comp), filter->level, filter->threshold1, filter->threshold2);
- gst_buffer_set_data (buf, filter->cvSegmentedImage->imageData,
+ gst_buffer_set_data (buf, (guint8 *) filter->cvSegmentedImage->imageData,
filter->cvSegmentedImage->imageSize);
return gst_pad_push (filter->srcpad, buf);
}
/* entry point to initialize the plug-in
* initialize the plug-in itself
* register the element factories and other features
*/
gboolean
gst_pyramidsegment_plugin_init (GstPlugin * plugin)
{
/* debug category for fltering log messages */
GST_DEBUG_CATEGORY_INIT (gst_pyramidsegment_debug, "pyramidsegment",
0, "Applies pyramid segmentation to a video or image");
return gst_element_register (plugin, "pyramidsegment", GST_RANK_NONE,
GST_TYPE_PYRAMIDSEGMENT);
}
diff --git a/src/templatematch/gsttemplatematch.c b/src/templatematch/gsttemplatematch.c
index 4f42237..6dad35b 100644
--- a/src/templatematch/gsttemplatematch.c
+++ b/src/templatematch/gsttemplatematch.c
@@ -1,413 +1,412 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2008 Michael Sheldon <mike@mikeasoft.com>
* Copyright (C) 2009 Noam Lewis <jones.noamle@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/**
* SECTION:element-templatematch
*
* FIXME:Describe templatematch here.
*
* <refsect2>
* <title>Example launch line</title>
* |[
* gst-launch-0.10 videotestsrc ! decodebin ! ffmpegcolorspace ! templatematch template=/path/to/file.jpg ! ffmpegcolorspace ! xvimagesink
* ]|
* </refsect2>
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <gst/gst.h>
#include "gsttemplatematch.h"
GST_DEBUG_CATEGORY_STATIC (gst_templatematch_debug);
#define GST_CAT_DEFAULT gst_templatematch_debug
#define DEFAULT_METHOD (3)
/* Filter signals and args */
enum
{
/* FILL ME */
LAST_SIGNAL
};
enum
{
PROP_0,
PROP_METHOD,
PROP_TEMPLATE,
PROP_DISPLAY,
};
/* the capabilities of the inputs and outputs.
*/
static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
GST_PAD_SINK,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("video/x-raw-rgb")
);
static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
GST_PAD_SRC,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("video/x-raw-rgb")
);
GST_BOILERPLATE (GstTemplateMatch, gst_templatematch, GstElement,
GST_TYPE_ELEMENT);
static void gst_templatematch_finalize (GObject * object);
static void gst_templatematch_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec);
static void gst_templatematch_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec);
static gboolean gst_templatematch_set_caps (GstPad * pad, GstCaps * caps);
static GstFlowReturn gst_templatematch_chain (GstPad * pad, GstBuffer * buf);
static void gst_templatematch_load_template (GstTemplateMatch * filter);
static void gst_templatematch_match (IplImage * input, IplImage * template,
IplImage * dist_image, double *best_res, CvPoint * best_pos, int method);
/* GObject vmethod implementations */
static void
gst_templatematch_base_init (gpointer gclass)
{
GstElementClass *element_class = GST_ELEMENT_CLASS (gclass);
gst_element_class_set_details_simple (element_class,
"templatematch",
"Filter/Effect/Video",
"Performs template matching on videos and images, providing detected positions via bus messages",
"Noam Lewis <jones.noamle@gmail.com>");
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&src_factory));
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&sink_factory));
}
/* initialize the templatematch's class */
static void
gst_templatematch_class_init (GstTemplateMatchClass * klass)
{
GObjectClass *gobject_class;
GstElementClass *gstelement_class;
gobject_class = (GObjectClass *) klass;
gstelement_class = (GstElementClass *) klass;
gobject_class->finalize = gst_templatematch_finalize;
gobject_class->set_property = gst_templatematch_set_property;
gobject_class->get_property = gst_templatematch_get_property;
g_object_class_install_property (gobject_class, PROP_METHOD,
g_param_spec_int ("method", "Method",
"Specifies the way the template must be compared with image regions. 0=SQDIFF, 1=SQDIFF_NORMED, 2=CCOR, 3=CCOR_NORMED, 4=CCOEFF, 5=CCOEFF_NORMED.",
0, 5, DEFAULT_METHOD, G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_TEMPLATE,
g_param_spec_string ("template", "Template", "Filename of template image",
NULL, G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_DISPLAY,
g_param_spec_boolean ("display", "Display",
"Sets whether the detected template should be highlighted in the output",
TRUE, G_PARAM_READWRITE));
}
/* initialize the new element
* instantiate pads and add them to element
* set pad calback functions
* initialize instance structure
*/
static void
gst_templatematch_init (GstTemplateMatch * filter,
GstTemplateMatchClass * gclass)
{
filter->sinkpad = gst_pad_new_from_static_template (&sink_factory, "sink");
gst_pad_set_setcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR (gst_templatematch_set_caps));
gst_pad_set_getcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR (gst_pad_proxy_getcaps));
gst_pad_set_chain_function (filter->sinkpad,
GST_DEBUG_FUNCPTR (gst_templatematch_chain));
filter->srcpad = gst_pad_new_from_static_template (&src_factory, "src");
gst_pad_set_getcaps_function (filter->srcpad,
GST_DEBUG_FUNCPTR (gst_pad_proxy_getcaps));
gst_element_add_pad (GST_ELEMENT (filter), filter->sinkpad);
gst_element_add_pad (GST_ELEMENT (filter), filter->srcpad);
filter->template = NULL;
filter->display = TRUE;
filter->cvTemplateImage = NULL;
filter->cvDistImage = NULL;
filter->cvImage = NULL;
filter->method = DEFAULT_METHOD;
gst_templatematch_load_template (filter);
}
static void
gst_templatematch_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec)
{
GstTemplateMatch *filter = GST_TEMPLATEMATCH (object);
switch (prop_id) {
case PROP_METHOD:
switch (g_value_get_int (value)) {
case 0:
filter->method = CV_TM_SQDIFF;
break;
case 1:
filter->method = CV_TM_SQDIFF_NORMED;
break;
case 2:
filter->method = CV_TM_CCORR;
break;
case 3:
filter->method = CV_TM_CCORR_NORMED;
break;
case 4:
filter->method = CV_TM_CCOEFF;
break;
case 5:
filter->method = CV_TM_CCOEFF_NORMED;
break;
}
break;
case PROP_TEMPLATE:
- filter->template = g_value_get_string (value);
+ filter->template = (char *) g_value_get_string (value);
gst_templatematch_load_template (filter);
break;
case PROP_DISPLAY:
filter->display = g_value_get_boolean (value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gst_templatematch_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec)
{
GstTemplateMatch *filter = GST_TEMPLATEMATCH (object);
switch (prop_id) {
case PROP_METHOD:
g_value_set_int (value, filter->method);
break;
case PROP_TEMPLATE:
g_value_set_string (value, filter->template);
break;
case PROP_DISPLAY:
g_value_set_boolean (value, filter->display);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
/* GstElement vmethod implementations */
/* this function handles the link with other elements */
static gboolean
gst_templatematch_set_caps (GstPad * pad, GstCaps * caps)
{
GstTemplateMatch *filter;
GstPad *otherpad;
gint width, height;
GstStructure *structure;
filter = GST_TEMPLATEMATCH (gst_pad_get_parent (pad));
structure = gst_caps_get_structure (caps, 0);
gst_structure_get_int (structure, "width", &width);
gst_structure_get_int (structure, "height", &height);
filter->cvImage =
cvCreateImageHeader (cvSize (width, height), IPL_DEPTH_8U, 3);
otherpad = (pad == filter->srcpad) ? filter->sinkpad : filter->srcpad;
gst_object_unref (filter);
return gst_pad_set_caps (otherpad, caps);
}
static void
gst_templatematch_finalize (GObject * object)
{
GstTemplateMatch *filter;
filter = GST_TEMPLATEMATCH (object);
if (filter->cvImage) {
cvReleaseImageHeader (&filter->cvImage);
}
if (filter->cvDistImage) {
cvReleaseImage (&filter->cvDistImage);
}
if (filter->cvTemplateImage) {
cvReleaseImage (&filter->cvTemplateImage);
}
}
/* chain function
* this function does the actual processing
*/
static GstFlowReturn
gst_templatematch_chain (GstPad * pad, GstBuffer * buf)
{
GstTemplateMatch *filter;
CvPoint best_pos;
double best_res;
- int i;
filter = GST_TEMPLATEMATCH (GST_OBJECT_PARENT (pad));
buf = gst_buffer_make_writable (buf);
if ((!filter) || (!buf) || filter->template == NULL) {
return GST_FLOW_OK;
}
filter->cvImage->imageData = (char *) GST_BUFFER_DATA (buf);
if (!filter->cvDistImage) {
filter->cvDistImage =
cvCreateImage (cvSize (filter->cvImage->width -
filter->cvTemplateImage->width + 1,
filter->cvImage->height - filter->cvTemplateImage->height + 1),
IPL_DEPTH_32F, 1);
if (!filter->cvDistImage) {
GST_WARNING ("Couldn't create dist image.");
}
}
if (filter->cvTemplateImage) {
gst_templatematch_match (filter->cvImage, filter->cvTemplateImage,
filter->cvDistImage, &best_res, &best_pos, filter->method);
GstStructure *s = gst_structure_new ("template_match",
"x", G_TYPE_UINT, best_pos.x,
"y", G_TYPE_UINT, best_pos.y,
"width", G_TYPE_UINT, filter->cvTemplateImage->width,
"height", G_TYPE_UINT, filter->cvTemplateImage->height,
"result", G_TYPE_DOUBLE, best_res,
NULL);
GstMessage *m = gst_message_new_element (GST_OBJECT (filter), s);
gst_element_post_message (GST_ELEMENT (filter), m);
if (filter->display) {
CvPoint corner = best_pos;
corner.x += filter->cvTemplateImage->width;
corner.y += filter->cvTemplateImage->height;
cvRectangle (filter->cvImage, best_pos, corner, CV_RGB (255, 32, 32), 3,
8, 0);
}
}
- gst_buffer_set_data (buf, filter->cvImage->imageData,
+ gst_buffer_set_data (buf, (guint8 *) filter->cvImage->imageData,
filter->cvImage->imageSize);
return gst_pad_push (filter->srcpad, buf);
}
static void
gst_templatematch_match (IplImage * input, IplImage * template,
IplImage * dist_image, double *best_res, CvPoint * best_pos, int method)
{
double dist_min = 0, dist_max = 0;
CvPoint min_pos, max_pos;
cvMatchTemplate (input, template, dist_image, method);
cvMinMaxLoc (dist_image, &dist_min, &dist_max, &min_pos, &max_pos, NULL);
if ((CV_TM_SQDIFF_NORMED == method) || (CV_TM_SQDIFF == method)) {
*best_res = dist_min;
*best_pos = min_pos;
if (CV_TM_SQDIFF_NORMED == method) {
*best_res = 1 - *best_res;
}
} else {
*best_res = dist_max;
*best_pos = max_pos;
}
}
static void
gst_templatematch_load_template (GstTemplateMatch * filter)
{
if (filter->template) {
filter->cvTemplateImage =
cvLoadImage (filter->template, CV_LOAD_IMAGE_COLOR);
if (!filter->cvTemplateImage) {
GST_WARNING ("Couldn't load template image: %s.", filter->template);
}
}
}
/* entry point to initialize the plug-in
* initialize the plug-in itself
* register the element factories and other features
*/
gboolean
gst_templatematch_plugin_init (GstPlugin * templatematch)
{
/* debug category for fltering log messages */
GST_DEBUG_CATEGORY_INIT (gst_templatematch_debug, "templatematch",
0,
"Performs template matching on videos and images, providing detected positions via bus messages");
return gst_element_register (templatematch, "templatematch", GST_RANK_NONE,
GST_TYPE_TEMPLATEMATCH);
}
diff --git a/src/textwrite/gsttextwrite.c b/src/textwrite/gsttextwrite.c
index a966571..7e56846 100644
--- a/src/textwrite/gsttextwrite.c
+++ b/src/textwrite/gsttextwrite.c
@@ -1,413 +1,414 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2010 Sreerenj Balachandran <bsreerenj@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/**
* SECTION:element-textwrite
*
* FIXME:Describe textwrite here.
*
* <refsect2>
* <title>Example launch line</title>
* |[
* gst-launch -v -m fakesrc ! textwrite ! fakesink silent=TRUE
* ]|
* </refsect2>
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <gst/gst.h>
#include "gsttextwrite.h"
GST_DEBUG_CATEGORY_STATIC (gst_textwrite_debug);
#define GST_CAT_DEFAULT gst_textwrite_debug
#define DEFAULT_PROP_TEXT ""
#define DEFAULT_PROP_WIDTH 1
#define DEFAULT_PROP_HEIGHT 1
#define DEFAULT_PROP_XPOS 50
#define DEFAULT_PROP_YPOS 50
#define DEFAULT_PROP_THICKNESS 2
#define DEFAULT_PROP_COLOR 0
/* Filter signals and args */
enum
{
/* FILL ME */
LAST_SIGNAL
};
#define DEFAULT_WIDTH 1.0
#define DEFAULT_HEIGHT 1.0
enum
{
PROP_0,
PROP_XPOS,
PROP_YPOS,
PROP_THICKNESS,
PROP_COLOR_R,
PROP_COLOR_G,
PROP_COLOR_B,
PROP_TEXT,
PROP_HEIGHT,
PROP_WIDTH
};
/* the capabilities of the inputs and outputs.
*
* describe the real formats here.
*/
static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
GST_PAD_SINK,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("video/x-raw-rgb")
);
static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
GST_PAD_SRC,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("ANY")
);
GST_BOILERPLATE (Gsttextwrite, gst_textwrite, GstElement,GST_TYPE_ELEMENT);
static void gst_textwrite_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec);
static void gst_textwrite_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec);
static gboolean gst_textwrite_set_caps (GstPad * pad, GstCaps * caps);
static GstFlowReturn gst_textwrite_chain (GstPad * pad, GstBuffer * buf);
/* Clean up */
static void
gst_textwrite_finalize (GObject * obj)
{
Gsttextwrite *filter = GST_textwrite (obj);
if (filter->cvImage) {
cvReleaseImage (&filter->cvImage);
}
G_OBJECT_CLASS (parent_class)->finalize (obj);
}
/* GObject vmethod implementations */
static void
gst_textwrite_base_init (gpointer gclass)
{
GstElementClass *element_class = GST_ELEMENT_CLASS (gclass);
gst_element_class_set_details_simple(element_class,
"textwrite",
"Filter/Effect/Video",
"Performs text writing to the video",
"sreerenj<bsreerenj@gmail.com>");
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&src_factory));
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&sink_factory));
}
/* initialize the textwrite's class */
static void
gst_textwrite_class_init (GsttextwriteClass * klass)
{
GObjectClass *gobject_class;
GstElementClass *gstelement_class;
gobject_class = (GObjectClass *) klass;
gstelement_class = (GstElementClass *) klass;
parent_class = g_type_class_peek_parent (klass);
gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_textwrite_finalize);
gobject_class->set_property = gst_textwrite_set_property;
gobject_class->get_property = gst_textwrite_get_property;
g_object_class_install_property (gobject_class, PROP_TEXT,
g_param_spec_string ("text", "text",
"Text to be display.", DEFAULT_PROP_TEXT,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
g_object_class_install_property (gobject_class, PROP_XPOS,
g_param_spec_int ("xpos", "horizontal position",
"Sets the Horizontal position", 0, G_MAXINT,
DEFAULT_PROP_XPOS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
g_object_class_install_property (gobject_class, PROP_YPOS,
g_param_spec_int ("ypos", "vertical position",
"Sets the Vertical position", 0, G_MAXINT,
DEFAULT_PROP_YPOS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
g_object_class_install_property (gobject_class, PROP_THICKNESS,
g_param_spec_int ("thickness", "font thickness",
"Sets the Thickness of Font", 0, G_MAXINT,
DEFAULT_PROP_THICKNESS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
g_object_class_install_property (gobject_class, PROP_COLOR_R,
g_param_spec_int ("colorR", "color -Red ",
"Sets the color -R", 0, 255,
DEFAULT_PROP_COLOR, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
g_object_class_install_property (gobject_class, PROP_COLOR_G,
g_param_spec_int ("colorG", "color -Green",
"Sets the color -G", 0, 255,
DEFAULT_PROP_COLOR, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
g_object_class_install_property (gobject_class, PROP_COLOR_B,
g_param_spec_int ("colorB", "color -Blue",
"Sets the color -B", 0, 255,
DEFAULT_PROP_COLOR, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
g_object_class_install_property (gobject_class, PROP_HEIGHT,
g_param_spec_double ("height", "Height",
"Sets the height of fonts",1.0,5.0,
DEFAULT_HEIGHT, G_PARAM_READWRITE|G_PARAM_STATIC_STRINGS));
g_object_class_install_property (gobject_class, PROP_WIDTH,
g_param_spec_double ("width", "Width",
"Sets the width of fonts",1.0,5.0,
DEFAULT_WIDTH, G_PARAM_READWRITE| G_PARAM_STATIC_STRINGS));
}
/* initialize the new element
* instantiate pads and add them to element
* set pad calback functions
* initialize instance structure
*/
static void
gst_textwrite_init (Gsttextwrite * filter,
GsttextwriteClass * gclass)
{
filter->sinkpad = gst_pad_new_from_static_template (&sink_factory, "sink");
gst_pad_set_setcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR(gst_textwrite_set_caps));
gst_pad_set_getcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR(gst_pad_proxy_getcaps));
gst_pad_set_chain_function (filter->sinkpad,
GST_DEBUG_FUNCPTR(gst_textwrite_chain));
filter->srcpad = gst_pad_new_from_static_template (&src_factory, "src");
gst_pad_set_getcaps_function (filter->srcpad,
GST_DEBUG_FUNCPTR(gst_pad_proxy_getcaps));
gst_element_add_pad (GST_ELEMENT (filter), filter->sinkpad);
gst_element_add_pad (GST_ELEMENT (filter), filter->srcpad);
filter->textbuf = g_strdup (DEFAULT_PROP_TEXT);
filter->width = DEFAULT_PROP_WIDTH;
filter->height = DEFAULT_PROP_HEIGHT;
filter->xpos = DEFAULT_PROP_XPOS;
filter->ypos = DEFAULT_PROP_YPOS;
filter->thickness = DEFAULT_PROP_THICKNESS;
filter->colorR = DEFAULT_PROP_COLOR;
filter->colorG = DEFAULT_PROP_COLOR;
filter->colorB = DEFAULT_PROP_COLOR;
}
static void
gst_textwrite_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec)
{
Gsttextwrite *filter = GST_textwrite (object);
switch (prop_id) {
case PROP_TEXT:
g_free (filter->textbuf);
filter->textbuf = g_value_dup_string (value);
break;
case PROP_XPOS:
filter->xpos = g_value_get_int(value);
break;
case PROP_YPOS:
filter->ypos = g_value_get_int(value);
break;
case PROP_THICKNESS:
filter->thickness = g_value_get_int(value);
break;
case PROP_COLOR_R:
filter->colorR = g_value_get_int(value);
break;
case PROP_COLOR_G:
filter->colorG = g_value_get_int(value);
break;
case PROP_COLOR_B:
filter->colorB = g_value_get_int(value);
break;
case PROP_HEIGHT:
filter->height = g_value_get_double(value);
break;
case PROP_WIDTH:
filter->width = g_value_get_double(value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gst_textwrite_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec)
{
Gsttextwrite *filter = GST_textwrite (object);
switch (prop_id) {
case PROP_TEXT:
g_value_set_string (value, filter->textbuf);
break;
case PROP_XPOS:
g_value_set_int (value, filter->xpos);
break;
case PROP_YPOS:
g_value_set_int (value, filter->ypos);
break;
case PROP_THICKNESS:
g_value_set_int (value, filter->thickness);
break;
case PROP_COLOR_R:
g_value_set_int (value, filter->colorR);
break;
case PROP_COLOR_G:
g_value_set_int (value, filter->colorG);
break;
case PROP_COLOR_B:
g_value_set_int (value, filter->colorB);
break;
case PROP_HEIGHT:
g_value_set_double (value, filter->height);
break;
case PROP_WIDTH:
g_value_set_double (value, filter->width);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
/* GstElement vmethod implementations */
/* this function handles the link with other elements */
static gboolean
gst_textwrite_set_caps (GstPad * pad, GstCaps * caps)
{
Gsttextwrite *filter;
GstPad *otherpad;
gint width, height;
GstStructure *structure;
filter = GST_textwrite (gst_pad_get_parent (pad));
structure = gst_caps_get_structure (caps, 0);
gst_structure_get_int (structure, "width", &width);
gst_structure_get_int (structure, "height", &height);
filter->cvImage = cvCreateImage (cvSize (width, height), IPL_DEPTH_8U, 3);
filter->cvStorage = cvCreateMemStorage (0);
otherpad = (pad == filter->srcpad) ? filter->sinkpad : filter->srcpad;
gst_object_unref (filter);
return gst_pad_set_caps (otherpad, caps);
}
/* chain function
* this function does the actual processing
*/
static GstFlowReturn
gst_textwrite_chain (GstPad * pad, GstBuffer * buf)
{
Gsttextwrite *filter;
filter = GST_textwrite (GST_OBJECT_PARENT (pad));
filter->cvImage->imageData = (char *) GST_BUFFER_DATA (buf);
cvInitFont(&(filter->font),CV_FONT_VECTOR0, filter->width,filter->height,0,filter->thickness,0);
cvPutText (filter->cvImage,filter->textbuf,cvPoint(filter->xpos,filter->ypos), &(filter->font), cvScalar(filter->colorR,filter->colorG,filter->colorB,0));
- gst_buffer_set_data (buf, filter->cvImage->imageData,filter->cvImage->imageSize);
+ gst_buffer_set_data (buf, (guint8 *) filter->cvImage->imageData,
+ filter->cvImage->imageSize);
return gst_pad_push (filter->srcpad, buf);
}
/* entry point to initialize the plug-in
* initialize the plug-in itself
* register the element factories and other features
*/
gboolean
gst_textwrite_plugin_init (GstPlugin * plugin)
{
/* debug category for fltering log messages
*
* exchange the string 'Template textwrite' with your description
*/
GST_DEBUG_CATEGORY_INIT (gst_textwrite_debug, "textwrite",
0, "Template textwrite");
return gst_element_register (plugin, "textwrite", GST_RANK_NONE,
GST_TYPE_textwrite);
}
|
Elleo/gst-opencv
|
4514ee1608f001e85f264001355a76b5607b2144
|
Add config check for libswscale
|
diff --git a/ChangeLog b/ChangeLog
index 6c5477f..2f6c855 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,104 +1,109 @@
+2010-04-14 Mike Sheldon <mike@mikeasoft.com>
+
+ * configure.ac:
+ Add configure check for libswscale (patch from Thiago Santos)
+
2010-02-28 Mike Sheldon <mike@mikeasoft.com>
* AUTHORS:
Update list of contributors
* src/faceblur/gstfaceblur.c:
* src/facedetect/gstfacedetect.c:
Fix leaks which were crashing gst-inspect (patch from Stefan Kost)
2010-02-28 Sreerenj Balachandran <bsreerenj@gmail.com>
* src/textwrite/Makefile.am:
* src/textwrite/gsttextwrite.c:
* src/textwrite/gsttextwrite.h:
* src/gstopencv.c:
* src/Makefile.am:
Add a basic plugin to overlay text on to video streams
2009-12-18 Mike Sheldon <mike@mikeasoft.com>
* src/templatematch/gsttemplatematch.c:
Fix include statements to not include a hard-coded "opencv/" path
2009-05-26 Mike Sheldon <mike@mikeasoft.com>
* AUTHORS:
Add all current contributors to the authors list
* src/edgedetect/gstedgedetect.c:
* src/edgedetect/gstedgedetect.h:
* src/faceblur/gstfaceblur.c:
* src/faceblur/gstfaceblur.h:
* src/facedetect/gstfacedetect.c:
* src/facedetect/gstfacedetect.h:
* src/gstopencv.c:
* src/pyramidsegment/gstpyramidsegment.c:
* src/pyramidsegment/gstpyramidsegment.h:
* src/templatematch/gsttemplatematch.c:
* src/templatematch/gsttemplatematch.h:
Bring code in to line with general gstreamer standards
2009-05-25 Mike Sheldon <mike@mikeasoft.com>
* configure.ac:
* src/Makefile.am:
* src/gstopencv.c:
* src/faceblur/gstfaceblur.c:
* src/faceblur/gstfaceblur.h:
* src/faceblur/Makefile.am:
Add face blurring element
* debian/control:
* debian/changelog:
Fix dependencies and package section for debian package
* src/templatematch/gsttemplatematch.c:
Fix segfault when no template is loaded
Update example launch line to load a template
* examples/python/templatematch.py:
* examples/python/template.jpg:
Add example usage of the template matching element
2009-05-13 Noam Lewis <jones.noamle@gmail.com>
* configure.ac:
* src/Makefile.am:
* src/gstopencv.c:
* src/templatematch/gsttemplatematch.c:
* src/templatematch/gsttemplatematch.h:
* src/tempaltematch/Makefile.am:
Add template matching element
2009-05-08 Kapil Agrawal <kapil@mediamagictechnologies.com>
* configure.ac:
* src/Makefile.am:
* src/gstopencv.c:
* src/edgedetect/Makefile.am:
* src/edgedetect/gstedgedetect.c:
* src/facedetect/Makefile.am:
* src/facedetect/gstfacedetect.c:
* src/pyramidsegment/Makefile.am:
* src/pyramidsegment/gstpyramidsegment.c:
All elements will register as features of opencv plugin.
2009-05-06 Mike Sheldon <mike@mikeasoft.com>
* src/facedetect/gstfacedetect.c:
Fix "profile" parameter in face detect element to accept a string correctly
(was using char param instead of string param)
* src/edgedetect/gstedgedetect.c:
* src/pyramidsegment/gstpyramidsegment.c:
* src/facedetect/gstfacedetect.c:
Release OpenCV images when finalizing
2009-05-06 Kapil Agrawal <kapil@mediamagictechnologies.com>
* configure.ac: Added an error check for opencv.
* src/edgedetect/gstedgedetect.h:
* src/facedetect/gstfacedetect.h:
* src/pyramidsegment/gstpyramidsegment.h: Fixed the included path.
Fixed some compilation errors.
diff --git a/configure.ac b/configure.ac
index 11edb9f..9272730 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1,142 +1,149 @@
AC_INIT
dnl versions of gstreamer and plugins-base
GST_MAJORMINOR=0.10
GST_REQUIRED=0.10.0
GSTPB_REQUIRED=0.10.0
dnl fill in your package name and version here
dnl the fourth (nano) number should be 0 for a release, 1 for CVS,
dnl and 2... for a prerelease
dnl when going to/from release please set the nano correctly !
dnl releases only do Wall, cvs and prerelease does Werror too
AS_VERSION(gst-opencv, GST_PLUGIN_VERSION, 0, 10, 0, 1,
GST_PLUGIN_CVS="no", GST_PLUGIN_CVS="yes")
dnl AM_MAINTAINER_MODE provides the option to enable maintainer mode
AM_MAINTAINER_MODE
AM_INIT_AUTOMAKE($PACKAGE, $VERSION)
dnl make aclocal work in maintainer mode
AC_SUBST(ACLOCAL_AMFLAGS, "-I m4")
AM_CONFIG_HEADER(config.h)
dnl check for tools
AC_PROG_CC
AC_PROG_LIBTOOL
dnl decide on error flags
AS_COMPILER_FLAG(-Wall, GST_WALL="yes", GST_WALL="no")
if test "x$GST_WALL" = "xyes"; then
GST_ERROR="$GST_ERROR -Wall"
# if test "x$GST_PLUGIN_CVS" = "xyes"; then
# AS_COMPILER_FLAG(-Werror,GST_ERROR="$GST_ERROR -Werror",GST_ERROR="$GST_ERROR")
# fi
fi
dnl Check for pkgconfig first
AC_CHECK_PROG(HAVE_PKGCONFIG, pkg-config, yes, no)
dnl Give error and exit if we don't have pkgconfig
if test "x$HAVE_PKGCONFIG" = "xno"; then
AC_MSG_ERROR(you need to have pkgconfig installed !)
fi
dnl Now we're ready to ask for gstreamer libs and cflags
dnl And we can also ask for the right version of gstreamer
PKG_CHECK_MODULES(GST, \
gstreamer-$GST_MAJORMINOR >= $GST_REQUIRED,
HAVE_GST=yes,HAVE_GST=no)
dnl Give error and exit if we don't have gstreamer
if test "x$HAVE_GST" = "xno"; then
AC_MSG_ERROR(you need gstreamer development packages installed !)
fi
dnl append GST_ERROR cflags to GST_CFLAGS
GST_CFLAGS="$GST_CFLAGS $GST_ERROR"
dnl make GST_CFLAGS and GST_LIBS available
AC_SUBST(GST_CFLAGS)
AC_SUBST(GST_LIBS)
dnl make GST_MAJORMINOR available in Makefile.am
AC_SUBST(GST_MAJORMINOR)
dnl If we need them, we can also use the base class libraries
PKG_CHECK_MODULES(GST_BASE, gstreamer-base-$GST_MAJORMINOR >= $GST_REQUIRED,
HAVE_GST_BASE=yes, HAVE_GST_BASE=no)
dnl Give a warning if we don't have gstreamer libs
dnl you can turn this into an error if you need them
if test "x$HAVE_GST_BASE" = "xno"; then
AC_MSG_NOTICE(no GStreamer base class libraries found (gstreamer-base-$GST_MAJORMINOR))
fi
dnl make _CFLAGS and _LIBS available
AC_SUBST(GST_BASE_CFLAGS)
AC_SUBST(GST_BASE_LIBS)
PKG_CHECK_MODULES(OPENCV,
opencv,
HAVE_OPENCV=yes, HAVE_OPENCV=no)
AC_SUBST(OPENCV_CFLAGS)
AC_SUBST(OPENCV_LIBS)
if test "x$HAVE_OPENCV" = "xno"; then
AC_MSG_ERROR(OpenCV libraries could not be found)
fi
+PKG_CHECK_MODULES(SWSCALE,
+ libswscale,
+ HAVE_LIBSWSCALE=yes, HAVE_LIBSWSCALE=no)
+if test "x$HAVE_LIBSWSCALE" = "xno"; then
+ AC_MSG_ERROR(libswscale could not be found)
+fi
+
dnl If we need them, we can also use the gstreamer-plugins-base libraries
PKG_CHECK_MODULES(GSTPB_BASE,
gstreamer-plugins-base-$GST_MAJORMINOR >= $GSTPB_REQUIRED,
HAVE_GSTPB_BASE=yes, HAVE_GSTPB_BASE=no)
dnl Give a warning if we don't have gstreamer libs
dnl you can turn this into an error if you need them
if test "x$HAVE_GSTPB_BASE" = "xno"; then
AC_MSG_NOTICE(no GStreamer Plugins Base libraries found (gstreamer-plugins-base-$GST_MAJORMINOR))
fi
dnl make _CFLAGS and _LIBS available
AC_SUBST(GSTPB_BASE_CFLAGS)
AC_SUBST(GSTPB_BASE_LIBS)
dnl If we need them, we can also use the gstreamer-controller libraries
PKG_CHECK_MODULES(GSTCTRL,
gstreamer-controller-$GST_MAJORMINOR >= $GSTPB_REQUIRED,
HAVE_GSTCTRL=yes, HAVE_GSTCTRL=no)
dnl Give a warning if we don't have gstreamer-controller
dnl you can turn this into an error if you need them
if test "x$HAVE_GSTCTRL" = "xno"; then
AC_MSG_NOTICE(no GStreamer Controller libraries found (gstreamer-controller-$GST_MAJORMINOR))
fi
dnl make _CFLAGS and _LIBS available
AC_SUBST(GSTCTRL_CFLAGS)
AC_SUBST(GSTCTRL_LIBS)
dnl set the plugindir where plugins should be installed
if test "x${prefix}" = "x$HOME"; then
plugindir="$HOME/.gstreamer-$GST_MAJORMINOR/plugins"
else
plugindir="\$(libdir)/gstreamer-$GST_MAJORMINOR"
fi
AC_SUBST(plugindir)
dnl set proper LDFLAGS for plugins
GST_PLUGIN_LDFLAGS='-module -avoid-version -export-symbols-regex [_]*\(gst_\|Gst\|GST_\).*'
AC_SUBST(GST_PLUGIN_LDFLAGS)
AC_OUTPUT(Makefile m4/Makefile src/Makefile src/edgedetect/Makefile src/faceblur/Makefile src/facedetect/Makefile src/pyramidsegment/Makefile src/templatematch/Makefile src/textwrite/Makefile)
|
Elleo/gst-opencv
|
bbc7982b8523a3f5265ebd8b29825e47917c850b
|
Added the property for setting the RGB colours. modified: src/textwrite/gsttextwrite.c modified: src/textwrite/gsttextwrite.h
|
diff --git a/src/textwrite/gsttextwrite.c b/src/textwrite/gsttextwrite.c
index c5de38a..a966571 100644
--- a/src/textwrite/gsttextwrite.c
+++ b/src/textwrite/gsttextwrite.c
@@ -1,368 +1,413 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2010 Sreerenj Balachandran <bsreerenj@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/**
* SECTION:element-textwrite
*
* FIXME:Describe textwrite here.
*
* <refsect2>
* <title>Example launch line</title>
* |[
* gst-launch -v -m fakesrc ! textwrite ! fakesink silent=TRUE
* ]|
* </refsect2>
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <gst/gst.h>
#include "gsttextwrite.h"
GST_DEBUG_CATEGORY_STATIC (gst_textwrite_debug);
#define GST_CAT_DEFAULT gst_textwrite_debug
#define DEFAULT_PROP_TEXT ""
#define DEFAULT_PROP_WIDTH 1
#define DEFAULT_PROP_HEIGHT 1
#define DEFAULT_PROP_XPOS 50
#define DEFAULT_PROP_YPOS 50
#define DEFAULT_PROP_THICKNESS 2
+#define DEFAULT_PROP_COLOR 0
+
/* Filter signals and args */
enum
{
/* FILL ME */
LAST_SIGNAL
};
#define DEFAULT_WIDTH 1.0
#define DEFAULT_HEIGHT 1.0
enum
{
PROP_0,
PROP_XPOS,
PROP_YPOS,
PROP_THICKNESS,
+ PROP_COLOR_R,
+ PROP_COLOR_G,
+ PROP_COLOR_B,
PROP_TEXT,
PROP_HEIGHT,
PROP_WIDTH
};
/* the capabilities of the inputs and outputs.
*
* describe the real formats here.
*/
static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
GST_PAD_SINK,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("video/x-raw-rgb")
);
static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
GST_PAD_SRC,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("ANY")
);
GST_BOILERPLATE (Gsttextwrite, gst_textwrite, GstElement,GST_TYPE_ELEMENT);
static void gst_textwrite_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec);
static void gst_textwrite_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec);
static gboolean gst_textwrite_set_caps (GstPad * pad, GstCaps * caps);
static GstFlowReturn gst_textwrite_chain (GstPad * pad, GstBuffer * buf);
/* Clean up */
static void
gst_textwrite_finalize (GObject * obj)
{
Gsttextwrite *filter = GST_textwrite (obj);
if (filter->cvImage) {
cvReleaseImage (&filter->cvImage);
}
G_OBJECT_CLASS (parent_class)->finalize (obj);
}
/* GObject vmethod implementations */
static void
gst_textwrite_base_init (gpointer gclass)
{
GstElementClass *element_class = GST_ELEMENT_CLASS (gclass);
gst_element_class_set_details_simple(element_class,
"textwrite",
"Filter/Effect/Video",
"Performs text writing to the video",
"sreerenj<bsreerenj@gmail.com>");
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&src_factory));
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&sink_factory));
}
/* initialize the textwrite's class */
static void
gst_textwrite_class_init (GsttextwriteClass * klass)
{
GObjectClass *gobject_class;
GstElementClass *gstelement_class;
gobject_class = (GObjectClass *) klass;
gstelement_class = (GstElementClass *) klass;
parent_class = g_type_class_peek_parent (klass);
gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_textwrite_finalize);
gobject_class->set_property = gst_textwrite_set_property;
gobject_class->get_property = gst_textwrite_get_property;
g_object_class_install_property (gobject_class, PROP_TEXT,
g_param_spec_string ("text", "text",
"Text to be display.", DEFAULT_PROP_TEXT,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
g_object_class_install_property (gobject_class, PROP_XPOS,
g_param_spec_int ("xpos", "horizontal position",
"Sets the Horizontal position", 0, G_MAXINT,
DEFAULT_PROP_XPOS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
g_object_class_install_property (gobject_class, PROP_YPOS,
g_param_spec_int ("ypos", "vertical position",
"Sets the Vertical position", 0, G_MAXINT,
DEFAULT_PROP_YPOS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
-g_object_class_install_property (gobject_class, PROP_THICKNESS,
+ g_object_class_install_property (gobject_class, PROP_THICKNESS,
g_param_spec_int ("thickness", "font thickness",
"Sets the Thickness of Font", 0, G_MAXINT,
DEFAULT_PROP_THICKNESS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+ g_object_class_install_property (gobject_class, PROP_COLOR_R,
+ g_param_spec_int ("colorR", "color -Red ",
+ "Sets the color -R", 0, 255,
+ DEFAULT_PROP_COLOR, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+
+ g_object_class_install_property (gobject_class, PROP_COLOR_G,
+ g_param_spec_int ("colorG", "color -Green",
+ "Sets the color -G", 0, 255,
+ DEFAULT_PROP_COLOR, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+
+ g_object_class_install_property (gobject_class, PROP_COLOR_B,
+ g_param_spec_int ("colorB", "color -Blue",
+ "Sets the color -B", 0, 255,
+ DEFAULT_PROP_COLOR, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+
+
+
g_object_class_install_property (gobject_class, PROP_HEIGHT,
g_param_spec_double ("height", "Height",
"Sets the height of fonts",1.0,5.0,
DEFAULT_HEIGHT, G_PARAM_READWRITE|G_PARAM_STATIC_STRINGS));
g_object_class_install_property (gobject_class, PROP_WIDTH,
g_param_spec_double ("width", "Width",
"Sets the width of fonts",1.0,5.0,
DEFAULT_WIDTH, G_PARAM_READWRITE| G_PARAM_STATIC_STRINGS));
}
/* initialize the new element
* instantiate pads and add them to element
* set pad calback functions
* initialize instance structure
*/
static void
gst_textwrite_init (Gsttextwrite * filter,
GsttextwriteClass * gclass)
{
filter->sinkpad = gst_pad_new_from_static_template (&sink_factory, "sink");
gst_pad_set_setcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR(gst_textwrite_set_caps));
gst_pad_set_getcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR(gst_pad_proxy_getcaps));
gst_pad_set_chain_function (filter->sinkpad,
GST_DEBUG_FUNCPTR(gst_textwrite_chain));
filter->srcpad = gst_pad_new_from_static_template (&src_factory, "src");
gst_pad_set_getcaps_function (filter->srcpad,
GST_DEBUG_FUNCPTR(gst_pad_proxy_getcaps));
gst_element_add_pad (GST_ELEMENT (filter), filter->sinkpad);
gst_element_add_pad (GST_ELEMENT (filter), filter->srcpad);
filter->textbuf = g_strdup (DEFAULT_PROP_TEXT);
filter->width = DEFAULT_PROP_WIDTH;
filter->height = DEFAULT_PROP_HEIGHT;
filter->xpos = DEFAULT_PROP_XPOS;
filter->ypos = DEFAULT_PROP_YPOS;
filter->thickness = DEFAULT_PROP_THICKNESS;
+ filter->colorR = DEFAULT_PROP_COLOR;
+ filter->colorG = DEFAULT_PROP_COLOR;
+ filter->colorB = DEFAULT_PROP_COLOR;
}
static void
gst_textwrite_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec)
{
Gsttextwrite *filter = GST_textwrite (object);
switch (prop_id) {
case PROP_TEXT:
g_free (filter->textbuf);
filter->textbuf = g_value_dup_string (value);
break;
case PROP_XPOS:
filter->xpos = g_value_get_int(value);
break;
case PROP_YPOS:
filter->ypos = g_value_get_int(value);
break;
case PROP_THICKNESS:
filter->thickness = g_value_get_int(value);
break;
+
+ case PROP_COLOR_R:
+ filter->colorR = g_value_get_int(value);
+ break;
+ case PROP_COLOR_G:
+ filter->colorG = g_value_get_int(value);
+ break;
+ case PROP_COLOR_B:
+ filter->colorB = g_value_get_int(value);
+ break;
+
case PROP_HEIGHT:
filter->height = g_value_get_double(value);
break;
case PROP_WIDTH:
filter->width = g_value_get_double(value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gst_textwrite_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec)
{
Gsttextwrite *filter = GST_textwrite (object);
switch (prop_id) {
case PROP_TEXT:
g_value_set_string (value, filter->textbuf);
break;
case PROP_XPOS:
g_value_set_int (value, filter->xpos);
break;
case PROP_YPOS:
g_value_set_int (value, filter->ypos);
break;
case PROP_THICKNESS:
g_value_set_int (value, filter->thickness);
break;
+ case PROP_COLOR_R:
+ g_value_set_int (value, filter->colorR);
+ break;
+ case PROP_COLOR_G:
+ g_value_set_int (value, filter->colorG);
+ break;
+ case PROP_COLOR_B:
+ g_value_set_int (value, filter->colorB);
+ break;
case PROP_HEIGHT:
g_value_set_double (value, filter->height);
break;
case PROP_WIDTH:
g_value_set_double (value, filter->width);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
/* GstElement vmethod implementations */
/* this function handles the link with other elements */
static gboolean
gst_textwrite_set_caps (GstPad * pad, GstCaps * caps)
{
Gsttextwrite *filter;
GstPad *otherpad;
gint width, height;
GstStructure *structure;
filter = GST_textwrite (gst_pad_get_parent (pad));
structure = gst_caps_get_structure (caps, 0);
gst_structure_get_int (structure, "width", &width);
gst_structure_get_int (structure, "height", &height);
filter->cvImage = cvCreateImage (cvSize (width, height), IPL_DEPTH_8U, 3);
filter->cvStorage = cvCreateMemStorage (0);
otherpad = (pad == filter->srcpad) ? filter->sinkpad : filter->srcpad;
gst_object_unref (filter);
return gst_pad_set_caps (otherpad, caps);
}
/* chain function
* this function does the actual processing
*/
static GstFlowReturn
gst_textwrite_chain (GstPad * pad, GstBuffer * buf)
{
Gsttextwrite *filter;
filter = GST_textwrite (GST_OBJECT_PARENT (pad));
filter->cvImage->imageData = (char *) GST_BUFFER_DATA (buf);
cvInitFont(&(filter->font),CV_FONT_VECTOR0, filter->width,filter->height,0,filter->thickness,0);
- cvPutText (filter->cvImage,filter->textbuf,cvPoint(filter->xpos,filter->ypos), &(filter->font), cvScalar(165,14,14,0));
+ cvPutText (filter->cvImage,filter->textbuf,cvPoint(filter->xpos,filter->ypos), &(filter->font), cvScalar(filter->colorR,filter->colorG,filter->colorB,0));
gst_buffer_set_data (buf, filter->cvImage->imageData,filter->cvImage->imageSize);
return gst_pad_push (filter->srcpad, buf);
}
/* entry point to initialize the plug-in
* initialize the plug-in itself
* register the element factories and other features
*/
gboolean
gst_textwrite_plugin_init (GstPlugin * plugin)
{
/* debug category for fltering log messages
*
* exchange the string 'Template textwrite' with your description
*/
GST_DEBUG_CATEGORY_INIT (gst_textwrite_debug, "textwrite",
0, "Template textwrite");
return gst_element_register (plugin, "textwrite", GST_RANK_NONE,
GST_TYPE_textwrite);
}
diff --git a/src/textwrite/gsttextwrite.h b/src/textwrite/gsttextwrite.h
index f36de2a..442519a 100644
--- a/src/textwrite/gsttextwrite.h
+++ b/src/textwrite/gsttextwrite.h
@@ -1,100 +1,101 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2010 root <<user@hostname.org>>m
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#ifndef __GST_textwrite_H__
#define __GST_textwrite_H__
#include <gst/gst.h>
#include <cv.h>
#include <cvaux.h>
#include <highgui.h>
G_BEGIN_DECLS
/* #defines don't like whitespacey bits */
#define GST_TYPE_textwrite \
(gst_textwrite_get_type())
#define GST_textwrite(obj) \
(G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_textwrite,Gsttextwrite))
#define GST_textwrite_CLASS(klass) \
(G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_textwrite,GsttextwriteClass))
#define GST_IS_textwrite(obj) \
(G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_textwrite))
#define GST_IS_textwrite_CLASS(klass) \
(G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_textwrite))
typedef struct _Gsttextwrite Gsttextwrite;
typedef struct _GsttextwriteClass GsttextwriteClass;
struct _Gsttextwrite
{
GstElement element;
GstPad *sinkpad, *srcpad;
IplImage *cvImage;
CvMemStorage *cvStorage;
CvFont font;
gint xpos;
gint ypos;
gint thickness;
+ gint colorR,colorG,colorB;
gdouble height;
gdouble width;
gchar *textbuf;
};
struct _GsttextwriteClass
{
GstElementClass parent_class;
};
GType gst_textwrite_get_type (void);
gboolean gst_textwrite_plugin_init (GstPlugin * plugin);
G_END_DECLS
#endif /* __GST_textwrite_H__ */
|
Elleo/gst-opencv
|
38a3469a00c204c6a77f1ee63ef7eab3b65f8461
|
Added the property for setting the "thickness" of font modified: src/textwrite/gsttextwrite.c modified: src/textwrite/gsttextwrite.h
|
diff --git a/src/textwrite/gsttextwrite.c b/src/textwrite/gsttextwrite.c
index 807aed2..c5de38a 100644
--- a/src/textwrite/gsttextwrite.c
+++ b/src/textwrite/gsttextwrite.c
@@ -1,357 +1,368 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2010 Sreerenj Balachandran <bsreerenj@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/**
* SECTION:element-textwrite
*
* FIXME:Describe textwrite here.
*
* <refsect2>
* <title>Example launch line</title>
* |[
* gst-launch -v -m fakesrc ! textwrite ! fakesink silent=TRUE
* ]|
* </refsect2>
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <gst/gst.h>
#include "gsttextwrite.h"
GST_DEBUG_CATEGORY_STATIC (gst_textwrite_debug);
#define GST_CAT_DEFAULT gst_textwrite_debug
#define DEFAULT_PROP_TEXT ""
#define DEFAULT_PROP_WIDTH 1
#define DEFAULT_PROP_HEIGHT 1
#define DEFAULT_PROP_XPOS 50
#define DEFAULT_PROP_YPOS 50
+#define DEFAULT_PROP_THICKNESS 2
/* Filter signals and args */
enum
{
/* FILL ME */
LAST_SIGNAL
};
#define DEFAULT_WIDTH 1.0
#define DEFAULT_HEIGHT 1.0
enum
{
PROP_0,
PROP_XPOS,
PROP_YPOS,
+ PROP_THICKNESS,
PROP_TEXT,
PROP_HEIGHT,
PROP_WIDTH
};
/* the capabilities of the inputs and outputs.
*
* describe the real formats here.
*/
static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
GST_PAD_SINK,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("video/x-raw-rgb")
);
static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
GST_PAD_SRC,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("ANY")
);
GST_BOILERPLATE (Gsttextwrite, gst_textwrite, GstElement,GST_TYPE_ELEMENT);
static void gst_textwrite_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec);
static void gst_textwrite_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec);
static gboolean gst_textwrite_set_caps (GstPad * pad, GstCaps * caps);
static GstFlowReturn gst_textwrite_chain (GstPad * pad, GstBuffer * buf);
/* Clean up */
static void
gst_textwrite_finalize (GObject * obj)
{
Gsttextwrite *filter = GST_textwrite (obj);
if (filter->cvImage) {
cvReleaseImage (&filter->cvImage);
}
G_OBJECT_CLASS (parent_class)->finalize (obj);
}
/* GObject vmethod implementations */
static void
gst_textwrite_base_init (gpointer gclass)
{
GstElementClass *element_class = GST_ELEMENT_CLASS (gclass);
gst_element_class_set_details_simple(element_class,
"textwrite",
"Filter/Effect/Video",
"Performs text writing to the video",
"sreerenj<bsreerenj@gmail.com>");
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&src_factory));
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&sink_factory));
}
/* initialize the textwrite's class */
static void
gst_textwrite_class_init (GsttextwriteClass * klass)
{
GObjectClass *gobject_class;
GstElementClass *gstelement_class;
gobject_class = (GObjectClass *) klass;
gstelement_class = (GstElementClass *) klass;
parent_class = g_type_class_peek_parent (klass);
gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_textwrite_finalize);
gobject_class->set_property = gst_textwrite_set_property;
gobject_class->get_property = gst_textwrite_get_property;
g_object_class_install_property (gobject_class, PROP_TEXT,
g_param_spec_string ("text", "text",
"Text to be display.", DEFAULT_PROP_TEXT,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
g_object_class_install_property (gobject_class, PROP_XPOS,
g_param_spec_int ("xpos", "horizontal position",
"Sets the Horizontal position", 0, G_MAXINT,
DEFAULT_PROP_XPOS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
g_object_class_install_property (gobject_class, PROP_YPOS,
g_param_spec_int ("ypos", "vertical position",
"Sets the Vertical position", 0, G_MAXINT,
DEFAULT_PROP_YPOS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+g_object_class_install_property (gobject_class, PROP_THICKNESS,
+ g_param_spec_int ("thickness", "font thickness",
+ "Sets the Thickness of Font", 0, G_MAXINT,
+ DEFAULT_PROP_THICKNESS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+
g_object_class_install_property (gobject_class, PROP_HEIGHT,
g_param_spec_double ("height", "Height",
"Sets the height of fonts",1.0,5.0,
DEFAULT_HEIGHT, G_PARAM_READWRITE|G_PARAM_STATIC_STRINGS));
g_object_class_install_property (gobject_class, PROP_WIDTH,
g_param_spec_double ("width", "Width",
"Sets the width of fonts",1.0,5.0,
DEFAULT_WIDTH, G_PARAM_READWRITE| G_PARAM_STATIC_STRINGS));
}
/* initialize the new element
* instantiate pads and add them to element
* set pad calback functions
* initialize instance structure
*/
static void
gst_textwrite_init (Gsttextwrite * filter,
GsttextwriteClass * gclass)
{
filter->sinkpad = gst_pad_new_from_static_template (&sink_factory, "sink");
gst_pad_set_setcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR(gst_textwrite_set_caps));
gst_pad_set_getcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR(gst_pad_proxy_getcaps));
gst_pad_set_chain_function (filter->sinkpad,
GST_DEBUG_FUNCPTR(gst_textwrite_chain));
filter->srcpad = gst_pad_new_from_static_template (&src_factory, "src");
gst_pad_set_getcaps_function (filter->srcpad,
GST_DEBUG_FUNCPTR(gst_pad_proxy_getcaps));
gst_element_add_pad (GST_ELEMENT (filter), filter->sinkpad);
gst_element_add_pad (GST_ELEMENT (filter), filter->srcpad);
filter->textbuf = g_strdup (DEFAULT_PROP_TEXT);
- filter->width=DEFAULT_PROP_WIDTH;
- filter->height=DEFAULT_PROP_HEIGHT;
- filter->xpos=DEFAULT_PROP_XPOS;
- filter->ypos=DEFAULT_PROP_XPOS;
-
+ filter->width = DEFAULT_PROP_WIDTH;
+ filter->height = DEFAULT_PROP_HEIGHT;
+ filter->xpos = DEFAULT_PROP_XPOS;
+ filter->ypos = DEFAULT_PROP_YPOS;
+ filter->thickness = DEFAULT_PROP_THICKNESS;
+
}
static void
gst_textwrite_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec)
{
Gsttextwrite *filter = GST_textwrite (object);
switch (prop_id) {
case PROP_TEXT:
g_free (filter->textbuf);
filter->textbuf = g_value_dup_string (value);
break;
case PROP_XPOS:
filter->xpos = g_value_get_int(value);
break;
case PROP_YPOS:
filter->ypos = g_value_get_int(value);
break;
+ case PROP_THICKNESS:
+ filter->thickness = g_value_get_int(value);
+ break;
case PROP_HEIGHT:
filter->height = g_value_get_double(value);
break;
case PROP_WIDTH:
filter->width = g_value_get_double(value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gst_textwrite_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec)
{
Gsttextwrite *filter = GST_textwrite (object);
switch (prop_id) {
case PROP_TEXT:
g_value_set_string (value, filter->textbuf);
break;
case PROP_XPOS:
g_value_set_int (value, filter->xpos);
break;
case PROP_YPOS:
g_value_set_int (value, filter->ypos);
break;
+ case PROP_THICKNESS:
+ g_value_set_int (value, filter->thickness);
+ break;
case PROP_HEIGHT:
g_value_set_double (value, filter->height);
break;
case PROP_WIDTH:
g_value_set_double (value, filter->width);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
/* GstElement vmethod implementations */
/* this function handles the link with other elements */
static gboolean
gst_textwrite_set_caps (GstPad * pad, GstCaps * caps)
{
Gsttextwrite *filter;
GstPad *otherpad;
gint width, height;
GstStructure *structure;
filter = GST_textwrite (gst_pad_get_parent (pad));
structure = gst_caps_get_structure (caps, 0);
gst_structure_get_int (structure, "width", &width);
gst_structure_get_int (structure, "height", &height);
filter->cvImage = cvCreateImage (cvSize (width, height), IPL_DEPTH_8U, 3);
filter->cvStorage = cvCreateMemStorage (0);
otherpad = (pad == filter->srcpad) ? filter->sinkpad : filter->srcpad;
gst_object_unref (filter);
return gst_pad_set_caps (otherpad, caps);
}
/* chain function
* this function does the actual processing
*/
static GstFlowReturn
gst_textwrite_chain (GstPad * pad, GstBuffer * buf)
{
Gsttextwrite *filter;
filter = GST_textwrite (GST_OBJECT_PARENT (pad));
filter->cvImage->imageData = (char *) GST_BUFFER_DATA (buf);
- int lineWidth=1;
- cvInitFont(&(filter->font),CV_FONT_VECTOR0, filter->width,filter->height,0,lineWidth,0);
-
+
+ cvInitFont(&(filter->font),CV_FONT_VECTOR0, filter->width,filter->height,0,filter->thickness,0);
cvPutText (filter->cvImage,filter->textbuf,cvPoint(filter->xpos,filter->ypos), &(filter->font), cvScalar(165,14,14,0));
-
gst_buffer_set_data (buf, filter->cvImage->imageData,filter->cvImage->imageSize);
-
return gst_pad_push (filter->srcpad, buf);
}
/* entry point to initialize the plug-in
* initialize the plug-in itself
* register the element factories and other features
*/
gboolean
gst_textwrite_plugin_init (GstPlugin * plugin)
{
/* debug category for fltering log messages
*
* exchange the string 'Template textwrite' with your description
*/
GST_DEBUG_CATEGORY_INIT (gst_textwrite_debug, "textwrite",
0, "Template textwrite");
return gst_element_register (plugin, "textwrite", GST_RANK_NONE,
GST_TYPE_textwrite);
}
diff --git a/src/textwrite/gsttextwrite.h b/src/textwrite/gsttextwrite.h
index 350e267..f36de2a 100644
--- a/src/textwrite/gsttextwrite.h
+++ b/src/textwrite/gsttextwrite.h
@@ -1,99 +1,100 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2010 root <<user@hostname.org>>m
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#ifndef __GST_textwrite_H__
#define __GST_textwrite_H__
#include <gst/gst.h>
#include <cv.h>
#include <cvaux.h>
#include <highgui.h>
G_BEGIN_DECLS
/* #defines don't like whitespacey bits */
#define GST_TYPE_textwrite \
(gst_textwrite_get_type())
#define GST_textwrite(obj) \
(G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_textwrite,Gsttextwrite))
#define GST_textwrite_CLASS(klass) \
(G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_textwrite,GsttextwriteClass))
#define GST_IS_textwrite(obj) \
(G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_textwrite))
#define GST_IS_textwrite_CLASS(klass) \
(G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_textwrite))
typedef struct _Gsttextwrite Gsttextwrite;
typedef struct _GsttextwriteClass GsttextwriteClass;
struct _Gsttextwrite
{
GstElement element;
GstPad *sinkpad, *srcpad;
IplImage *cvImage;
CvMemStorage *cvStorage;
CvFont font;
gint xpos;
gint ypos;
+ gint thickness;
gdouble height;
gdouble width;
gchar *textbuf;
};
struct _GsttextwriteClass
{
GstElementClass parent_class;
};
GType gst_textwrite_get_type (void);
gboolean gst_textwrite_plugin_init (GstPlugin * plugin);
G_END_DECLS
#endif /* __GST_textwrite_H__ */
|
Elleo/gst-opencv
|
b7644070ee1d74506989a52d083a574258de2d99
|
Added the property for setting x and y co-ordinates modified: src/textwrite/gsttextwrite.c modified: src/textwrite/gsttextwrite.h
|
diff --git a/src/textwrite/gsttextwrite.c b/src/textwrite/gsttextwrite.c
index 7449884..807aed2 100644
--- a/src/textwrite/gsttextwrite.c
+++ b/src/textwrite/gsttextwrite.c
@@ -1,356 +1,357 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2010 Sreerenj Balachandran <bsreerenj@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/**
* SECTION:element-textwrite
*
* FIXME:Describe textwrite here.
*
* <refsect2>
* <title>Example launch line</title>
* |[
* gst-launch -v -m fakesrc ! textwrite ! fakesink silent=TRUE
* ]|
* </refsect2>
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <gst/gst.h>
#include "gsttextwrite.h"
GST_DEBUG_CATEGORY_STATIC (gst_textwrite_debug);
#define GST_CAT_DEFAULT gst_textwrite_debug
#define DEFAULT_PROP_TEXT ""
#define DEFAULT_PROP_WIDTH 1
#define DEFAULT_PROP_HEIGHT 1
#define DEFAULT_PROP_XPOS 50
#define DEFAULT_PROP_YPOS 50
/* Filter signals and args */
enum
{
/* FILL ME */
LAST_SIGNAL
};
#define DEFAULT_WIDTH 1.0
#define DEFAULT_HEIGHT 1.0
enum
{
PROP_0,
PROP_XPOS,
PROP_YPOS,
PROP_TEXT,
PROP_HEIGHT,
PROP_WIDTH
};
/* the capabilities of the inputs and outputs.
*
* describe the real formats here.
*/
static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
GST_PAD_SINK,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("video/x-raw-rgb")
);
static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
GST_PAD_SRC,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("ANY")
);
GST_BOILERPLATE (Gsttextwrite, gst_textwrite, GstElement,GST_TYPE_ELEMENT);
static void gst_textwrite_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec);
static void gst_textwrite_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec);
static gboolean gst_textwrite_set_caps (GstPad * pad, GstCaps * caps);
static GstFlowReturn gst_textwrite_chain (GstPad * pad, GstBuffer * buf);
/* Clean up */
static void
gst_textwrite_finalize (GObject * obj)
{
Gsttextwrite *filter = GST_textwrite (obj);
if (filter->cvImage) {
cvReleaseImage (&filter->cvImage);
}
G_OBJECT_CLASS (parent_class)->finalize (obj);
}
/* GObject vmethod implementations */
static void
gst_textwrite_base_init (gpointer gclass)
{
GstElementClass *element_class = GST_ELEMENT_CLASS (gclass);
gst_element_class_set_details_simple(element_class,
"textwrite",
"Filter/Effect/Video",
"Performs text writing to the video",
"sreerenj<bsreerenj@gmail.com>");
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&src_factory));
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&sink_factory));
}
/* initialize the textwrite's class */
static void
gst_textwrite_class_init (GsttextwriteClass * klass)
{
GObjectClass *gobject_class;
GstElementClass *gstelement_class;
gobject_class = (GObjectClass *) klass;
gstelement_class = (GstElementClass *) klass;
parent_class = g_type_class_peek_parent (klass);
gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_textwrite_finalize);
gobject_class->set_property = gst_textwrite_set_property;
gobject_class->get_property = gst_textwrite_get_property;
g_object_class_install_property (gobject_class, PROP_TEXT,
g_param_spec_string ("text", "text",
"Text to be display.", DEFAULT_PROP_TEXT,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
g_object_class_install_property (gobject_class, PROP_XPOS,
g_param_spec_int ("xpos", "horizontal position",
"Sets the Horizontal position", 0, G_MAXINT,
DEFAULT_PROP_XPOS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+
g_object_class_install_property (gobject_class, PROP_YPOS,
g_param_spec_int ("ypos", "vertical position",
"Sets the Vertical position", 0, G_MAXINT,
DEFAULT_PROP_YPOS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
g_object_class_install_property (gobject_class, PROP_HEIGHT,
g_param_spec_double ("height", "Height",
"Sets the height of fonts",1.0,5.0,
DEFAULT_HEIGHT, G_PARAM_READWRITE|G_PARAM_STATIC_STRINGS));
g_object_class_install_property (gobject_class, PROP_WIDTH,
g_param_spec_double ("width", "Width",
"Sets the width of fonts",1.0,5.0,
DEFAULT_WIDTH, G_PARAM_READWRITE| G_PARAM_STATIC_STRINGS));
}
/* initialize the new element
* instantiate pads and add them to element
* set pad calback functions
* initialize instance structure
*/
static void
gst_textwrite_init (Gsttextwrite * filter,
GsttextwriteClass * gclass)
{
filter->sinkpad = gst_pad_new_from_static_template (&sink_factory, "sink");
gst_pad_set_setcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR(gst_textwrite_set_caps));
gst_pad_set_getcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR(gst_pad_proxy_getcaps));
gst_pad_set_chain_function (filter->sinkpad,
GST_DEBUG_FUNCPTR(gst_textwrite_chain));
filter->srcpad = gst_pad_new_from_static_template (&src_factory, "src");
gst_pad_set_getcaps_function (filter->srcpad,
GST_DEBUG_FUNCPTR(gst_pad_proxy_getcaps));
gst_element_add_pad (GST_ELEMENT (filter), filter->sinkpad);
gst_element_add_pad (GST_ELEMENT (filter), filter->srcpad);
filter->textbuf = g_strdup (DEFAULT_PROP_TEXT);
filter->width=DEFAULT_PROP_WIDTH;
filter->height=DEFAULT_PROP_HEIGHT;
filter->xpos=DEFAULT_PROP_XPOS;
filter->ypos=DEFAULT_PROP_XPOS;
}
static void
gst_textwrite_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec)
{
Gsttextwrite *filter = GST_textwrite (object);
switch (prop_id) {
case PROP_TEXT:
g_free (filter->textbuf);
filter->textbuf = g_value_dup_string (value);
break;
case PROP_XPOS:
filter->xpos = g_value_get_int(value);
break;
case PROP_YPOS:
filter->ypos = g_value_get_int(value);
break;
case PROP_HEIGHT:
filter->height = g_value_get_double(value);
break;
case PROP_WIDTH:
filter->width = g_value_get_double(value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gst_textwrite_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec)
{
Gsttextwrite *filter = GST_textwrite (object);
switch (prop_id) {
case PROP_TEXT:
g_value_set_string (value, filter->textbuf);
break;
case PROP_XPOS:
g_value_set_int (value, filter->xpos);
break;
case PROP_YPOS:
g_value_set_int (value, filter->ypos);
break;
case PROP_HEIGHT:
g_value_set_double (value, filter->height);
break;
case PROP_WIDTH:
g_value_set_double (value, filter->width);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
/* GstElement vmethod implementations */
/* this function handles the link with other elements */
static gboolean
gst_textwrite_set_caps (GstPad * pad, GstCaps * caps)
{
Gsttextwrite *filter;
GstPad *otherpad;
gint width, height;
GstStructure *structure;
filter = GST_textwrite (gst_pad_get_parent (pad));
structure = gst_caps_get_structure (caps, 0);
gst_structure_get_int (structure, "width", &width);
gst_structure_get_int (structure, "height", &height);
filter->cvImage = cvCreateImage (cvSize (width, height), IPL_DEPTH_8U, 3);
filter->cvStorage = cvCreateMemStorage (0);
otherpad = (pad == filter->srcpad) ? filter->sinkpad : filter->srcpad;
gst_object_unref (filter);
return gst_pad_set_caps (otherpad, caps);
}
/* chain function
* this function does the actual processing
*/
static GstFlowReturn
gst_textwrite_chain (GstPad * pad, GstBuffer * buf)
{
Gsttextwrite *filter;
filter = GST_textwrite (GST_OBJECT_PARENT (pad));
filter->cvImage->imageData = (char *) GST_BUFFER_DATA (buf);
int lineWidth=1;
cvInitFont(&(filter->font),CV_FONT_VECTOR0, filter->width,filter->height,0,lineWidth,0);
cvPutText (filter->cvImage,filter->textbuf,cvPoint(filter->xpos,filter->ypos), &(filter->font), cvScalar(165,14,14,0));
gst_buffer_set_data (buf, filter->cvImage->imageData,filter->cvImage->imageSize);
return gst_pad_push (filter->srcpad, buf);
}
/* entry point to initialize the plug-in
* initialize the plug-in itself
* register the element factories and other features
*/
gboolean
gst_textwrite_plugin_init (GstPlugin * plugin)
{
/* debug category for fltering log messages
*
* exchange the string 'Template textwrite' with your description
*/
GST_DEBUG_CATEGORY_INIT (gst_textwrite_debug, "textwrite",
0, "Template textwrite");
return gst_element_register (plugin, "textwrite", GST_RANK_NONE,
GST_TYPE_textwrite);
}
diff --git a/src/textwrite/gsttextwrite.h b/src/textwrite/gsttextwrite.h
index af3d6af..350e267 100644
--- a/src/textwrite/gsttextwrite.h
+++ b/src/textwrite/gsttextwrite.h
@@ -1,100 +1,99 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2010 root <<user@hostname.org>>m
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#ifndef __GST_textwrite_H__
#define __GST_textwrite_H__
#include <gst/gst.h>
-//sreechage
#include <cv.h>
#include <cvaux.h>
#include <highgui.h>
G_BEGIN_DECLS
/* #defines don't like whitespacey bits */
#define GST_TYPE_textwrite \
(gst_textwrite_get_type())
#define GST_textwrite(obj) \
(G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_textwrite,Gsttextwrite))
#define GST_textwrite_CLASS(klass) \
(G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_textwrite,GsttextwriteClass))
#define GST_IS_textwrite(obj) \
(G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_textwrite))
#define GST_IS_textwrite_CLASS(klass) \
(G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_textwrite))
typedef struct _Gsttextwrite Gsttextwrite;
typedef struct _GsttextwriteClass GsttextwriteClass;
struct _Gsttextwrite
{
GstElement element;
GstPad *sinkpad, *srcpad;
IplImage *cvImage;
CvMemStorage *cvStorage;
CvFont font;
gint xpos;
gint ypos;
gdouble height;
gdouble width;
gchar *textbuf;
};
struct _GsttextwriteClass
{
GstElementClass parent_class;
};
GType gst_textwrite_get_type (void);
gboolean gst_textwrite_plugin_init (GstPlugin * plugin);
G_END_DECLS
#endif /* __GST_textwrite_H__ */
|
Elleo/gst-opencv
|
bd87df18042d49ef0198a6c961108e3eaa137d05
|
added the propery for setting x and y co-ordinates modified: src/textwrite/gsttextwrite.c modified: src/textwrite/gsttextwrite.h
|
diff --git a/src/textwrite/gsttextwrite.c b/src/textwrite/gsttextwrite.c
index 3369e92..7449884 100644
--- a/src/textwrite/gsttextwrite.c
+++ b/src/textwrite/gsttextwrite.c
@@ -1,329 +1,356 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2010 Sreerenj Balachandran <bsreerenj@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/**
* SECTION:element-textwrite
*
* FIXME:Describe textwrite here.
*
* <refsect2>
* <title>Example launch line</title>
* |[
* gst-launch -v -m fakesrc ! textwrite ! fakesink silent=TRUE
* ]|
* </refsect2>
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <gst/gst.h>
#include "gsttextwrite.h"
GST_DEBUG_CATEGORY_STATIC (gst_textwrite_debug);
#define GST_CAT_DEFAULT gst_textwrite_debug
#define DEFAULT_PROP_TEXT ""
#define DEFAULT_PROP_WIDTH 1
#define DEFAULT_PROP_HEIGHT 1
+#define DEFAULT_PROP_XPOS 50
+#define DEFAULT_PROP_YPOS 50
/* Filter signals and args */
enum
{
/* FILL ME */
LAST_SIGNAL
};
#define DEFAULT_WIDTH 1.0
#define DEFAULT_HEIGHT 1.0
enum
{
PROP_0,
+ PROP_XPOS,
+ PROP_YPOS,
PROP_TEXT,
PROP_HEIGHT,
PROP_WIDTH
};
/* the capabilities of the inputs and outputs.
*
* describe the real formats here.
*/
static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
GST_PAD_SINK,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("video/x-raw-rgb")
);
static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
GST_PAD_SRC,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("ANY")
);
GST_BOILERPLATE (Gsttextwrite, gst_textwrite, GstElement,GST_TYPE_ELEMENT);
static void gst_textwrite_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec);
static void gst_textwrite_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec);
static gboolean gst_textwrite_set_caps (GstPad * pad, GstCaps * caps);
static GstFlowReturn gst_textwrite_chain (GstPad * pad, GstBuffer * buf);
/* Clean up */
static void
gst_textwrite_finalize (GObject * obj)
{
Gsttextwrite *filter = GST_textwrite (obj);
if (filter->cvImage) {
cvReleaseImage (&filter->cvImage);
}
G_OBJECT_CLASS (parent_class)->finalize (obj);
}
/* GObject vmethod implementations */
static void
gst_textwrite_base_init (gpointer gclass)
{
GstElementClass *element_class = GST_ELEMENT_CLASS (gclass);
gst_element_class_set_details_simple(element_class,
"textwrite",
"Filter/Effect/Video",
"Performs text writing to the video",
"sreerenj<bsreerenj@gmail.com>");
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&src_factory));
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&sink_factory));
}
/* initialize the textwrite's class */
static void
gst_textwrite_class_init (GsttextwriteClass * klass)
{
GObjectClass *gobject_class;
GstElementClass *gstelement_class;
gobject_class = (GObjectClass *) klass;
gstelement_class = (GstElementClass *) klass;
parent_class = g_type_class_peek_parent (klass);
gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_textwrite_finalize);
gobject_class->set_property = gst_textwrite_set_property;
gobject_class->get_property = gst_textwrite_get_property;
g_object_class_install_property (gobject_class, PROP_TEXT,
g_param_spec_string ("text", "text",
"Text to be display.", DEFAULT_PROP_TEXT,
G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+ g_object_class_install_property (gobject_class, PROP_XPOS,
+ g_param_spec_int ("xpos", "horizontal position",
+ "Sets the Horizontal position", 0, G_MAXINT,
+ DEFAULT_PROP_XPOS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+ g_object_class_install_property (gobject_class, PROP_YPOS,
+ g_param_spec_int ("ypos", "vertical position",
+ "Sets the Vertical position", 0, G_MAXINT,
+ DEFAULT_PROP_YPOS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+
g_object_class_install_property (gobject_class, PROP_HEIGHT,
g_param_spec_double ("height", "Height",
"Sets the height of fonts",1.0,5.0,
DEFAULT_HEIGHT, G_PARAM_READWRITE|G_PARAM_STATIC_STRINGS));
g_object_class_install_property (gobject_class, PROP_WIDTH,
g_param_spec_double ("width", "Width",
"Sets the width of fonts",1.0,5.0,
DEFAULT_WIDTH, G_PARAM_READWRITE| G_PARAM_STATIC_STRINGS));
}
/* initialize the new element
* instantiate pads and add them to element
* set pad calback functions
* initialize instance structure
*/
static void
gst_textwrite_init (Gsttextwrite * filter,
GsttextwriteClass * gclass)
{
filter->sinkpad = gst_pad_new_from_static_template (&sink_factory, "sink");
gst_pad_set_setcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR(gst_textwrite_set_caps));
gst_pad_set_getcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR(gst_pad_proxy_getcaps));
gst_pad_set_chain_function (filter->sinkpad,
GST_DEBUG_FUNCPTR(gst_textwrite_chain));
filter->srcpad = gst_pad_new_from_static_template (&src_factory, "src");
gst_pad_set_getcaps_function (filter->srcpad,
GST_DEBUG_FUNCPTR(gst_pad_proxy_getcaps));
gst_element_add_pad (GST_ELEMENT (filter), filter->sinkpad);
gst_element_add_pad (GST_ELEMENT (filter), filter->srcpad);
filter->textbuf = g_strdup (DEFAULT_PROP_TEXT);
filter->width=DEFAULT_PROP_WIDTH;
filter->height=DEFAULT_PROP_HEIGHT;
+ filter->xpos=DEFAULT_PROP_XPOS;
+ filter->ypos=DEFAULT_PROP_XPOS;
}
static void
gst_textwrite_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec)
{
Gsttextwrite *filter = GST_textwrite (object);
switch (prop_id) {
case PROP_TEXT:
g_free (filter->textbuf);
filter->textbuf = g_value_dup_string (value);
break;
+ case PROP_XPOS:
+ filter->xpos = g_value_get_int(value);
+ break;
+ case PROP_YPOS:
+ filter->ypos = g_value_get_int(value);
+ break;
case PROP_HEIGHT:
filter->height = g_value_get_double(value);
break;
case PROP_WIDTH:
filter->width = g_value_get_double(value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gst_textwrite_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec)
{
Gsttextwrite *filter = GST_textwrite (object);
switch (prop_id) {
case PROP_TEXT:
g_value_set_string (value, filter->textbuf);
break;
+ case PROP_XPOS:
+ g_value_set_int (value, filter->xpos);
+ break;
+ case PROP_YPOS:
+ g_value_set_int (value, filter->ypos);
+ break;
case PROP_HEIGHT:
g_value_set_double (value, filter->height);
break;
case PROP_WIDTH:
g_value_set_double (value, filter->width);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
/* GstElement vmethod implementations */
/* this function handles the link with other elements */
static gboolean
gst_textwrite_set_caps (GstPad * pad, GstCaps * caps)
{
Gsttextwrite *filter;
GstPad *otherpad;
gint width, height;
GstStructure *structure;
filter = GST_textwrite (gst_pad_get_parent (pad));
structure = gst_caps_get_structure (caps, 0);
gst_structure_get_int (structure, "width", &width);
gst_structure_get_int (structure, "height", &height);
filter->cvImage = cvCreateImage (cvSize (width, height), IPL_DEPTH_8U, 3);
filter->cvStorage = cvCreateMemStorage (0);
otherpad = (pad == filter->srcpad) ? filter->sinkpad : filter->srcpad;
gst_object_unref (filter);
return gst_pad_set_caps (otherpad, caps);
}
/* chain function
* this function does the actual processing
*/
static GstFlowReturn
gst_textwrite_chain (GstPad * pad, GstBuffer * buf)
{
Gsttextwrite *filter;
filter = GST_textwrite (GST_OBJECT_PARENT (pad));
filter->cvImage->imageData = (char *) GST_BUFFER_DATA (buf);
int lineWidth=1;
cvInitFont(&(filter->font),CV_FONT_VECTOR0, filter->width,filter->height,0,lineWidth,0);
- cvPutText (filter->cvImage,filter->textbuf,cvPoint(100,100), &(filter->font), cvScalar(165,14,14,0));
+ cvPutText (filter->cvImage,filter->textbuf,cvPoint(filter->xpos,filter->ypos), &(filter->font), cvScalar(165,14,14,0));
gst_buffer_set_data (buf, filter->cvImage->imageData,filter->cvImage->imageSize);
return gst_pad_push (filter->srcpad, buf);
}
/* entry point to initialize the plug-in
* initialize the plug-in itself
* register the element factories and other features
*/
gboolean
gst_textwrite_plugin_init (GstPlugin * plugin)
{
/* debug category for fltering log messages
*
* exchange the string 'Template textwrite' with your description
*/
GST_DEBUG_CATEGORY_INIT (gst_textwrite_debug, "textwrite",
0, "Template textwrite");
return gst_element_register (plugin, "textwrite", GST_RANK_NONE,
GST_TYPE_textwrite);
}
diff --git a/src/textwrite/gsttextwrite.h b/src/textwrite/gsttextwrite.h
index 8253e91..af3d6af 100644
--- a/src/textwrite/gsttextwrite.h
+++ b/src/textwrite/gsttextwrite.h
@@ -1,98 +1,100 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2010 root <<user@hostname.org>>m
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#ifndef __GST_textwrite_H__
#define __GST_textwrite_H__
#include <gst/gst.h>
//sreechage
#include <cv.h>
#include <cvaux.h>
#include <highgui.h>
G_BEGIN_DECLS
/* #defines don't like whitespacey bits */
#define GST_TYPE_textwrite \
(gst_textwrite_get_type())
#define GST_textwrite(obj) \
(G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_textwrite,Gsttextwrite))
#define GST_textwrite_CLASS(klass) \
(G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_textwrite,GsttextwriteClass))
#define GST_IS_textwrite(obj) \
(G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_textwrite))
#define GST_IS_textwrite_CLASS(klass) \
(G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_textwrite))
typedef struct _Gsttextwrite Gsttextwrite;
typedef struct _GsttextwriteClass GsttextwriteClass;
struct _Gsttextwrite
{
GstElement element;
GstPad *sinkpad, *srcpad;
IplImage *cvImage;
CvMemStorage *cvStorage;
CvFont font;
+ gint xpos;
+ gint ypos;
gdouble height;
gdouble width;
gchar *textbuf;
};
struct _GsttextwriteClass
{
GstElementClass parent_class;
};
GType gst_textwrite_get_type (void);
gboolean gst_textwrite_plugin_init (GstPlugin * plugin);
G_END_DECLS
#endif /* __GST_textwrite_H__ */
|
Elleo/gst-opencv
|
e4bb11ea8446eb8dd0b84d1e4a1076b4816a87d8
|
Add libswscale-dev to debian build-deps and libswscale0 to deps
|
diff --git a/debian/changelog b/debian/changelog
index ba15356..e519d53 100644
--- a/debian/changelog
+++ b/debian/changelog
@@ -1,30 +1,36 @@
+gst-opencv (0.1+git20100301ubuntu2) karmic; urgency=low
+
+ * Add libswscale-dev to build-deps and libswscale0 to deps
+
+ -- Mike Sheldon <mike@mikeasoft.com> Mon, 01 Mar 2010 15:44:29 +0000
+
gst-opencv (0.1+git20100301ubuntu1) karmic; urgency=low
* Add textwrite element
* Fix leaks in facedetect and faceblur
-- Mike Sheldon <mike@mikeasoft.com> Mon, 01 Mar 2010 14:52:25 +0000
gst-opencv (0.1+git20090525ubuntu5) jaunty; urgency=low
* Add autotools, libtool and pkgconfig to package dependencies
-- Mike Sheldon <mike@mikeasoft.com> Mon, 25 May 2009 12:22:43 +0100
gst-opencv (0.1+git20090525ubuntu2) jaunty; urgency=low
* Fix package section
-- Mike Sheldon <mike@mikeasoft.com> Mon, 25 May 2009 12:04:33 +0100
gst-opencv (0.1+git20090525ubuntu1) jaunty; urgency=low
* Add face blurring element
-- Mike Sheldon <mike@mikeasoft.com> Mon, 25 May 2009 11:34:39 +0100
gst-opencv (0.1-1) jaunty; urgency=low
* Initial release
-- Noam Lewis <jones.noamle@gmail.com> Mon, 27 Apr 2009 23:26:11 +0300
diff --git a/debian/control b/debian/control
index e4637c6..2b2f8df 100644
--- a/debian/control
+++ b/debian/control
@@ -1,13 +1,13 @@
Source: gst-opencv
Section: libs
Priority: extra
Maintainer: Noam Lewis <jones.noamle@gmail.com>
-Build-Depends: autoconf (>= 2.52), automake (>= 1.7), libtool (>= 1.5.0), pkg-config (>= 0.11.0), debhelper (>= 7), libcv-dev, libgstreamer-plugins-base0.10-dev,
+Build-Depends: autoconf (>= 2.52), automake (>= 1.7), libtool (>= 1.5.0), pkg-config (>= 0.11.0), debhelper (>= 7), libcv-dev, libgstreamer-plugins-base0.10-dev, libswscale-dev
Standards-Version: 3.8.0
Homepage: https://launchpad.net/gst-opencv
Package: gst-opencv
Architecture: any
-Depends: ${shlibs:Depends}, ${misc:Depends}, libcv1, gstreamer0.10-plugins-base
+Depends: ${shlibs:Depends}, ${misc:Depends}, libcv1, gstreamer0.10-plugins-base, libswscale0
Description: Gstreamer plugins using opencv
A collection of Gstreamer plugins making computer vision techniques from OpenCV available to Gstreamer based applications.
|
Elleo/gst-opencv
|
06173ccab44910582cfe8004a2e843e709160742
|
modified: AUTHORS
|
diff --git a/AUTHORS b/AUTHORS
index 17bd6f8..7534cb4 100644
--- a/AUTHORS
+++ b/AUTHORS
@@ -1,6 +1,6 @@
Mike Sheldon <mike@mikeasoft.com>
Noam Lewis <jones.noamle@gmail.com>
Kapil Agrawal <kapil@mediamagictechnologies.com>
Thomas Vander Stichele <thomas@apestaart.org>
-Sreerenj Balachandran <bsreerenj@gmail.com>
+Balachandran Sreerenj <bsreerenj@gmail.com>
Stefan Kost <ensonic@hora-obscura.de>
|
Elleo/gst-opencv
|
b16903e6455dd5f475a18a975e41786adb7be58d
|
Apply Stefan's faceblur fixes to facedetect
|
diff --git a/src/facedetect/gstfacedetect.c b/src/facedetect/gstfacedetect.c
index 70e717f..0928b45 100644
--- a/src/facedetect/gstfacedetect.c
+++ b/src/facedetect/gstfacedetect.c
@@ -1,342 +1,345 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2008 Michael Sheldon <mike@mikeasoft.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/**
* SECTION:element-facedetect
*
* FIXME:Describe facedetect here.
*
* <refsect2>
* <title>Example launch line</title>
* |[
* gst-launch-0.10 videotestsrc ! decodebin ! ffmpegcolorspace ! facedetect ! ffmpegcolorspace ! xvimagesink
* ]|
* </refsect2>
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <gst/gst.h>
#include "gstfacedetect.h"
GST_DEBUG_CATEGORY_STATIC (gst_facedetect_debug);
#define GST_CAT_DEFAULT gst_facedetect_debug
#define DEFAULT_PROFILE "/usr/share/opencv/haarcascades/haarcascade_frontalface_default.xml"
/* Filter signals and args */
enum
{
/* FILL ME */
LAST_SIGNAL
};
enum
{
PROP_0,
PROP_DISPLAY,
PROP_PROFILE
};
/* the capabilities of the inputs and outputs.
*/
static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
GST_PAD_SINK,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("video/x-raw-rgb")
);
static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
GST_PAD_SRC,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("video/x-raw-rgb")
);
GST_BOILERPLATE (Gstfacedetect, gst_facedetect, GstElement, GST_TYPE_ELEMENT);
static void gst_facedetect_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec);
static void gst_facedetect_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec);
static gboolean gst_facedetect_set_caps (GstPad * pad, GstCaps * caps);
static GstFlowReturn gst_facedetect_chain (GstPad * pad, GstBuffer * buf);
static void gst_facedetect_load_profile (Gstfacedetect * filter);
/* Clean up */
static void
gst_facedetect_finalize (GObject * obj)
{
Gstfacedetect *filter = GST_FACEDETECT (obj);
if (filter->cvImage) {
cvReleaseImage (&filter->cvImage);
cvReleaseImage (&filter->cvGray);
}
+ g_free (filter->profile);
+
G_OBJECT_CLASS (parent_class)->finalize (obj);
}
/* GObject vmethod implementations */
static void
gst_facedetect_base_init (gpointer gclass)
{
GstElementClass *element_class = GST_ELEMENT_CLASS (gclass);
gst_element_class_set_details_simple (element_class,
"facedetect",
"Filter/Effect/Video",
"Performs face detection on videos and images, providing detected positions via bus messages",
"Michael Sheldon <mike@mikeasoft.com>");
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&src_factory));
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&sink_factory));
}
/* initialize the facedetect's class */
static void
gst_facedetect_class_init (GstfacedetectClass * klass)
{
GObjectClass *gobject_class;
GstElementClass *gstelement_class;
gobject_class = (GObjectClass *) klass;
gstelement_class = (GstElementClass *) klass;
parent_class = g_type_class_peek_parent (klass);
gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_facedetect_finalize);
gobject_class->set_property = gst_facedetect_set_property;
gobject_class->get_property = gst_facedetect_get_property;
g_object_class_install_property (gobject_class, PROP_DISPLAY,
g_param_spec_boolean ("display", "Display",
"Sets whether the detected faces should be highlighted in the output",
TRUE, G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_PROFILE,
g_param_spec_string ("profile", "Profile",
"Location of Haar cascade file to use for face detection",
DEFAULT_PROFILE, G_PARAM_READWRITE));
}
/* initialize the new element
* instantiate pads and add them to element
* set pad calback functions
* initialize instance structure
*/
static void
gst_facedetect_init (Gstfacedetect * filter, GstfacedetectClass * gclass)
{
filter->sinkpad = gst_pad_new_from_static_template (&sink_factory, "sink");
gst_pad_set_setcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR (gst_facedetect_set_caps));
gst_pad_set_getcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR (gst_pad_proxy_getcaps));
gst_pad_set_chain_function (filter->sinkpad,
GST_DEBUG_FUNCPTR (gst_facedetect_chain));
filter->srcpad = gst_pad_new_from_static_template (&src_factory, "src");
gst_pad_set_getcaps_function (filter->srcpad,
GST_DEBUG_FUNCPTR (gst_pad_proxy_getcaps));
gst_element_add_pad (GST_ELEMENT (filter), filter->sinkpad);
gst_element_add_pad (GST_ELEMENT (filter), filter->srcpad);
- filter->profile = DEFAULT_PROFILE;
+ filter->profile = g_strdup(DEFAULT_PROFILE);
filter->display = TRUE;
gst_facedetect_load_profile (filter);
}
static void
gst_facedetect_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec)
{
Gstfacedetect *filter = GST_FACEDETECT (object);
switch (prop_id) {
case PROP_PROFILE:
+ g_free (filter->profile);
filter->profile = g_value_dup_string (value);
gst_facedetect_load_profile (filter);
break;
case PROP_DISPLAY:
filter->display = g_value_get_boolean (value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gst_facedetect_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec)
{
Gstfacedetect *filter = GST_FACEDETECT (object);
switch (prop_id) {
case PROP_PROFILE:
- g_value_take_string (value, filter->profile);
+ g_value_set_string (value, filter->profile);
break;
case PROP_DISPLAY:
g_value_set_boolean (value, filter->display);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
/* GstElement vmethod implementations */
/* this function handles the link with other elements */
static gboolean
gst_facedetect_set_caps (GstPad * pad, GstCaps * caps)
{
Gstfacedetect *filter;
GstPad *otherpad;
gint width, height;
GstStructure *structure;
filter = GST_FACEDETECT (gst_pad_get_parent (pad));
structure = gst_caps_get_structure (caps, 0);
gst_structure_get_int (structure, "width", &width);
gst_structure_get_int (structure, "height", &height);
filter->cvImage = cvCreateImage (cvSize (width, height), IPL_DEPTH_8U, 3);
filter->cvGray = cvCreateImage (cvSize (width, height), IPL_DEPTH_8U, 1);
filter->cvStorage = cvCreateMemStorage (0);
otherpad = (pad == filter->srcpad) ? filter->sinkpad : filter->srcpad;
gst_object_unref (filter);
return gst_pad_set_caps (otherpad, caps);
}
/* chain function
* this function does the actual processing
*/
static GstFlowReturn
gst_facedetect_chain (GstPad * pad, GstBuffer * buf)
{
Gstfacedetect *filter;
CvSeq *faces;
int i;
filter = GST_FACEDETECT (GST_OBJECT_PARENT (pad));
filter->cvImage->imageData = (char *) GST_BUFFER_DATA (buf);
cvCvtColor (filter->cvImage, filter->cvGray, CV_RGB2GRAY);
cvClearMemStorage (filter->cvStorage);
if (filter->cvCascade) {
faces =
cvHaarDetectObjects (filter->cvGray, filter->cvCascade,
filter->cvStorage, 1.1, 2, 0, cvSize (30, 30));
for (i = 0; i < (faces ? faces->total : 0); i++) {
CvRect *r = (CvRect *) cvGetSeqElem (faces, i);
GstStructure *s = gst_structure_new ("face",
"x", G_TYPE_UINT, r->x,
"y", G_TYPE_UINT, r->y,
"width", G_TYPE_UINT, r->width,
"height", G_TYPE_UINT, r->height, NULL);
GstMessage *m = gst_message_new_element (GST_OBJECT (filter), s);
gst_element_post_message (GST_ELEMENT (filter), m);
if (filter->display) {
CvPoint center;
int radius;
center.x = cvRound ((r->x + r->width * 0.5));
center.y = cvRound ((r->y + r->height * 0.5));
radius = cvRound ((r->width + r->height) * 0.25);
cvCircle (filter->cvImage, center, radius, CV_RGB (255, 32, 32), 3, 8,
0);
}
}
}
gst_buffer_set_data (buf, filter->cvImage->imageData,
filter->cvImage->imageSize);
return gst_pad_push (filter->srcpad, buf);
}
static void
gst_facedetect_load_profile (Gstfacedetect * filter)
{
filter->cvCascade =
(CvHaarClassifierCascade *) cvLoad (filter->profile, 0, 0, 0);
if (!filter->cvCascade) {
GST_WARNING ("Couldn't load Haar classifier cascade: %s.", filter->profile);
}
}
/* entry point to initialize the plug-in
* initialize the plug-in itself
* register the element factories and other features
*/
gboolean
gst_facedetect_plugin_init (GstPlugin * plugin)
{
/* debug category for fltering log messages */
GST_DEBUG_CATEGORY_INIT (gst_facedetect_debug, "facedetect",
0,
"Performs face detection on videos and images, providing detected positions via bus messages");
return gst_element_register (plugin, "facedetect", GST_RANK_NONE,
GST_TYPE_FACEDETECT);
}
|
Elleo/gst-opencv
|
e30bc4032b6898dd462a8afefbcb3f227c5d1dde
|
Add simple text overlay plugin
|
diff --git a/AUTHORS b/AUTHORS
index 140d640..52ac932 100644
--- a/AUTHORS
+++ b/AUTHORS
@@ -1,4 +1,5 @@
Mike Sheldon <mike@mikeasoft.com>
Noam Lewis <jones.noamle@gmail.com>
Kapil Agrawal <kapil@mediamagictechnologies.com>
Thomas Vander Stichele <thomas@apestaart.org>
+Sreerenj Balachandran <bsreerenj@gmail.com>
diff --git a/configure.ac b/configure.ac
index 94a6d44..11edb9f 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1,142 +1,142 @@
AC_INIT
dnl versions of gstreamer and plugins-base
GST_MAJORMINOR=0.10
GST_REQUIRED=0.10.0
GSTPB_REQUIRED=0.10.0
dnl fill in your package name and version here
dnl the fourth (nano) number should be 0 for a release, 1 for CVS,
dnl and 2... for a prerelease
dnl when going to/from release please set the nano correctly !
dnl releases only do Wall, cvs and prerelease does Werror too
AS_VERSION(gst-opencv, GST_PLUGIN_VERSION, 0, 10, 0, 1,
GST_PLUGIN_CVS="no", GST_PLUGIN_CVS="yes")
dnl AM_MAINTAINER_MODE provides the option to enable maintainer mode
AM_MAINTAINER_MODE
AM_INIT_AUTOMAKE($PACKAGE, $VERSION)
dnl make aclocal work in maintainer mode
AC_SUBST(ACLOCAL_AMFLAGS, "-I m4")
AM_CONFIG_HEADER(config.h)
dnl check for tools
AC_PROG_CC
AC_PROG_LIBTOOL
dnl decide on error flags
AS_COMPILER_FLAG(-Wall, GST_WALL="yes", GST_WALL="no")
if test "x$GST_WALL" = "xyes"; then
GST_ERROR="$GST_ERROR -Wall"
# if test "x$GST_PLUGIN_CVS" = "xyes"; then
# AS_COMPILER_FLAG(-Werror,GST_ERROR="$GST_ERROR -Werror",GST_ERROR="$GST_ERROR")
# fi
fi
dnl Check for pkgconfig first
AC_CHECK_PROG(HAVE_PKGCONFIG, pkg-config, yes, no)
dnl Give error and exit if we don't have pkgconfig
if test "x$HAVE_PKGCONFIG" = "xno"; then
AC_MSG_ERROR(you need to have pkgconfig installed !)
fi
dnl Now we're ready to ask for gstreamer libs and cflags
dnl And we can also ask for the right version of gstreamer
PKG_CHECK_MODULES(GST, \
gstreamer-$GST_MAJORMINOR >= $GST_REQUIRED,
HAVE_GST=yes,HAVE_GST=no)
dnl Give error and exit if we don't have gstreamer
if test "x$HAVE_GST" = "xno"; then
AC_MSG_ERROR(you need gstreamer development packages installed !)
fi
dnl append GST_ERROR cflags to GST_CFLAGS
GST_CFLAGS="$GST_CFLAGS $GST_ERROR"
dnl make GST_CFLAGS and GST_LIBS available
AC_SUBST(GST_CFLAGS)
AC_SUBST(GST_LIBS)
dnl make GST_MAJORMINOR available in Makefile.am
AC_SUBST(GST_MAJORMINOR)
dnl If we need them, we can also use the base class libraries
PKG_CHECK_MODULES(GST_BASE, gstreamer-base-$GST_MAJORMINOR >= $GST_REQUIRED,
HAVE_GST_BASE=yes, HAVE_GST_BASE=no)
dnl Give a warning if we don't have gstreamer libs
dnl you can turn this into an error if you need them
if test "x$HAVE_GST_BASE" = "xno"; then
AC_MSG_NOTICE(no GStreamer base class libraries found (gstreamer-base-$GST_MAJORMINOR))
fi
dnl make _CFLAGS and _LIBS available
AC_SUBST(GST_BASE_CFLAGS)
AC_SUBST(GST_BASE_LIBS)
PKG_CHECK_MODULES(OPENCV,
opencv,
HAVE_OPENCV=yes, HAVE_OPENCV=no)
AC_SUBST(OPENCV_CFLAGS)
AC_SUBST(OPENCV_LIBS)
if test "x$HAVE_OPENCV" = "xno"; then
AC_MSG_ERROR(OpenCV libraries could not be found)
fi
dnl If we need them, we can also use the gstreamer-plugins-base libraries
PKG_CHECK_MODULES(GSTPB_BASE,
gstreamer-plugins-base-$GST_MAJORMINOR >= $GSTPB_REQUIRED,
HAVE_GSTPB_BASE=yes, HAVE_GSTPB_BASE=no)
dnl Give a warning if we don't have gstreamer libs
dnl you can turn this into an error if you need them
if test "x$HAVE_GSTPB_BASE" = "xno"; then
AC_MSG_NOTICE(no GStreamer Plugins Base libraries found (gstreamer-plugins-base-$GST_MAJORMINOR))
fi
dnl make _CFLAGS and _LIBS available
AC_SUBST(GSTPB_BASE_CFLAGS)
AC_SUBST(GSTPB_BASE_LIBS)
dnl If we need them, we can also use the gstreamer-controller libraries
PKG_CHECK_MODULES(GSTCTRL,
gstreamer-controller-$GST_MAJORMINOR >= $GSTPB_REQUIRED,
HAVE_GSTCTRL=yes, HAVE_GSTCTRL=no)
dnl Give a warning if we don't have gstreamer-controller
dnl you can turn this into an error if you need them
if test "x$HAVE_GSTCTRL" = "xno"; then
AC_MSG_NOTICE(no GStreamer Controller libraries found (gstreamer-controller-$GST_MAJORMINOR))
fi
dnl make _CFLAGS and _LIBS available
AC_SUBST(GSTCTRL_CFLAGS)
AC_SUBST(GSTCTRL_LIBS)
dnl set the plugindir where plugins should be installed
if test "x${prefix}" = "x$HOME"; then
plugindir="$HOME/.gstreamer-$GST_MAJORMINOR/plugins"
else
plugindir="\$(libdir)/gstreamer-$GST_MAJORMINOR"
fi
AC_SUBST(plugindir)
dnl set proper LDFLAGS for plugins
GST_PLUGIN_LDFLAGS='-module -avoid-version -export-symbols-regex [_]*\(gst_\|Gst\|GST_\).*'
AC_SUBST(GST_PLUGIN_LDFLAGS)
-AC_OUTPUT(Makefile m4/Makefile src/Makefile src/edgedetect/Makefile src/faceblur/Makefile src/facedetect/Makefile src/pyramidsegment/Makefile src/templatematch/Makefile)
+AC_OUTPUT(Makefile m4/Makefile src/Makefile src/edgedetect/Makefile src/faceblur/Makefile src/facedetect/Makefile src/pyramidsegment/Makefile src/templatematch/Makefile src/textwrite/Makefile)
diff --git a/src/Makefile.am b/src/Makefile.am
index 9a9ac41..4c9e575 100644
--- a/src/Makefile.am
+++ b/src/Makefile.am
@@ -1,36 +1,39 @@
-SUBDIRS = edgedetect faceblur facedetect pyramidsegment templatematch
+SUBDIRS = edgedetect faceblur facedetect pyramidsegment templatematch textwrite
# plugindir is set in configure
plugin_LTLIBRARIES = libgstopencv.la
# sources used to compile this plug-in
libgstopencv_la_SOURCES = gstopencv.c
# flags used to compile this facedetect
# add other _CFLAGS and _LIBS as needed
libgstopencv_la_CFLAGS = $(GST_CFLAGS) $(OPENCV_CFLAGS) \
-I${top_srcdir}/src/edgedetect \
-I${top_srcdir}/src/faceblur \
-I${top_srcdir}/src/facedetect \
-I${top_srcdir}/src/pyramidsegment \
- -I${top_srcdir}/src/templatematch
+ -I${top_srcdir}/src/templatematch \
+ -I${top_srcdir}/src/textwrite
libgstopencv_la_LIBADD = $(GST_LIBS) $(OPENCV_LIBS) \
$(top_builddir)/src/edgedetect/libgstedgedetect.la \
$(top_builddir)/src/faceblur/libgstfaceblur.la \
$(top_builddir)/src/facedetect/libgstfacedetect.la \
$(top_builddir)/src/pyramidsegment/libgstpyramidsegment.la \
- $(top_builddir)/src/templatematch/libgsttemplatematch.la
+ $(top_builddir)/src/templatematch/libgsttemplatematch.la \
+ $(top_builddir)/src/textwrite/libgsttextwrite.la
libgstopencv_la_LDFLAGS = $(GST_PLUGIN_LDFLAGS)
libgstopencv_la_DEPENDENCIES = \
$(top_builddir)/src/edgedetect/libgstedgedetect.la \
$(top_builddir)/src/faceblur/libgstfaceblur.la \
$(top_builddir)/src/facedetect/libgstfacedetect.la \
$(top_builddir)/src/pyramidsegment/libgstpyramidsegment.la \
- $(top_builddir)/src/templatematch/libgsttemplatematch.la
+ $(top_builddir)/src/templatematch/libgsttemplatematch.la \
+ $(top_builddir)/src/textwrite/libgsttextwrite.la
# headers we need but don't want installed
noinst_HEADERS =
diff --git a/src/gstopencv.c b/src/gstopencv.c
index f08fdb1..120efd8 100644
--- a/src/gstopencv.c
+++ b/src/gstopencv.c
@@ -1,58 +1,62 @@
/* GStreamer
* Copyright (C) <2009> Kapil Agrawal <kapil@mediamagictechnologies.com>
*
* gstopencv.c: plugin registering
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "gstedgedetect.h"
#include "gstfaceblur.h"
#include "gstfacedetect.h"
#include "gstpyramidsegment.h"
#include "gsttemplatematch.h"
+#include "gsttextwrite.h"
static gboolean
plugin_init (GstPlugin * plugin)
{
if (!gst_edgedetect_plugin_init (plugin))
return FALSE;
if (!gst_faceblur_plugin_init (plugin))
return FALSE;
if (!gst_facedetect_plugin_init (plugin))
return FALSE;
if (!gst_pyramidsegment_plugin_init (plugin))
return FALSE;
if (!gst_templatematch_plugin_init (plugin))
return FALSE;
+ if (!gst_textwrite_plugin_init (plugin))
+ return FALSE;
+
return TRUE;
}
GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
GST_VERSION_MINOR,
"opencv",
"GStreamer OpenCV Plugins",
plugin_init, VERSION, "LGPL", "OpenCv", "http://opencv.willowgarage.com")
diff --git a/src/textwrite/Makefile.am b/src/textwrite/Makefile.am
new file mode 100644
index 0000000..677224c
--- /dev/null
+++ b/src/textwrite/Makefile.am
@@ -0,0 +1,15 @@
+# plugindir is set in configure
+
+noinst_LTLIBRARIES = libgsttextwrite.la
+
+# sources used to compile this plug-in
+libgsttextwrite_la_SOURCES = gsttextwrite.c
+
+# flags used to compile this textwrite
+# add other _CFLAGS and _LIBS as needed
+libgsttextwrite_la_CFLAGS = $(GST_CFLAGS) $(OPENCV_CFLAGS)
+libgsttextwrite_la_LIBADD = $(GST_LIBS) $(OPENCV_LIBS)
+libgsttextwrite_la_LDFLAGS = $(GST_PLUGIN_LDFLAGS)
+
+# headers we need but don't want installed
+noinst_HEADERS = gsttextwrite.h
diff --git a/src/textwrite/gsttextwrite.c b/src/textwrite/gsttextwrite.c
new file mode 100644
index 0000000..3369e92
--- /dev/null
+++ b/src/textwrite/gsttextwrite.c
@@ -0,0 +1,329 @@
+/*
+ * GStreamer
+ * Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
+ * Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
+ * Copyright (C) 2010 Sreerenj Balachandran <bsreerenj@gmail.com>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ * Alternatively, the contents of this file may be used under the
+ * GNU Lesser General Public License Version 2.1 (the "LGPL"), in
+ * which case the following provisions apply instead of the ones
+ * mentioned above:
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+/**
+ * SECTION:element-textwrite
+ *
+ * FIXME:Describe textwrite here.
+ *
+ * <refsect2>
+ * <title>Example launch line</title>
+ * |[
+ * gst-launch -v -m fakesrc ! textwrite ! fakesink silent=TRUE
+ * ]|
+ * </refsect2>
+ */
+
+#ifdef HAVE_CONFIG_H
+# include <config.h>
+#endif
+
+#include <gst/gst.h>
+
+#include "gsttextwrite.h"
+
+GST_DEBUG_CATEGORY_STATIC (gst_textwrite_debug);
+#define GST_CAT_DEFAULT gst_textwrite_debug
+#define DEFAULT_PROP_TEXT ""
+#define DEFAULT_PROP_WIDTH 1
+#define DEFAULT_PROP_HEIGHT 1
+
+/* Filter signals and args */
+enum
+{
+ /* FILL ME */
+ LAST_SIGNAL
+};
+#define DEFAULT_WIDTH 1.0
+#define DEFAULT_HEIGHT 1.0
+enum
+{
+ PROP_0,
+ PROP_TEXT,
+ PROP_HEIGHT,
+ PROP_WIDTH
+};
+
+/* the capabilities of the inputs and outputs.
+ *
+ * describe the real formats here.
+ */
+static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
+ GST_PAD_SINK,
+ GST_PAD_ALWAYS,
+ GST_STATIC_CAPS ("video/x-raw-rgb")
+ );
+
+static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
+ GST_PAD_SRC,
+ GST_PAD_ALWAYS,
+ GST_STATIC_CAPS ("ANY")
+ );
+
+GST_BOILERPLATE (Gsttextwrite, gst_textwrite, GstElement,GST_TYPE_ELEMENT);
+
+static void gst_textwrite_set_property (GObject * object, guint prop_id,
+ const GValue * value, GParamSpec * pspec);
+static void gst_textwrite_get_property (GObject * object, guint prop_id,
+ GValue * value, GParamSpec * pspec);
+
+static gboolean gst_textwrite_set_caps (GstPad * pad, GstCaps * caps);
+static GstFlowReturn gst_textwrite_chain (GstPad * pad, GstBuffer * buf);
+
+
+
+/* Clean up */
+static void
+gst_textwrite_finalize (GObject * obj)
+{
+ Gsttextwrite *filter = GST_textwrite (obj);
+
+ if (filter->cvImage) {
+ cvReleaseImage (&filter->cvImage);
+ }
+
+ G_OBJECT_CLASS (parent_class)->finalize (obj);
+}
+
+
+
+/* GObject vmethod implementations */
+
+static void
+gst_textwrite_base_init (gpointer gclass)
+{
+ GstElementClass *element_class = GST_ELEMENT_CLASS (gclass);
+
+ gst_element_class_set_details_simple(element_class,
+ "textwrite",
+ "Filter/Effect/Video",
+ "Performs text writing to the video",
+ "sreerenj<bsreerenj@gmail.com>");
+
+ gst_element_class_add_pad_template (element_class,
+ gst_static_pad_template_get (&src_factory));
+ gst_element_class_add_pad_template (element_class,
+ gst_static_pad_template_get (&sink_factory));
+}
+
+/* initialize the textwrite's class */
+static void
+gst_textwrite_class_init (GsttextwriteClass * klass)
+{
+ GObjectClass *gobject_class;
+ GstElementClass *gstelement_class;
+
+ gobject_class = (GObjectClass *) klass;
+ gstelement_class = (GstElementClass *) klass;
+
+ parent_class = g_type_class_peek_parent (klass);
+ gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_textwrite_finalize);
+
+ gobject_class->set_property = gst_textwrite_set_property;
+ gobject_class->get_property = gst_textwrite_get_property;
+
+
+ g_object_class_install_property (gobject_class, PROP_TEXT,
+ g_param_spec_string ("text", "text",
+ "Text to be display.", DEFAULT_PROP_TEXT,
+ G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
+
+ g_object_class_install_property (gobject_class, PROP_HEIGHT,
+ g_param_spec_double ("height", "Height",
+ "Sets the height of fonts",1.0,5.0,
+ DEFAULT_HEIGHT, G_PARAM_READWRITE|G_PARAM_STATIC_STRINGS));
+
+ g_object_class_install_property (gobject_class, PROP_WIDTH,
+ g_param_spec_double ("width", "Width",
+ "Sets the width of fonts",1.0,5.0,
+ DEFAULT_WIDTH, G_PARAM_READWRITE| G_PARAM_STATIC_STRINGS));
+
+}
+
+/* initialize the new element
+ * instantiate pads and add them to element
+ * set pad calback functions
+ * initialize instance structure
+ */
+static void
+gst_textwrite_init (Gsttextwrite * filter,
+ GsttextwriteClass * gclass)
+{
+ filter->sinkpad = gst_pad_new_from_static_template (&sink_factory, "sink");
+ gst_pad_set_setcaps_function (filter->sinkpad,
+ GST_DEBUG_FUNCPTR(gst_textwrite_set_caps));
+ gst_pad_set_getcaps_function (filter->sinkpad,
+ GST_DEBUG_FUNCPTR(gst_pad_proxy_getcaps));
+ gst_pad_set_chain_function (filter->sinkpad,
+ GST_DEBUG_FUNCPTR(gst_textwrite_chain));
+
+ filter->srcpad = gst_pad_new_from_static_template (&src_factory, "src");
+ gst_pad_set_getcaps_function (filter->srcpad,
+ GST_DEBUG_FUNCPTR(gst_pad_proxy_getcaps));
+
+ gst_element_add_pad (GST_ELEMENT (filter), filter->sinkpad);
+ gst_element_add_pad (GST_ELEMENT (filter), filter->srcpad);
+ filter->textbuf = g_strdup (DEFAULT_PROP_TEXT);
+ filter->width=DEFAULT_PROP_WIDTH;
+ filter->height=DEFAULT_PROP_HEIGHT;
+
+}
+
+static void
+gst_textwrite_set_property (GObject * object, guint prop_id,
+ const GValue * value, GParamSpec * pspec)
+{
+ Gsttextwrite *filter = GST_textwrite (object);
+
+ switch (prop_id) {
+ case PROP_TEXT:
+ g_free (filter->textbuf);
+ filter->textbuf = g_value_dup_string (value);
+ break;
+ case PROP_HEIGHT:
+ filter->height = g_value_get_double(value);
+ break;
+ case PROP_WIDTH:
+ filter->width = g_value_get_double(value);
+ break;
+ default:
+ G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
+ break;
+ }
+}
+
+static void
+gst_textwrite_get_property (GObject * object, guint prop_id,
+ GValue * value, GParamSpec * pspec)
+{
+ Gsttextwrite *filter = GST_textwrite (object);
+
+ switch (prop_id) {
+ case PROP_TEXT:
+ g_value_set_string (value, filter->textbuf);
+ break;
+ case PROP_HEIGHT:
+ g_value_set_double (value, filter->height);
+ break;
+ case PROP_WIDTH:
+ g_value_set_double (value, filter->width);
+ break;
+ default:
+ G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
+ break;
+ }
+}
+
+/* GstElement vmethod implementations */
+
+/* this function handles the link with other elements */
+static gboolean
+gst_textwrite_set_caps (GstPad * pad, GstCaps * caps)
+{
+ Gsttextwrite *filter;
+ GstPad *otherpad;
+
+ gint width, height;
+ GstStructure *structure;
+
+ filter = GST_textwrite (gst_pad_get_parent (pad));
+
+ structure = gst_caps_get_structure (caps, 0);
+ gst_structure_get_int (structure, "width", &width);
+ gst_structure_get_int (structure, "height", &height);
+
+ filter->cvImage = cvCreateImage (cvSize (width, height), IPL_DEPTH_8U, 3);
+ filter->cvStorage = cvCreateMemStorage (0);
+
+ otherpad = (pad == filter->srcpad) ? filter->sinkpad : filter->srcpad;
+ gst_object_unref (filter);
+
+ return gst_pad_set_caps (otherpad, caps);
+}
+
+/* chain function
+ * this function does the actual processing
+ */
+static GstFlowReturn
+gst_textwrite_chain (GstPad * pad, GstBuffer * buf)
+{
+ Gsttextwrite *filter;
+
+ filter = GST_textwrite (GST_OBJECT_PARENT (pad));
+
+ filter->cvImage->imageData = (char *) GST_BUFFER_DATA (buf);
+ int lineWidth=1;
+ cvInitFont(&(filter->font),CV_FONT_VECTOR0, filter->width,filter->height,0,lineWidth,0);
+
+
+ cvPutText (filter->cvImage,filter->textbuf,cvPoint(100,100), &(filter->font), cvScalar(165,14,14,0));
+
+
+ gst_buffer_set_data (buf, filter->cvImage->imageData,filter->cvImage->imageSize);
+
+
+ return gst_pad_push (filter->srcpad, buf);
+}
+
+
+/* entry point to initialize the plug-in
+ * initialize the plug-in itself
+ * register the element factories and other features
+ */
+gboolean
+gst_textwrite_plugin_init (GstPlugin * plugin)
+{
+ /* debug category for fltering log messages
+ *
+ * exchange the string 'Template textwrite' with your description
+ */
+ GST_DEBUG_CATEGORY_INIT (gst_textwrite_debug, "textwrite",
+ 0, "Template textwrite");
+
+ return gst_element_register (plugin, "textwrite", GST_RANK_NONE,
+ GST_TYPE_textwrite);
+}
+
+
diff --git a/src/textwrite/gsttextwrite.h b/src/textwrite/gsttextwrite.h
new file mode 100644
index 0000000..8253e91
--- /dev/null
+++ b/src/textwrite/gsttextwrite.h
@@ -0,0 +1,98 @@
+/*
+ * GStreamer
+ * Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
+ * Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
+ * Copyright (C) 2010 root <<user@hostname.org>>m
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ * Alternatively, the contents of this file may be used under the
+ * GNU Lesser General Public License Version 2.1 (the "LGPL"), in
+ * which case the following provisions apply instead of the ones
+ * mentioned above:
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+#ifndef __GST_textwrite_H__
+#define __GST_textwrite_H__
+
+#include <gst/gst.h>
+//sreechage
+#include <cv.h>
+#include <cvaux.h>
+#include <highgui.h>
+G_BEGIN_DECLS
+
+/* #defines don't like whitespacey bits */
+#define GST_TYPE_textwrite \
+ (gst_textwrite_get_type())
+#define GST_textwrite(obj) \
+ (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_textwrite,Gsttextwrite))
+#define GST_textwrite_CLASS(klass) \
+ (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_textwrite,GsttextwriteClass))
+#define GST_IS_textwrite(obj) \
+ (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_textwrite))
+#define GST_IS_textwrite_CLASS(klass) \
+ (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_textwrite))
+
+typedef struct _Gsttextwrite Gsttextwrite;
+typedef struct _GsttextwriteClass GsttextwriteClass;
+
+struct _Gsttextwrite
+{
+ GstElement element;
+
+ GstPad *sinkpad, *srcpad;
+
+
+ IplImage *cvImage;
+ CvMemStorage *cvStorage;
+ CvFont font;
+
+ gdouble height;
+ gdouble width;
+ gchar *textbuf;
+
+};
+
+struct _GsttextwriteClass
+{
+ GstElementClass parent_class;
+};
+
+GType gst_textwrite_get_type (void);
+gboolean gst_textwrite_plugin_init (GstPlugin * plugin);
+
+G_END_DECLS
+
+#endif /* __GST_textwrite_H__ */
|
Elleo/gst-opencv
|
97eaa64c4246ec5459f81e8b34603b3fbf5de186
|
faceblur: fix handling of profile property.
|
diff --git a/src/faceblur/gstfaceblur.c b/src/faceblur/gstfaceblur.c
index e9da8f8..5f1deb3 100644
--- a/src/faceblur/gstfaceblur.c
+++ b/src/faceblur/gstfaceblur.c
@@ -1,313 +1,316 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2008 Michael Sheldon <mike@mikeasoft.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/**
* SECTION:element-faceblur
*
* FIXME:Describe faceblur here.
*
* <refsect2>
* <title>Example launch line</title>
* |[
* gst-launch-0.10 videotestsrc ! decodebin ! ffmpegcolorspace ! faceblur ! ffmpegcolorspace ! xvimagesink
* ]|
* </refsect2>
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <gst/gst.h>
#include "gstfaceblur.h"
GST_DEBUG_CATEGORY_STATIC (gst_faceblur_debug);
#define GST_CAT_DEFAULT gst_faceblur_debug
#define DEFAULT_PROFILE "/usr/share/opencv/haarcascades/haarcascade_frontalface_default.xml"
/* Filter signals and args */
enum
{
/* FILL ME */
LAST_SIGNAL
};
enum
{
PROP_0,
PROP_PROFILE
};
/* the capabilities of the inputs and outputs.
*/
static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
GST_PAD_SINK,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("video/x-raw-rgb")
);
static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
GST_PAD_SRC,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("video/x-raw-rgb")
);
GST_BOILERPLATE (Gstfaceblur, gst_faceblur, GstElement, GST_TYPE_ELEMENT);
static void gst_faceblur_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec);
static void gst_faceblur_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec);
static gboolean gst_faceblur_set_caps (GstPad * pad, GstCaps * caps);
static GstFlowReturn gst_faceblur_chain (GstPad * pad, GstBuffer * buf);
static void gst_faceblur_load_profile (Gstfaceblur * filter);
/* Clean up */
static void
gst_faceblur_finalize (GObject * obj)
{
Gstfaceblur *filter = GST_FACEBLUR (obj);
if (filter->cvImage) {
cvReleaseImage (&filter->cvImage);
cvReleaseImage (&filter->cvGray);
}
+
+ g_free (filter->profile);
G_OBJECT_CLASS (parent_class)->finalize (obj);
}
/* GObject vmethod implementations */
static void
gst_faceblur_base_init (gpointer gclass)
{
GstElementClass *element_class = GST_ELEMENT_CLASS (gclass);
gst_element_class_set_details_simple (element_class,
"faceblur",
"Filter/Effect/Video",
"Blurs faces in images and videos",
"Michael Sheldon <mike@mikeasoft.com>");
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&src_factory));
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&sink_factory));
}
/* initialize the faceblur's class */
static void
gst_faceblur_class_init (GstfaceblurClass * klass)
{
GObjectClass *gobject_class;
GstElementClass *gstelement_class;
gobject_class = (GObjectClass *) klass;
gstelement_class = (GstElementClass *) klass;
parent_class = g_type_class_peek_parent (klass);
gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_faceblur_finalize);
gobject_class->set_property = gst_faceblur_set_property;
gobject_class->get_property = gst_faceblur_get_property;
g_object_class_install_property (gobject_class, PROP_PROFILE,
g_param_spec_string ("profile", "Profile",
"Location of Haar cascade file to use for face blurion",
DEFAULT_PROFILE, G_PARAM_READWRITE));
}
/* initialize the new element
* instantiate pads and add them to element
* set pad calback functions
* initialize instance structure
*/
static void
gst_faceblur_init (Gstfaceblur * filter, GstfaceblurClass * gclass)
{
filter->sinkpad = gst_pad_new_from_static_template (&sink_factory, "sink");
gst_pad_set_setcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR (gst_faceblur_set_caps));
gst_pad_set_getcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR (gst_pad_proxy_getcaps));
gst_pad_set_chain_function (filter->sinkpad,
GST_DEBUG_FUNCPTR (gst_faceblur_chain));
filter->srcpad = gst_pad_new_from_static_template (&src_factory, "src");
gst_pad_set_getcaps_function (filter->srcpad,
GST_DEBUG_FUNCPTR (gst_pad_proxy_getcaps));
gst_element_add_pad (GST_ELEMENT (filter), filter->sinkpad);
gst_element_add_pad (GST_ELEMENT (filter), filter->srcpad);
- filter->profile = DEFAULT_PROFILE;
+ filter->profile = g_strdup (DEFAULT_PROFILE);
gst_faceblur_load_profile (filter);
}
static void
gst_faceblur_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec)
{
Gstfaceblur *filter = GST_FACEBLUR (object);
switch (prop_id) {
case PROP_PROFILE:
+ g_free (filter->profile);
filter->profile = g_value_dup_string (value);
gst_faceblur_load_profile (filter);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gst_faceblur_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec)
{
Gstfaceblur *filter = GST_FACEBLUR (object);
switch (prop_id) {
case PROP_PROFILE:
- g_value_take_string (value, filter->profile);
+ g_value_set_string (value, filter->profile);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
/* GstElement vmethod implementations */
/* this function handles the link with other elements */
static gboolean
gst_faceblur_set_caps (GstPad * pad, GstCaps * caps)
{
Gstfaceblur *filter;
GstPad *otherpad;
gint width, height;
GstStructure *structure;
filter = GST_FACEBLUR (gst_pad_get_parent (pad));
structure = gst_caps_get_structure (caps, 0);
gst_structure_get_int (structure, "width", &width);
gst_structure_get_int (structure, "height", &height);
filter->cvImage = cvCreateImage (cvSize (width, height), IPL_DEPTH_8U, 3);
filter->cvGray = cvCreateImage (cvSize (width, height), IPL_DEPTH_8U, 1);
filter->cvStorage = cvCreateMemStorage (0);
otherpad = (pad == filter->srcpad) ? filter->sinkpad : filter->srcpad;
gst_object_unref (filter);
return gst_pad_set_caps (otherpad, caps);
}
/* chain function
* this function does the actual processing
*/
static GstFlowReturn
gst_faceblur_chain (GstPad * pad, GstBuffer * buf)
{
Gstfaceblur *filter;
CvSeq *faces;
int i;
filter = GST_FACEBLUR (GST_OBJECT_PARENT (pad));
filter->cvImage->imageData = (char *) GST_BUFFER_DATA (buf);
cvCvtColor (filter->cvImage, filter->cvGray, CV_RGB2GRAY);
cvClearMemStorage (filter->cvStorage);
if (filter->cvCascade) {
faces =
cvHaarDetectObjects (filter->cvGray, filter->cvCascade,
filter->cvStorage, 1.1, 2, 0, cvSize (30, 30));
for (i = 0; i < (faces ? faces->total : 0); i++) {
CvRect *r = (CvRect *) cvGetSeqElem (faces, i);
cvSetImageROI (filter->cvImage, *r);
cvSmooth (filter->cvImage, filter->cvImage, CV_BLUR, 11, 11, 0, 0);
cvSmooth (filter->cvImage, filter->cvImage, CV_GAUSSIAN, 11, 11, 0, 0);
cvResetImageROI (filter->cvImage);
}
}
gst_buffer_set_data (buf, filter->cvImage->imageData,
filter->cvImage->imageSize);
return gst_pad_push (filter->srcpad, buf);
}
static void
gst_faceblur_load_profile (Gstfaceblur * filter)
{
filter->cvCascade =
(CvHaarClassifierCascade *) cvLoad (filter->profile, 0, 0, 0);
if (!filter->cvCascade) {
GST_WARNING ("Couldn't load Haar classifier cascade: %s.", filter->profile);
}
}
/* entry point to initialize the plug-in
* initialize the plug-in itself
* register the element factories and other features
*/
gboolean
gst_faceblur_plugin_init (GstPlugin * plugin)
{
/* debug category for filtering log messages */
GST_DEBUG_CATEGORY_INIT (gst_faceblur_debug, "faceblur",
0, "Blurs faces in images and videos");
return gst_element_register (plugin, "faceblur", GST_RANK_NONE,
GST_TYPE_FACEBLUR);
}
|
Elleo/gst-opencv
|
b76cab6955b223d18f059ec10428aaa0359f486e
|
Fix includes in template matching element
|
diff --git a/src/templatematch/gsttemplatematch.h b/src/templatematch/gsttemplatematch.h
index d4f8414..b18e0c7 100644
--- a/src/templatematch/gsttemplatematch.h
+++ b/src/templatematch/gsttemplatematch.h
@@ -1,92 +1,92 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2008 Michael Sheldon <mike@mikeasoft.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#ifndef __GST_TEMPLATEMATCH_H__
#define __GST_TEMPLATEMATCH_H__
#include <gst/gst.h>
-#include <opencv/cv.h>
-#include <opencv/highgui.h>
+#include <cv.h>
+#include <highgui.h>
G_BEGIN_DECLS
/* #defines don't like whitespacey bits */
#define GST_TYPE_TEMPLATEMATCH \
(gst_templatematch_get_type())
#define GST_TEMPLATEMATCH(obj) \
(G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_TEMPLATEMATCH,GstTemplateMatch))
#define GST_TEMPLATEMATCH_CLASS(klass) \
(G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_TEMPLATEMATCH,GstTemplateMatchClass))
#define GST_IS_TEMPLATEMATCH(obj) \
(G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_TEMPLATEMATCH))
#define GST_IS_TEMPLATEMATCH_CLASS(klass) \
(G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_TEMPLATEMATCH))
typedef struct _GstTemplateMatch GstTemplateMatch;
typedef struct _GstTemplateMatchClass GstTemplateMatchClass;
struct _GstTemplateMatch
{
GstElement element;
GstPad *sinkpad, *srcpad;
gint method;
gboolean display;
gchar *template;
IplImage *cvImage, *cvGray, *cvTemplateImage, *cvDistImage;
};
struct _GstTemplateMatchClass
{
GstElementClass parent_class;
};
GType gst_templatematch_get_type (void);
gboolean gst_templatematch_plugin_init (GstPlugin * templatematch);
G_END_DECLS
#endif /* __GST_TEMPLATEMATCH_H__ */
|
Elleo/gst-opencv
|
3435bb2200294a321b4ca53144af08daf3b6701b
|
Bring code in to line with general Gstreamer standards
|
diff --git a/ChangeLog b/ChangeLog
index a871587..dd740cc 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,68 +1,81 @@
2009-05-26 Mike Sheldon <mike@mikeasoft.com>
* AUTHORS:
Add all current contributors to the authors list
+ * src/edgedetect/gstedgedetect.c:
+ * src/edgedetect/gstedgedetect.h:
+ * src/faceblur/gstfaceblur.c:
+ * src/faceblur/gstfaceblur.h:
+ * src/facedetect/gstfacedetect.c:
+ * src/facedetect/gstfacedetect.h:
+ * src/gstopencv.c:
+ * src/pyramidsegment/gstpyramidsegment.c:
+ * src/pyramidsegment/gstpyramidsegment.h:
+ * src/templatematch/gsttemplatematch.c:
+ * src/templatematch/gsttemplatematch.h:
+ Bring code in to line with general gstreamer standards
+
2009-05-25 Mike Sheldon <mike@mikeasoft.com>
* configure.ac:
* src/Makefile.am:
* src/gstopencv.c:
* src/faceblur/gstfaceblur.c:
* src/faceblur/gstfaceblur.h:
* src/faceblur/Makefile.am:
Add face blurring element
* debian/control:
* debian/changelog:
Fix dependencies and package section for debian package
* src/templatematch/gsttemplatematch.c:
Fix segfault when no template is loaded
Update example launch line to load a template
* examples/python/templatematch.py:
* examples/python/template.jpg:
Add example usage of the template matching element
2009-05-13 Noam Lewis <jones.noamle@gmail.com>
* configure.ac:
* src/Makefile.am:
* src/gstopencv.c:
* src/templatematch/gsttemplatematch.c:
* src/templatematch/gsttemplatematch.h:
* src/tempaltematch/Makefile.am:
Add template matching element
2009-05-08 Kapil Agrawal <kapil@mediamagictechnologies.com>
* configure.ac:
* src/Makefile.am:
* src/gstopencv.c:
* src/edgedetect/Makefile.am:
* src/edgedetect/gstedgedetect.c:
* src/facedetect/Makefile.am:
* src/facedetect/gstfacedetect.c:
* src/pyramidsegment/Makefile.am:
* src/pyramidsegment/gstpyramidsegment.c:
All elements will register as features of opencv plugin.
2009-05-06 Mike Sheldon <mike@mikeasoft.com>
* src/facedetect/gstfacedetect.c:
Fix "profile" parameter in face detect element to accept a string correctly
(was using char param instead of string param)
* src/edgedetect/gstedgedetect.c:
* src/pyramidsegment/gstpyramidsegment.c:
* src/facedetect/gstfacedetect.c:
Release OpenCV images when finalizing
2009-05-06 Kapil Agrawal <kapil@mediamagictechnologies.com>
* configure.ac: Added an error check for opencv.
* src/edgedetect/gstedgedetect.h:
* src/facedetect/gstfacedetect.h:
* src/pyramidsegment/gstpyramidsegment.h: Fixed the included path.
Fixed some compilation errors.
diff --git a/src/edgedetect/gstedgedetect.c b/src/edgedetect/gstedgedetect.c
index c5c226a..c88d5e3 100644
--- a/src/edgedetect/gstedgedetect.c
+++ b/src/edgedetect/gstedgedetect.c
@@ -1,331 +1,330 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2008 Michael Sheldon <mike@mikeasoft.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/**
* SECTION:element-edgedetect
*
* FIXME:Describe edgedetect here.
*
* <refsect2>
* <title>Example launch line</title>
* |[
* gst-launch-0.10 videotestsrc ! decodebin ! ffmpegcolorspace ! edgedetect ! ffmpegcolorspace ! xvimagesink
* ]|
* </refsect2>
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <gst/gst.h>
#include "gstedgedetect.h"
GST_DEBUG_CATEGORY_STATIC (gst_edgedetect_debug);
#define GST_CAT_DEFAULT gst_edgedetect_debug
/* Filter signals and args */
enum
{
/* FILL ME */
LAST_SIGNAL
};
enum
{
PROP_0,
PROP_THRESHOLD1,
PROP_THRESHOLD2,
PROP_APERTURE,
PROP_MASK
};
/* the capabilities of the inputs and outputs.
*
* describe the real formats here.
*/
static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
GST_PAD_SINK,
GST_PAD_ALWAYS,
- GST_STATIC_CAPS (
- "video/x-raw-rgb"
- )
-);
+ GST_STATIC_CAPS ("video/x-raw-rgb")
+ );
static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
GST_PAD_SRC,
GST_PAD_ALWAYS,
- GST_STATIC_CAPS (
- "video/x-raw-rgb"
- )
-);
+ GST_STATIC_CAPS ("video/x-raw-rgb")
+ );
-GST_BOILERPLATE (Gstedgedetect, gst_edgedetect, GstElement,
- GST_TYPE_ELEMENT);
+GST_BOILERPLATE (Gstedgedetect, gst_edgedetect, GstElement, GST_TYPE_ELEMENT);
static void gst_edgedetect_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec);
static void gst_edgedetect_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec);
static gboolean gst_edgedetect_set_caps (GstPad * pad, GstCaps * caps);
static GstFlowReturn gst_edgedetect_chain (GstPad * pad, GstBuffer * buf);
/* Clean up */
static void
gst_edgedetect_finalize (GObject * obj)
{
Gstedgedetect *filter = GST_EDGEDETECT (obj);
- if (filter->cvImage != NULL)
- {
+ if (filter->cvImage != NULL) {
cvReleaseImage (&filter->cvImage);
cvReleaseImage (&filter->cvCEdge);
cvReleaseImage (&filter->cvGray);
cvReleaseImage (&filter->cvEdge);
}
G_OBJECT_CLASS (parent_class)->finalize (obj);
}
/* GObject vmethod implementations */
static void
gst_edgedetect_base_init (gpointer gclass)
{
GstElementClass *element_class = GST_ELEMENT_CLASS (gclass);
- gst_element_class_set_details_simple(element_class,
- "edgedetect",
- "Filter/Effect/Video",
- "Performs canny edge detection on videos and images.",
- "Michael Sheldon <mike@mikeasoft.com>");
+ gst_element_class_set_details_simple (element_class,
+ "edgedetect",
+ "Filter/Effect/Video",
+ "Performs canny edge detection on videos and images.",
+ "Michael Sheldon <mike@mikeasoft.com>");
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&src_factory));
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&sink_factory));
}
/* initialize the edgedetect's class */
static void
gst_edgedetect_class_init (GstedgedetectClass * klass)
{
GObjectClass *gobject_class;
GstElementClass *gstelement_class;
gobject_class = (GObjectClass *) klass;
gstelement_class = (GstElementClass *) klass;
parent_class = g_type_class_peek_parent (klass);
gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_edgedetect_finalize);
gobject_class->set_property = gst_edgedetect_set_property;
gobject_class->get_property = gst_edgedetect_get_property;
g_object_class_install_property (gobject_class, PROP_MASK,
- g_param_spec_boolean ("mask", "Mask", "Sets whether the detected edges should be used as a mask on the original input or not",
+ g_param_spec_boolean ("mask", "Mask",
+ "Sets whether the detected edges should be used as a mask on the original input or not",
TRUE, G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_THRESHOLD1,
- g_param_spec_int ("threshold1", "Threshold1", "Threshold value for canny edge detection",
- 0, 1000, 50, G_PARAM_READWRITE));
+ g_param_spec_int ("threshold1", "Threshold1",
+ "Threshold value for canny edge detection", 0, 1000, 50,
+ G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_THRESHOLD2,
- g_param_spec_int ("threshold2", "Threshold2", "Second threshold value for canny edge detection",
- 0, 1000, 150, G_PARAM_READWRITE));
+ g_param_spec_int ("threshold2", "Threshold2",
+ "Second threshold value for canny edge detection", 0, 1000, 150,
+ G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_APERTURE,
- g_param_spec_int ("aperture", "Aperture", "Aperture size for Sobel operator (Must be either 3, 5 or 7",
- 3, 7, 3, G_PARAM_READWRITE));
+ g_param_spec_int ("aperture", "Aperture",
+ "Aperture size for Sobel operator (Must be either 3, 5 or 7", 3, 7, 3,
+ G_PARAM_READWRITE));
}
/* initialize the new element
* instantiate pads and add them to element
* set pad calback functions
* initialize instance structure
*/
static void
-gst_edgedetect_init (Gstedgedetect * filter,
- GstedgedetectClass * gclass)
+gst_edgedetect_init (Gstedgedetect * filter, GstedgedetectClass * gclass)
{
filter->sinkpad = gst_pad_new_from_static_template (&sink_factory, "sink");
gst_pad_set_setcaps_function (filter->sinkpad,
- GST_DEBUG_FUNCPTR(gst_edgedetect_set_caps));
+ GST_DEBUG_FUNCPTR (gst_edgedetect_set_caps));
gst_pad_set_getcaps_function (filter->sinkpad,
- GST_DEBUG_FUNCPTR(gst_pad_proxy_getcaps));
+ GST_DEBUG_FUNCPTR (gst_pad_proxy_getcaps));
gst_pad_set_chain_function (filter->sinkpad,
- GST_DEBUG_FUNCPTR(gst_edgedetect_chain));
+ GST_DEBUG_FUNCPTR (gst_edgedetect_chain));
filter->srcpad = gst_pad_new_from_static_template (&src_factory, "src");
gst_pad_set_getcaps_function (filter->srcpad,
- GST_DEBUG_FUNCPTR(gst_pad_proxy_getcaps));
+ GST_DEBUG_FUNCPTR (gst_pad_proxy_getcaps));
gst_element_add_pad (GST_ELEMENT (filter), filter->sinkpad);
gst_element_add_pad (GST_ELEMENT (filter), filter->srcpad);
filter->mask = TRUE;
filter->threshold1 = 50;
filter->threshold2 = 150;
filter->aperture = 3;
}
static void
gst_edgedetect_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec)
{
Gstedgedetect *filter = GST_EDGEDETECT (object);
switch (prop_id) {
case PROP_MASK:
filter->mask = g_value_get_boolean (value);
break;
case PROP_THRESHOLD1:
filter->threshold1 = g_value_get_int (value);
break;
case PROP_THRESHOLD2:
filter->threshold2 = g_value_get_int (value);
break;
case PROP_APERTURE:
filter->aperture = g_value_get_int (value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gst_edgedetect_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec)
{
Gstedgedetect *filter = GST_EDGEDETECT (object);
switch (prop_id) {
case PROP_MASK:
g_value_set_boolean (value, filter->mask);
break;
case PROP_THRESHOLD1:
g_value_set_int (value, filter->threshold1);
break;
case PROP_THRESHOLD2:
g_value_set_int (value, filter->threshold2);
break;
case PROP_APERTURE:
g_value_set_int (value, filter->aperture);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
/* GstElement vmethod implementations */
/* this function handles the link with other elements */
static gboolean
gst_edgedetect_set_caps (GstPad * pad, GstCaps * caps)
{
Gstedgedetect *filter;
GstPad *otherpad;
gint width, height;
GstStructure *structure;
filter = GST_EDGEDETECT (gst_pad_get_parent (pad));
structure = gst_caps_get_structure (caps, 0);
gst_structure_get_int (structure, "width", &width);
gst_structure_get_int (structure, "height", &height);
- filter->cvImage = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 3);
- filter->cvCEdge = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 3);
- filter->cvGray = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 1);
- filter->cvEdge = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 1);
+ filter->cvImage = cvCreateImage (cvSize (width, height), IPL_DEPTH_8U, 3);
+ filter->cvCEdge = cvCreateImage (cvSize (width, height), IPL_DEPTH_8U, 3);
+ filter->cvGray = cvCreateImage (cvSize (width, height), IPL_DEPTH_8U, 1);
+ filter->cvEdge = cvCreateImage (cvSize (width, height), IPL_DEPTH_8U, 1);
otherpad = (pad == filter->srcpad) ? filter->sinkpad : filter->srcpad;
gst_object_unref (filter);
return gst_pad_set_caps (otherpad, caps);
}
/* chain function
* this function does the actual processing
*/
static GstFlowReturn
gst_edgedetect_chain (GstPad * pad, GstBuffer * buf)
{
Gstedgedetect *filter;
filter = GST_EDGEDETECT (GST_OBJECT_PARENT (pad));
filter->cvImage->imageData = (char *) GST_BUFFER_DATA (buf);
- cvCvtColor(filter->cvImage, filter->cvGray, CV_RGB2GRAY);
- cvSmooth(filter->cvGray, filter->cvEdge, CV_BLUR, 3, 3, 0, 0 );
- cvNot(filter->cvGray, filter->cvEdge);
- cvCanny(filter->cvGray, filter->cvEdge, filter->threshold1, filter->threshold2, filter->aperture);
+ cvCvtColor (filter->cvImage, filter->cvGray, CV_RGB2GRAY);
+ cvSmooth (filter->cvGray, filter->cvEdge, CV_BLUR, 3, 3, 0, 0);
+ cvNot (filter->cvGray, filter->cvEdge);
+ cvCanny (filter->cvGray, filter->cvEdge, filter->threshold1,
+ filter->threshold2, filter->aperture);
- cvZero(filter->cvCEdge);
- if(filter-> mask) {
- cvCopy(filter->cvImage, filter->cvCEdge, filter->cvEdge);
+ cvZero (filter->cvCEdge);
+ if (filter->mask) {
+ cvCopy (filter->cvImage, filter->cvCEdge, filter->cvEdge);
} else {
- cvCvtColor(filter->cvEdge, filter->cvCEdge, CV_GRAY2RGB);
+ cvCvtColor (filter->cvEdge, filter->cvCEdge, CV_GRAY2RGB);
}
- gst_buffer_set_data(buf, filter->cvCEdge->imageData, filter->cvCEdge->imageSize);
+ gst_buffer_set_data (buf, filter->cvCEdge->imageData,
+ filter->cvCEdge->imageSize);
return gst_pad_push (filter->srcpad, buf);
}
/* entry point to initialize the plug-in
* initialize the plug-in itself
* register the element factories and other features
*/
gboolean
gst_edgedetect_plugin_init (GstPlugin * plugin)
{
/* debug category for fltering log messages
*
* exchange the string 'Template edgedetect' with your description
*/
GST_DEBUG_CATEGORY_INIT (gst_edgedetect_debug, "edgedetect",
0, "Performs canny edge detection on videos and images");
return gst_element_register (plugin, "edgedetect", GST_RANK_NONE,
GST_TYPE_EDGEDETECT);
}
diff --git a/src/edgedetect/gstedgedetect.h b/src/edgedetect/gstedgedetect.h
index 9d17632..eaaa3c0 100644
--- a/src/edgedetect/gstedgedetect.h
+++ b/src/edgedetect/gstedgedetect.h
@@ -1,93 +1,90 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2008 Michael Sheldon <mike@mikeasoft.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#ifndef __GST_EDGEDETECT_H__
#define __GST_EDGEDETECT_H__
#include <gst/gst.h>
#include <cv.h>
G_BEGIN_DECLS
-
/* #defines don't like whitespacey bits */
#define GST_TYPE_EDGEDETECT \
(gst_edgedetect_get_type())
#define GST_EDGEDETECT(obj) \
(G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_EDGEDETECT,Gstedgedetect))
#define GST_EDGEDETECT_CLASS(klass) \
(G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_EDGEDETECT,GstedgedetectClass))
#define GST_IS_EDGEDETECT(obj) \
(G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_EDGEDETECT))
#define GST_IS_EDGEDETECT_CLASS(klass) \
(G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_EDGEDETECT))
-
-typedef struct _Gstedgedetect Gstedgedetect;
+typedef struct _Gstedgedetect Gstedgedetect;
typedef struct _GstedgedetectClass GstedgedetectClass;
struct _Gstedgedetect
{
GstElement element;
GstPad *sinkpad, *srcpad;
gboolean mask;
int threshold1, threshold2, aperture;
IplImage *cvEdge, *cvGray, *cvImage, *cvCEdge;
};
-struct _GstedgedetectClass
+struct _GstedgedetectClass
{
GstElementClass parent_class;
};
GType gst_edgedetect_get_type (void);
gboolean gst_edgedetect_plugin_init (GstPlugin * plugin);
G_END_DECLS
-
#endif /* __GST_EDGEDETECT_H__ */
diff --git a/src/faceblur/gstfaceblur.c b/src/faceblur/gstfaceblur.c
index 7a878c1..e9da8f8 100644
--- a/src/faceblur/gstfaceblur.c
+++ b/src/faceblur/gstfaceblur.c
@@ -1,313 +1,313 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2008 Michael Sheldon <mike@mikeasoft.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/**
* SECTION:element-faceblur
*
* FIXME:Describe faceblur here.
*
* <refsect2>
* <title>Example launch line</title>
* |[
* gst-launch-0.10 videotestsrc ! decodebin ! ffmpegcolorspace ! faceblur ! ffmpegcolorspace ! xvimagesink
* ]|
* </refsect2>
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <gst/gst.h>
#include "gstfaceblur.h"
GST_DEBUG_CATEGORY_STATIC (gst_faceblur_debug);
#define GST_CAT_DEFAULT gst_faceblur_debug
#define DEFAULT_PROFILE "/usr/share/opencv/haarcascades/haarcascade_frontalface_default.xml"
/* Filter signals and args */
enum
{
/* FILL ME */
LAST_SIGNAL
};
enum
{
PROP_0,
PROP_PROFILE
};
/* the capabilities of the inputs and outputs.
*/
static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
GST_PAD_SINK,
GST_PAD_ALWAYS,
- GST_STATIC_CAPS (
- "video/x-raw-rgb"
- )
-);
+ GST_STATIC_CAPS ("video/x-raw-rgb")
+ );
static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
GST_PAD_SRC,
GST_PAD_ALWAYS,
- GST_STATIC_CAPS (
- "video/x-raw-rgb"
- )
-);
+ GST_STATIC_CAPS ("video/x-raw-rgb")
+ );
-GST_BOILERPLATE (Gstfaceblur, gst_faceblur, GstElement,
- GST_TYPE_ELEMENT);
+GST_BOILERPLATE (Gstfaceblur, gst_faceblur, GstElement, GST_TYPE_ELEMENT);
static void gst_faceblur_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec);
static void gst_faceblur_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec);
static gboolean gst_faceblur_set_caps (GstPad * pad, GstCaps * caps);
static GstFlowReturn gst_faceblur_chain (GstPad * pad, GstBuffer * buf);
static void gst_faceblur_load_profile (Gstfaceblur * filter);
/* Clean up */
static void
gst_faceblur_finalize (GObject * obj)
{
- Gstfaceblur *filter = GST_FACEBLUR(obj);
+ Gstfaceblur *filter = GST_FACEBLUR (obj);
- if (filter->cvImage)
- {
+ if (filter->cvImage) {
cvReleaseImage (&filter->cvImage);
cvReleaseImage (&filter->cvGray);
}
G_OBJECT_CLASS (parent_class)->finalize (obj);
}
/* GObject vmethod implementations */
static void
gst_faceblur_base_init (gpointer gclass)
{
GstElementClass *element_class = GST_ELEMENT_CLASS (gclass);
- gst_element_class_set_details_simple(element_class,
- "faceblur",
- "Filter/Effect/Video",
- "Blurs faces in images and videos",
- "Michael Sheldon <mike@mikeasoft.com>");
+ gst_element_class_set_details_simple (element_class,
+ "faceblur",
+ "Filter/Effect/Video",
+ "Blurs faces in images and videos",
+ "Michael Sheldon <mike@mikeasoft.com>");
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&src_factory));
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&sink_factory));
}
/* initialize the faceblur's class */
static void
gst_faceblur_class_init (GstfaceblurClass * klass)
{
GObjectClass *gobject_class;
GstElementClass *gstelement_class;
gobject_class = (GObjectClass *) klass;
gstelement_class = (GstElementClass *) klass;
parent_class = g_type_class_peek_parent (klass);
gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_faceblur_finalize);
gobject_class->set_property = gst_faceblur_set_property;
gobject_class->get_property = gst_faceblur_get_property;
g_object_class_install_property (gobject_class, PROP_PROFILE,
- g_param_spec_string ("profile", "Profile", "Location of Haar cascade file to use for face blurion",
+ g_param_spec_string ("profile", "Profile",
+ "Location of Haar cascade file to use for face blurion",
DEFAULT_PROFILE, G_PARAM_READWRITE));
}
/* initialize the new element
* instantiate pads and add them to element
* set pad calback functions
* initialize instance structure
*/
static void
-gst_faceblur_init (Gstfaceblur * filter,
- GstfaceblurClass * gclass)
+gst_faceblur_init (Gstfaceblur * filter, GstfaceblurClass * gclass)
{
filter->sinkpad = gst_pad_new_from_static_template (&sink_factory, "sink");
gst_pad_set_setcaps_function (filter->sinkpad,
- GST_DEBUG_FUNCPTR(gst_faceblur_set_caps));
+ GST_DEBUG_FUNCPTR (gst_faceblur_set_caps));
gst_pad_set_getcaps_function (filter->sinkpad,
- GST_DEBUG_FUNCPTR(gst_pad_proxy_getcaps));
+ GST_DEBUG_FUNCPTR (gst_pad_proxy_getcaps));
gst_pad_set_chain_function (filter->sinkpad,
- GST_DEBUG_FUNCPTR(gst_faceblur_chain));
+ GST_DEBUG_FUNCPTR (gst_faceblur_chain));
filter->srcpad = gst_pad_new_from_static_template (&src_factory, "src");
gst_pad_set_getcaps_function (filter->srcpad,
- GST_DEBUG_FUNCPTR(gst_pad_proxy_getcaps));
+ GST_DEBUG_FUNCPTR (gst_pad_proxy_getcaps));
gst_element_add_pad (GST_ELEMENT (filter), filter->sinkpad);
gst_element_add_pad (GST_ELEMENT (filter), filter->srcpad);
filter->profile = DEFAULT_PROFILE;
- gst_faceblur_load_profile(filter);
+ gst_faceblur_load_profile (filter);
}
static void
gst_faceblur_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec)
{
Gstfaceblur *filter = GST_FACEBLUR (object);
switch (prop_id) {
case PROP_PROFILE:
filter->profile = g_value_dup_string (value);
- gst_faceblur_load_profile(filter);
+ gst_faceblur_load_profile (filter);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gst_faceblur_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec)
{
Gstfaceblur *filter = GST_FACEBLUR (object);
switch (prop_id) {
case PROP_PROFILE:
g_value_take_string (value, filter->profile);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
/* GstElement vmethod implementations */
/* this function handles the link with other elements */
static gboolean
gst_faceblur_set_caps (GstPad * pad, GstCaps * caps)
{
Gstfaceblur *filter;
GstPad *otherpad;
gint width, height;
GstStructure *structure;
filter = GST_FACEBLUR (gst_pad_get_parent (pad));
structure = gst_caps_get_structure (caps, 0);
gst_structure_get_int (structure, "width", &width);
gst_structure_get_int (structure, "height", &height);
- filter->cvImage = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 3);
- filter->cvGray = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 1);
- filter->cvStorage = cvCreateMemStorage(0);
+ filter->cvImage = cvCreateImage (cvSize (width, height), IPL_DEPTH_8U, 3);
+ filter->cvGray = cvCreateImage (cvSize (width, height), IPL_DEPTH_8U, 1);
+ filter->cvStorage = cvCreateMemStorage (0);
otherpad = (pad == filter->srcpad) ? filter->sinkpad : filter->srcpad;
gst_object_unref (filter);
return gst_pad_set_caps (otherpad, caps);
}
/* chain function
* this function does the actual processing
*/
static GstFlowReturn
gst_faceblur_chain (GstPad * pad, GstBuffer * buf)
{
Gstfaceblur *filter;
CvSeq *faces;
int i;
filter = GST_FACEBLUR (GST_OBJECT_PARENT (pad));
filter->cvImage->imageData = (char *) GST_BUFFER_DATA (buf);
- cvCvtColor(filter->cvImage, filter->cvGray, CV_RGB2GRAY);
- cvClearMemStorage(filter->cvStorage);
+ cvCvtColor (filter->cvImage, filter->cvGray, CV_RGB2GRAY);
+ cvClearMemStorage (filter->cvStorage);
if (filter->cvCascade) {
- faces = cvHaarDetectObjects(filter->cvGray, filter->cvCascade, filter->cvStorage, 1.1, 2, 0, cvSize(30, 30));
-
- for (i = 0; i < (faces ? faces->total : 0); i++) {
- CvRect* r = (CvRect *) cvGetSeqElem(faces, i);
- cvSetImageROI(filter->cvImage, *r);
- cvSmooth(filter->cvImage, filter->cvImage, CV_BLUR, 11, 11, 0, 0);
- cvSmooth(filter->cvImage, filter->cvImage, CV_GAUSSIAN, 11, 11, 0, 0);
- cvResetImageROI(filter->cvImage);
+ faces =
+ cvHaarDetectObjects (filter->cvGray, filter->cvCascade,
+ filter->cvStorage, 1.1, 2, 0, cvSize (30, 30));
+
+ for (i = 0; i < (faces ? faces->total : 0); i++) {
+ CvRect *r = (CvRect *) cvGetSeqElem (faces, i);
+ cvSetImageROI (filter->cvImage, *r);
+ cvSmooth (filter->cvImage, filter->cvImage, CV_BLUR, 11, 11, 0, 0);
+ cvSmooth (filter->cvImage, filter->cvImage, CV_GAUSSIAN, 11, 11, 0, 0);
+ cvResetImageROI (filter->cvImage);
}
}
- gst_buffer_set_data(buf, filter->cvImage->imageData, filter->cvImage->imageSize);
+ gst_buffer_set_data (buf, filter->cvImage->imageData,
+ filter->cvImage->imageSize);
return gst_pad_push (filter->srcpad, buf);
}
-static void gst_faceblur_load_profile(Gstfaceblur * filter) {
- filter->cvCascade = (CvHaarClassifierCascade*)cvLoad(filter->profile, 0, 0, 0 );
+static void
+gst_faceblur_load_profile (Gstfaceblur * filter)
+{
+ filter->cvCascade =
+ (CvHaarClassifierCascade *) cvLoad (filter->profile, 0, 0, 0);
if (!filter->cvCascade) {
GST_WARNING ("Couldn't load Haar classifier cascade: %s.", filter->profile);
}
}
/* entry point to initialize the plug-in
* initialize the plug-in itself
* register the element factories and other features
*/
gboolean
gst_faceblur_plugin_init (GstPlugin * plugin)
{
/* debug category for filtering log messages */
GST_DEBUG_CATEGORY_INIT (gst_faceblur_debug, "faceblur",
0, "Blurs faces in images and videos");
return gst_element_register (plugin, "faceblur", GST_RANK_NONE,
GST_TYPE_FACEBLUR);
}
diff --git a/src/faceblur/gstfaceblur.h b/src/faceblur/gstfaceblur.h
index 57d2c4c..34ea09a 100644
--- a/src/faceblur/gstfaceblur.h
+++ b/src/faceblur/gstfaceblur.h
@@ -1,95 +1,92 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2008 Michael Sheldon <mike@mikeasoft.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#ifndef __GST_FACEBLUR_H__
#define __GST_FACEBLUR_H__
#include <gst/gst.h>
#include <cv.h>
G_BEGIN_DECLS
-
/* #defines don't like whitespacey bits */
#define GST_TYPE_FACEBLUR \
(gst_faceblur_get_type())
#define GST_FACEBLUR(obj) \
(G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_FACEBLUR,Gstfaceblur))
#define GST_FACEBLUR_CLASS(klass) \
(G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_FACEBLUR,GstfaceblurClass))
#define GST_IS_FACEBLUR(obj) \
(G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_FACEBLUR))
#define GST_IS_FACEBLUR_CLASS(klass) \
(G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_FACEBLUR))
-
-typedef struct _Gstfaceblur Gstfaceblur;
+typedef struct _Gstfaceblur Gstfaceblur;
typedef struct _GstfaceblurClass GstfaceblurClass;
struct _Gstfaceblur
{
GstElement element;
GstPad *sinkpad, *srcpad;
gboolean display;
gchar *profile;
IplImage *cvImage, *cvGray;
CvHaarClassifierCascade *cvCascade;
CvMemStorage *cvStorage;
};
-struct _GstfaceblurClass
+struct _GstfaceblurClass
{
GstElementClass parent_class;
};
GType gst_faceblur_get_type (void);
gboolean gst_faceblur_plugin_init (GstPlugin * plugin);
G_END_DECLS
-
#endif /* __GST_FACEBLUR_H__ */
diff --git a/src/facedetect/gstfacedetect.c b/src/facedetect/gstfacedetect.c
index 03d29b1..70e717f 100644
--- a/src/facedetect/gstfacedetect.c
+++ b/src/facedetect/gstfacedetect.c
@@ -1,339 +1,342 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2008 Michael Sheldon <mike@mikeasoft.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/**
* SECTION:element-facedetect
*
* FIXME:Describe facedetect here.
*
* <refsect2>
* <title>Example launch line</title>
* |[
* gst-launch-0.10 videotestsrc ! decodebin ! ffmpegcolorspace ! facedetect ! ffmpegcolorspace ! xvimagesink
* ]|
* </refsect2>
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <gst/gst.h>
#include "gstfacedetect.h"
GST_DEBUG_CATEGORY_STATIC (gst_facedetect_debug);
#define GST_CAT_DEFAULT gst_facedetect_debug
#define DEFAULT_PROFILE "/usr/share/opencv/haarcascades/haarcascade_frontalface_default.xml"
/* Filter signals and args */
enum
{
/* FILL ME */
LAST_SIGNAL
};
enum
{
PROP_0,
PROP_DISPLAY,
PROP_PROFILE
};
/* the capabilities of the inputs and outputs.
*/
static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
GST_PAD_SINK,
GST_PAD_ALWAYS,
- GST_STATIC_CAPS (
- "video/x-raw-rgb"
- )
-);
+ GST_STATIC_CAPS ("video/x-raw-rgb")
+ );
static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
GST_PAD_SRC,
GST_PAD_ALWAYS,
- GST_STATIC_CAPS (
- "video/x-raw-rgb"
- )
-);
+ GST_STATIC_CAPS ("video/x-raw-rgb")
+ );
-GST_BOILERPLATE (Gstfacedetect, gst_facedetect, GstElement,
- GST_TYPE_ELEMENT);
+GST_BOILERPLATE (Gstfacedetect, gst_facedetect, GstElement, GST_TYPE_ELEMENT);
static void gst_facedetect_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec);
static void gst_facedetect_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec);
static gboolean gst_facedetect_set_caps (GstPad * pad, GstCaps * caps);
static GstFlowReturn gst_facedetect_chain (GstPad * pad, GstBuffer * buf);
static void gst_facedetect_load_profile (Gstfacedetect * filter);
/* Clean up */
static void
gst_facedetect_finalize (GObject * obj)
{
- Gstfacedetect *filter = GST_FACEDETECT(obj);
+ Gstfacedetect *filter = GST_FACEDETECT (obj);
- if (filter->cvImage)
- {
+ if (filter->cvImage) {
cvReleaseImage (&filter->cvImage);
cvReleaseImage (&filter->cvGray);
}
G_OBJECT_CLASS (parent_class)->finalize (obj);
}
/* GObject vmethod implementations */
static void
gst_facedetect_base_init (gpointer gclass)
{
GstElementClass *element_class = GST_ELEMENT_CLASS (gclass);
- gst_element_class_set_details_simple(element_class,
- "facedetect",
- "Filter/Effect/Video",
- "Performs face detection on videos and images, providing detected positions via bus messages",
- "Michael Sheldon <mike@mikeasoft.com>");
+ gst_element_class_set_details_simple (element_class,
+ "facedetect",
+ "Filter/Effect/Video",
+ "Performs face detection on videos and images, providing detected positions via bus messages",
+ "Michael Sheldon <mike@mikeasoft.com>");
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&src_factory));
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&sink_factory));
}
/* initialize the facedetect's class */
static void
gst_facedetect_class_init (GstfacedetectClass * klass)
{
GObjectClass *gobject_class;
GstElementClass *gstelement_class;
gobject_class = (GObjectClass *) klass;
gstelement_class = (GstElementClass *) klass;
parent_class = g_type_class_peek_parent (klass);
gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_facedetect_finalize);
gobject_class->set_property = gst_facedetect_set_property;
gobject_class->get_property = gst_facedetect_get_property;
g_object_class_install_property (gobject_class, PROP_DISPLAY,
- g_param_spec_boolean ("display", "Display", "Sets whether the detected faces should be highlighted in the output",
+ g_param_spec_boolean ("display", "Display",
+ "Sets whether the detected faces should be highlighted in the output",
TRUE, G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_PROFILE,
- g_param_spec_string ("profile", "Profile", "Location of Haar cascade file to use for face detection",
+ g_param_spec_string ("profile", "Profile",
+ "Location of Haar cascade file to use for face detection",
DEFAULT_PROFILE, G_PARAM_READWRITE));
}
/* initialize the new element
* instantiate pads and add them to element
* set pad calback functions
* initialize instance structure
*/
static void
-gst_facedetect_init (Gstfacedetect * filter,
- GstfacedetectClass * gclass)
+gst_facedetect_init (Gstfacedetect * filter, GstfacedetectClass * gclass)
{
filter->sinkpad = gst_pad_new_from_static_template (&sink_factory, "sink");
gst_pad_set_setcaps_function (filter->sinkpad,
- GST_DEBUG_FUNCPTR(gst_facedetect_set_caps));
+ GST_DEBUG_FUNCPTR (gst_facedetect_set_caps));
gst_pad_set_getcaps_function (filter->sinkpad,
- GST_DEBUG_FUNCPTR(gst_pad_proxy_getcaps));
+ GST_DEBUG_FUNCPTR (gst_pad_proxy_getcaps));
gst_pad_set_chain_function (filter->sinkpad,
- GST_DEBUG_FUNCPTR(gst_facedetect_chain));
+ GST_DEBUG_FUNCPTR (gst_facedetect_chain));
filter->srcpad = gst_pad_new_from_static_template (&src_factory, "src");
gst_pad_set_getcaps_function (filter->srcpad,
- GST_DEBUG_FUNCPTR(gst_pad_proxy_getcaps));
+ GST_DEBUG_FUNCPTR (gst_pad_proxy_getcaps));
gst_element_add_pad (GST_ELEMENT (filter), filter->sinkpad);
gst_element_add_pad (GST_ELEMENT (filter), filter->srcpad);
filter->profile = DEFAULT_PROFILE;
filter->display = TRUE;
- gst_facedetect_load_profile(filter);
+ gst_facedetect_load_profile (filter);
}
static void
gst_facedetect_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec)
{
Gstfacedetect *filter = GST_FACEDETECT (object);
switch (prop_id) {
case PROP_PROFILE:
filter->profile = g_value_dup_string (value);
- gst_facedetect_load_profile(filter);
+ gst_facedetect_load_profile (filter);
break;
case PROP_DISPLAY:
filter->display = g_value_get_boolean (value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gst_facedetect_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec)
{
Gstfacedetect *filter = GST_FACEDETECT (object);
switch (prop_id) {
case PROP_PROFILE:
g_value_take_string (value, filter->profile);
break;
case PROP_DISPLAY:
g_value_set_boolean (value, filter->display);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
/* GstElement vmethod implementations */
/* this function handles the link with other elements */
static gboolean
gst_facedetect_set_caps (GstPad * pad, GstCaps * caps)
{
Gstfacedetect *filter;
GstPad *otherpad;
gint width, height;
GstStructure *structure;
filter = GST_FACEDETECT (gst_pad_get_parent (pad));
structure = gst_caps_get_structure (caps, 0);
gst_structure_get_int (structure, "width", &width);
gst_structure_get_int (structure, "height", &height);
- filter->cvImage = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 3);
- filter->cvGray = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 1);
- filter->cvStorage = cvCreateMemStorage(0);
+ filter->cvImage = cvCreateImage (cvSize (width, height), IPL_DEPTH_8U, 3);
+ filter->cvGray = cvCreateImage (cvSize (width, height), IPL_DEPTH_8U, 1);
+ filter->cvStorage = cvCreateMemStorage (0);
otherpad = (pad == filter->srcpad) ? filter->sinkpad : filter->srcpad;
gst_object_unref (filter);
return gst_pad_set_caps (otherpad, caps);
}
/* chain function
* this function does the actual processing
*/
static GstFlowReturn
gst_facedetect_chain (GstPad * pad, GstBuffer * buf)
{
Gstfacedetect *filter;
CvSeq *faces;
int i;
filter = GST_FACEDETECT (GST_OBJECT_PARENT (pad));
filter->cvImage->imageData = (char *) GST_BUFFER_DATA (buf);
- cvCvtColor(filter->cvImage, filter->cvGray, CV_RGB2GRAY);
- cvClearMemStorage(filter->cvStorage);
+ cvCvtColor (filter->cvImage, filter->cvGray, CV_RGB2GRAY);
+ cvClearMemStorage (filter->cvStorage);
if (filter->cvCascade) {
- faces = cvHaarDetectObjects(filter->cvGray, filter->cvCascade, filter->cvStorage, 1.1, 2, 0, cvSize(30, 30));
-
- for (i = 0; i < (faces ? faces->total : 0); i++) {
- CvRect* r = (CvRect *) cvGetSeqElem(faces, i);
+ faces =
+ cvHaarDetectObjects (filter->cvGray, filter->cvCascade,
+ filter->cvStorage, 1.1, 2, 0, cvSize (30, 30));
+
+ for (i = 0; i < (faces ? faces->total : 0); i++) {
+ CvRect *r = (CvRect *) cvGetSeqElem (faces, i);
GstStructure *s = gst_structure_new ("face",
- "x", G_TYPE_UINT, r->x,
- "y", G_TYPE_UINT, r->y,
- "width", G_TYPE_UINT, r->width,
- "height", G_TYPE_UINT, r->height, NULL);
+ "x", G_TYPE_UINT, r->x,
+ "y", G_TYPE_UINT, r->y,
+ "width", G_TYPE_UINT, r->width,
+ "height", G_TYPE_UINT, r->height, NULL);
GstMessage *m = gst_message_new_element (GST_OBJECT (filter), s);
gst_element_post_message (GST_ELEMENT (filter), m);
if (filter->display) {
CvPoint center;
int radius;
- center.x = cvRound((r->x + r->width*0.5));
- center.y = cvRound((r->y + r->height*0.5));
- radius = cvRound((r->width + r->height)*0.25);
- cvCircle(filter->cvImage, center, radius, CV_RGB(255, 32, 32), 3, 8, 0);
+ center.x = cvRound ((r->x + r->width * 0.5));
+ center.y = cvRound ((r->y + r->height * 0.5));
+ radius = cvRound ((r->width + r->height) * 0.25);
+ cvCircle (filter->cvImage, center, radius, CV_RGB (255, 32, 32), 3, 8,
+ 0);
}
-
+
}
}
- gst_buffer_set_data(buf, filter->cvImage->imageData, filter->cvImage->imageSize);
+ gst_buffer_set_data (buf, filter->cvImage->imageData,
+ filter->cvImage->imageSize);
return gst_pad_push (filter->srcpad, buf);
}
-static void gst_facedetect_load_profile(Gstfacedetect * filter) {
- filter->cvCascade = (CvHaarClassifierCascade*)cvLoad(filter->profile, 0, 0, 0 );
+static void
+gst_facedetect_load_profile (Gstfacedetect * filter)
+{
+ filter->cvCascade =
+ (CvHaarClassifierCascade *) cvLoad (filter->profile, 0, 0, 0);
if (!filter->cvCascade) {
GST_WARNING ("Couldn't load Haar classifier cascade: %s.", filter->profile);
}
}
/* entry point to initialize the plug-in
* initialize the plug-in itself
* register the element factories and other features
*/
gboolean
gst_facedetect_plugin_init (GstPlugin * plugin)
{
/* debug category for fltering log messages */
GST_DEBUG_CATEGORY_INIT (gst_facedetect_debug, "facedetect",
- 0, "Performs face detection on videos and images, providing detected positions via bus messages");
+ 0,
+ "Performs face detection on videos and images, providing detected positions via bus messages");
return gst_element_register (plugin, "facedetect", GST_RANK_NONE,
GST_TYPE_FACEDETECT);
}
diff --git a/src/facedetect/gstfacedetect.h b/src/facedetect/gstfacedetect.h
index 6ca56a7..cacefef 100644
--- a/src/facedetect/gstfacedetect.h
+++ b/src/facedetect/gstfacedetect.h
@@ -1,95 +1,92 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2008 Michael Sheldon <mike@mikeasoft.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#ifndef __GST_FACEDETECT_H__
#define __GST_FACEDETECT_H__
#include <gst/gst.h>
#include <cv.h>
G_BEGIN_DECLS
-
/* #defines don't like whitespacey bits */
#define GST_TYPE_FACEDETECT \
(gst_facedetect_get_type())
#define GST_FACEDETECT(obj) \
(G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_FACEDETECT,Gstfacedetect))
#define GST_FACEDETECT_CLASS(klass) \
(G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_FACEDETECT,GstfacedetectClass))
#define GST_IS_FACEDETECT(obj) \
(G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_FACEDETECT))
#define GST_IS_FACEDETECT_CLASS(klass) \
(G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_FACEDETECT))
-
-typedef struct _Gstfacedetect Gstfacedetect;
+typedef struct _Gstfacedetect Gstfacedetect;
typedef struct _GstfacedetectClass GstfacedetectClass;
struct _Gstfacedetect
{
GstElement element;
GstPad *sinkpad, *srcpad;
gboolean display;
gchar *profile;
IplImage *cvImage, *cvGray;
CvHaarClassifierCascade *cvCascade;
CvMemStorage *cvStorage;
};
-struct _GstfacedetectClass
+struct _GstfacedetectClass
{
GstElementClass parent_class;
};
GType gst_facedetect_get_type (void);
gboolean gst_facedetect_plugin_init (GstPlugin * plugin);
G_END_DECLS
-
#endif /* __GST_FACEDETECT_H__ */
diff --git a/src/gstopencv.c b/src/gstopencv.c
index be81894..f08fdb1 100644
--- a/src/gstopencv.c
+++ b/src/gstopencv.c
@@ -1,58 +1,58 @@
/* GStreamer
* Copyright (C) <2009> Kapil Agrawal <kapil@mediamagictechnologies.com>
*
* gstopencv.c: plugin registering
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "gstedgedetect.h"
#include "gstfaceblur.h"
#include "gstfacedetect.h"
#include "gstpyramidsegment.h"
#include "gsttemplatematch.h"
static gboolean
plugin_init (GstPlugin * plugin)
{
if (!gst_edgedetect_plugin_init (plugin))
return FALSE;
- if (!gst_faceblur_plugin_init(plugin))
+ if (!gst_faceblur_plugin_init (plugin))
return FALSE;
if (!gst_facedetect_plugin_init (plugin))
return FALSE;
-
+
if (!gst_pyramidsegment_plugin_init (plugin))
return FALSE;
if (!gst_templatematch_plugin_init (plugin))
return FALSE;
-
+
return TRUE;
}
GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
GST_VERSION_MINOR,
"opencv",
"GStreamer OpenCV Plugins",
plugin_init, VERSION, "LGPL", "OpenCv", "http://opencv.willowgarage.com")
diff --git a/src/pyramidsegment/gstpyramidsegment.c b/src/pyramidsegment/gstpyramidsegment.c
index 77afa0f..e57a703 100644
--- a/src/pyramidsegment/gstpyramidsegment.c
+++ b/src/pyramidsegment/gstpyramidsegment.c
@@ -1,320 +1,325 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2008 Michael Sheldon <mike@mikeasoft.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/**
* SECTION:element-pyramidsegment
*
* FIXME:Describe pyramidsegment here.
*
* <refsect2>
* <title>Example launch line</title>
* |[
* gst-launch -v -m fakesrc ! pyramidsegment ! fakesink silent=TRUE
* ]|
* </refsect2>
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <gst/gst.h>
#include "gstpyramidsegment.h"
#define BLOCK_SIZE 1000
GST_DEBUG_CATEGORY_STATIC (gst_pyramidsegment_debug);
#define GST_CAT_DEFAULT gst_pyramidsegment_debug
/* Filter signals and args */
enum
{
/* FILL ME */
LAST_SIGNAL
};
enum
{
PROP_0,
PROP_SILENT,
PROP_THRESHOLD1,
PROP_THRESHOLD2,
PROP_LEVEL
};
/* the capabilities of the inputs and outputs.
*
* describe the real formats here.
*/
static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
GST_PAD_SINK,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("video/x-raw-rgb")
);
static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
GST_PAD_SRC,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("video/x-raw-rgb")
);
GST_BOILERPLATE (Gstpyramidsegment, gst_pyramidsegment, GstElement,
GST_TYPE_ELEMENT);
static void gst_pyramidsegment_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec);
static void gst_pyramidsegment_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec);
static gboolean gst_pyramidsegment_set_caps (GstPad * pad, GstCaps * caps);
static GstFlowReturn gst_pyramidsegment_chain (GstPad * pad, GstBuffer * buf);
/* Clean up */
static void
-gst_pyramidsegment_finalize (GObject * obj)
+gst_pyramidsegment_finalize (GObject * obj)
{
- Gstpyramidsegment *filter = GST_PYRAMIDSEGMENT(obj);
+ Gstpyramidsegment *filter = GST_PYRAMIDSEGMENT (obj);
- if (filter->cvImage != NULL)
- {
+ if (filter->cvImage != NULL) {
cvReleaseImage (&filter->cvImage);
cvReleaseImage (&filter->cvSegmentedImage);
}
G_OBJECT_CLASS (parent_class)->finalize (obj);
}
/* GObject vmethod implementations */
static void
gst_pyramidsegment_base_init (gpointer gclass)
{
GstElementClass *element_class = GST_ELEMENT_CLASS (gclass);
- gst_element_class_set_details_simple(element_class,
- "pyramidsegment",
- "Filter/Effect/Video",
- "Applies pyramid segmentation to a video or image.",
- "Michael Sheldon <mike@mikeasoft.com>");
+ gst_element_class_set_details_simple (element_class,
+ "pyramidsegment",
+ "Filter/Effect/Video",
+ "Applies pyramid segmentation to a video or image.",
+ "Michael Sheldon <mike@mikeasoft.com>");
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&src_factory));
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&sink_factory));
}
/* initialize the pyramidsegment's class */
static void
gst_pyramidsegment_class_init (GstpyramidsegmentClass * klass)
{
GObjectClass *gobject_class;
GstElementClass *gstelement_class;
gobject_class = (GObjectClass *) klass;
gstelement_class = (GstElementClass *) klass;
parent_class = g_type_class_peek_parent (klass);
gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_pyramidsegment_finalize);
gobject_class->set_property = gst_pyramidsegment_set_property;
gobject_class->get_property = gst_pyramidsegment_get_property;
g_object_class_install_property (gobject_class, PROP_SILENT,
g_param_spec_boolean ("silent", "Silent", "Produce verbose output ?",
FALSE, G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_THRESHOLD1,
- g_param_spec_double ("threshold1", "Threshold1", "Error threshold for establishing links",
- 0, 1000, 50, G_PARAM_READWRITE));
+ g_param_spec_double ("threshold1", "Threshold1",
+ "Error threshold for establishing links", 0, 1000, 50,
+ G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_THRESHOLD2,
- g_param_spec_double ("threshold2", "Threshold2", "Error threshold for segment clustering",
- 0, 1000, 60, G_PARAM_READWRITE));
+ g_param_spec_double ("threshold2", "Threshold2",
+ "Error threshold for segment clustering", 0, 1000, 60,
+ G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_LEVEL,
- g_param_spec_int ("level", "Level", "Maximum level of the pyramid segmentation",
- 0, 4, 4, G_PARAM_READWRITE));
+ g_param_spec_int ("level", "Level",
+ "Maximum level of the pyramid segmentation", 0, 4, 4,
+ G_PARAM_READWRITE));
}
/* initialize the new element
* instantiate pads and add them to element
* set pad calback functions
* initialize instance structure
*/
static void
gst_pyramidsegment_init (Gstpyramidsegment * filter,
GstpyramidsegmentClass * gclass)
{
filter->sinkpad = gst_pad_new_from_static_template (&sink_factory, "sink");
gst_pad_set_setcaps_function (filter->sinkpad,
- GST_DEBUG_FUNCPTR(gst_pyramidsegment_set_caps));
+ GST_DEBUG_FUNCPTR (gst_pyramidsegment_set_caps));
gst_pad_set_getcaps_function (filter->sinkpad,
- GST_DEBUG_FUNCPTR(gst_pad_proxy_getcaps));
+ GST_DEBUG_FUNCPTR (gst_pad_proxy_getcaps));
gst_pad_set_chain_function (filter->sinkpad,
- GST_DEBUG_FUNCPTR(gst_pyramidsegment_chain));
+ GST_DEBUG_FUNCPTR (gst_pyramidsegment_chain));
filter->srcpad = gst_pad_new_from_static_template (&src_factory, "src");
gst_pad_set_getcaps_function (filter->srcpad,
- GST_DEBUG_FUNCPTR(gst_pad_proxy_getcaps));
+ GST_DEBUG_FUNCPTR (gst_pad_proxy_getcaps));
gst_element_add_pad (GST_ELEMENT (filter), filter->sinkpad);
gst_element_add_pad (GST_ELEMENT (filter), filter->srcpad);
- filter->storage = cvCreateMemStorage ( BLOCK_SIZE );
- filter->comp = cvCreateSeq(0, sizeof(CvSeq), sizeof(CvPoint), filter->storage);
+ filter->storage = cvCreateMemStorage (BLOCK_SIZE);
+ filter->comp =
+ cvCreateSeq (0, sizeof (CvSeq), sizeof (CvPoint), filter->storage);
filter->silent = FALSE;
filter->threshold1 = 50.0;
filter->threshold2 = 60.0;
filter->level = 4;
}
static void
gst_pyramidsegment_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec)
{
Gstpyramidsegment *filter = GST_PYRAMIDSEGMENT (object);
switch (prop_id) {
case PROP_SILENT:
filter->silent = g_value_get_boolean (value);
break;
case PROP_THRESHOLD1:
filter->threshold1 = g_value_get_double (value);
break;
case PROP_THRESHOLD2:
filter->threshold2 = g_value_get_double (value);
break;
case PROP_LEVEL:
filter->level = g_value_get_int (value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gst_pyramidsegment_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec)
{
Gstpyramidsegment *filter = GST_PYRAMIDSEGMENT (object);
switch (prop_id) {
case PROP_SILENT:
g_value_set_boolean (value, filter->silent);
break;
case PROP_THRESHOLD1:
g_value_set_double (value, filter->threshold1);
break;
case PROP_THRESHOLD2:
g_value_set_double (value, filter->threshold2);
break;
case PROP_LEVEL:
g_value_set_int (value, filter->level);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
/* GstElement vmethod implementations */
/* this function handles the link with other elements */
static gboolean
gst_pyramidsegment_set_caps (GstPad * pad, GstCaps * caps)
{
Gstpyramidsegment *filter;
GstPad *otherpad;
GstStructure *structure;
gint width, height;
filter = GST_PYRAMIDSEGMENT (gst_pad_get_parent (pad));
structure = gst_caps_get_structure (caps, 0);
gst_structure_get_int (structure, "width", &width);
gst_structure_get_int (structure, "height", &height);
-
- filter->cvImage = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 3);
+
+ filter->cvImage = cvCreateImage (cvSize (width, height), IPL_DEPTH_8U, 3);
otherpad = (pad == filter->srcpad) ? filter->sinkpad : filter->srcpad;
gst_object_unref (filter);
return gst_pad_set_caps (otherpad, caps);
}
/* chain function
* this function does the actual processing
*/
static GstFlowReturn
gst_pyramidsegment_chain (GstPad * pad, GstBuffer * buf)
{
Gstpyramidsegment *filter;
filter = GST_PYRAMIDSEGMENT (GST_OBJECT_PARENT (pad));
filter->cvImage->imageData = (char *) GST_BUFFER_DATA (buf);
- filter->cvSegmentedImage = cvCloneImage(filter->cvImage);
+ filter->cvSegmentedImage = cvCloneImage (filter->cvImage);
- cvPyrSegmentation(filter->cvImage, filter->cvSegmentedImage, filter->storage, &(filter->comp), filter->level, filter->threshold1, filter->threshold2);
+ cvPyrSegmentation (filter->cvImage, filter->cvSegmentedImage, filter->storage,
+ &(filter->comp), filter->level, filter->threshold1, filter->threshold2);
- gst_buffer_set_data(buf, filter->cvSegmentedImage->imageData, filter->cvSegmentedImage->imageSize);
+ gst_buffer_set_data (buf, filter->cvSegmentedImage->imageData,
+ filter->cvSegmentedImage->imageSize);
return gst_pad_push (filter->srcpad, buf);
}
/* entry point to initialize the plug-in
* initialize the plug-in itself
* register the element factories and other features
*/
gboolean
gst_pyramidsegment_plugin_init (GstPlugin * plugin)
{
/* debug category for fltering log messages */
GST_DEBUG_CATEGORY_INIT (gst_pyramidsegment_debug, "pyramidsegment",
0, "Applies pyramid segmentation to a video or image");
return gst_element_register (plugin, "pyramidsegment", GST_RANK_NONE,
GST_TYPE_PYRAMIDSEGMENT);
}
diff --git a/src/pyramidsegment/gstpyramidsegment.h b/src/pyramidsegment/gstpyramidsegment.h
index 5a04d81..3437073 100644
--- a/src/pyramidsegment/gstpyramidsegment.h
+++ b/src/pyramidsegment/gstpyramidsegment.h
@@ -1,99 +1,96 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2008 Michael Sheldon <mike@mikeasoft.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#ifndef __GST_PYRAMIDSEGMENT_H__
#define __GST_PYRAMIDSEGMENT_H__
#include <gst/gst.h>
#include <cv.h>
G_BEGIN_DECLS
-
/* #defines don't like whitespacey bits */
#define GST_TYPE_PYRAMIDSEGMENT \
(gst_pyramidsegment_get_type())
#define GST_PYRAMIDSEGMENT(obj) \
(G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_PYRAMIDSEGMENT,Gstpyramidsegment))
#define GST_PYRAMIDSEGMENT_CLASS(klass) \
(G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_PYRAMIDSEGMENT,GstpyramidsegmentClass))
#define GST_IS_PYRAMIDSEGMENT(obj) \
(G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_PYRAMIDSEGMENT))
#define GST_IS_PYRAMIDSEGMENT_CLASS(klass) \
(G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_PYRAMIDSEGMENT))
-
-typedef struct _Gstpyramidsegment Gstpyramidsegment;
+typedef struct _Gstpyramidsegment Gstpyramidsegment;
typedef struct _GstpyramidsegmentClass GstpyramidsegmentClass;
struct _Gstpyramidsegment
{
GstElement element;
GstPad *sinkpad, *srcpad;
gboolean silent;
IplImage *cvImage, *cvSegmentedImage;
CvMemStorage *storage;
CvSeq *comp;
double threshold1, threshold2;
-
+
int level;
};
-struct _GstpyramidsegmentClass
+struct _GstpyramidsegmentClass
{
GstElementClass parent_class;
};
GType gst_pyramidsegment_get_type (void);
gboolean gst_pyramidsegment_plugin_init (GstPlugin * plugin);
G_END_DECLS
-
#endif /* __GST_PYRAMIDSEGMENT_H__ */
diff --git a/src/templatematch/gsttemplatematch.c b/src/templatematch/gsttemplatematch.c
index 8db28f7..4f42237 100644
--- a/src/templatematch/gsttemplatematch.c
+++ b/src/templatematch/gsttemplatematch.c
@@ -1,401 +1,413 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2008 Michael Sheldon <mike@mikeasoft.com>
* Copyright (C) 2009 Noam Lewis <jones.noamle@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/**
* SECTION:element-templatematch
*
* FIXME:Describe templatematch here.
*
* <refsect2>
* <title>Example launch line</title>
* |[
* gst-launch-0.10 videotestsrc ! decodebin ! ffmpegcolorspace ! templatematch template=/path/to/file.jpg ! ffmpegcolorspace ! xvimagesink
* ]|
* </refsect2>
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <gst/gst.h>
#include "gsttemplatematch.h"
GST_DEBUG_CATEGORY_STATIC (gst_templatematch_debug);
#define GST_CAT_DEFAULT gst_templatematch_debug
#define DEFAULT_METHOD (3)
/* Filter signals and args */
enum
{
- /* FILL ME */
- LAST_SIGNAL
+ /* FILL ME */
+ LAST_SIGNAL
};
enum
{
- PROP_0,
- PROP_METHOD,
- PROP_TEMPLATE,
- PROP_DISPLAY,
+ PROP_0,
+ PROP_METHOD,
+ PROP_TEMPLATE,
+ PROP_DISPLAY,
};
/* the capabilities of the inputs and outputs.
*/
static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
- GST_PAD_SINK,
- GST_PAD_ALWAYS,
- GST_STATIC_CAPS (
- "video/x-raw-rgb"
- )
+ GST_PAD_SINK,
+ GST_PAD_ALWAYS,
+ GST_STATIC_CAPS ("video/x-raw-rgb")
);
static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
- GST_PAD_SRC,
- GST_PAD_ALWAYS,
- GST_STATIC_CAPS (
- "video/x-raw-rgb"
- )
+ GST_PAD_SRC,
+ GST_PAD_ALWAYS,
+ GST_STATIC_CAPS ("video/x-raw-rgb")
);
GST_BOILERPLATE (GstTemplateMatch, gst_templatematch, GstElement,
- GST_TYPE_ELEMENT);
+ GST_TYPE_ELEMENT);
static void gst_templatematch_finalize (GObject * object);
static void gst_templatematch_set_property (GObject * object, guint prop_id,
- const GValue * value, GParamSpec * pspec);
+ const GValue * value, GParamSpec * pspec);
static void gst_templatematch_get_property (GObject * object, guint prop_id,
- GValue * value, GParamSpec * pspec);
+ GValue * value, GParamSpec * pspec);
static gboolean gst_templatematch_set_caps (GstPad * pad, GstCaps * caps);
static GstFlowReturn gst_templatematch_chain (GstPad * pad, GstBuffer * buf);
-static void gst_templatematch_load_template(GstTemplateMatch *filter);
-static void gst_templatematch_match(IplImage *input, IplImage *template,
- IplImage *dist_image, double *best_res, CvPoint *best_pos, int method);
+static void gst_templatematch_load_template (GstTemplateMatch * filter);
+static void gst_templatematch_match (IplImage * input, IplImage * template,
+ IplImage * dist_image, double *best_res, CvPoint * best_pos, int method);
/* GObject vmethod implementations */
static void
gst_templatematch_base_init (gpointer gclass)
{
- GstElementClass *element_class = GST_ELEMENT_CLASS (gclass);
-
- gst_element_class_set_details_simple(element_class,
- "templatematch",
- "Filter/Effect/Video",
- "Performs template matching on videos and images, providing detected positions via bus messages",
- "Noam Lewis <jones.noamle@gmail.com>");
-
- gst_element_class_add_pad_template (element_class,
- gst_static_pad_template_get (&src_factory));
- gst_element_class_add_pad_template (element_class,
- gst_static_pad_template_get (&sink_factory));
+ GstElementClass *element_class = GST_ELEMENT_CLASS (gclass);
+
+ gst_element_class_set_details_simple (element_class,
+ "templatematch",
+ "Filter/Effect/Video",
+ "Performs template matching on videos and images, providing detected positions via bus messages",
+ "Noam Lewis <jones.noamle@gmail.com>");
+
+ gst_element_class_add_pad_template (element_class,
+ gst_static_pad_template_get (&src_factory));
+ gst_element_class_add_pad_template (element_class,
+ gst_static_pad_template_get (&sink_factory));
}
/* initialize the templatematch's class */
static void
gst_templatematch_class_init (GstTemplateMatchClass * klass)
{
- GObjectClass *gobject_class;
- GstElementClass *gstelement_class;
-
- gobject_class = (GObjectClass *) klass;
- gstelement_class = (GstElementClass *) klass;
-
- gobject_class->finalize = gst_templatematch_finalize;
- gobject_class->set_property = gst_templatematch_set_property;
- gobject_class->get_property = gst_templatematch_get_property;
-
- g_object_class_install_property (gobject_class, PROP_METHOD,
- g_param_spec_int ("method", "Method", "Specifies the way the template must be compared with image regions. 0=SQDIFF, 1=SQDIFF_NORMED, 2=CCOR, 3=CCOR_NORMED, 4=CCOEFF, 5=CCOEFF_NORMED.",
- 0, 5, DEFAULT_METHOD, G_PARAM_READWRITE));
- g_object_class_install_property (gobject_class, PROP_TEMPLATE,
- g_param_spec_string ("template", "Template", "Filename of template image",
- NULL, G_PARAM_READWRITE));
- g_object_class_install_property (gobject_class, PROP_DISPLAY,
- g_param_spec_boolean ("display", "Display", "Sets whether the detected template should be highlighted in the output",
- TRUE, G_PARAM_READWRITE));
+ GObjectClass *gobject_class;
+ GstElementClass *gstelement_class;
+
+ gobject_class = (GObjectClass *) klass;
+ gstelement_class = (GstElementClass *) klass;
+
+ gobject_class->finalize = gst_templatematch_finalize;
+ gobject_class->set_property = gst_templatematch_set_property;
+ gobject_class->get_property = gst_templatematch_get_property;
+
+ g_object_class_install_property (gobject_class, PROP_METHOD,
+ g_param_spec_int ("method", "Method",
+ "Specifies the way the template must be compared with image regions. 0=SQDIFF, 1=SQDIFF_NORMED, 2=CCOR, 3=CCOR_NORMED, 4=CCOEFF, 5=CCOEFF_NORMED.",
+ 0, 5, DEFAULT_METHOD, G_PARAM_READWRITE));
+ g_object_class_install_property (gobject_class, PROP_TEMPLATE,
+ g_param_spec_string ("template", "Template", "Filename of template image",
+ NULL, G_PARAM_READWRITE));
+ g_object_class_install_property (gobject_class, PROP_DISPLAY,
+ g_param_spec_boolean ("display", "Display",
+ "Sets whether the detected template should be highlighted in the output",
+ TRUE, G_PARAM_READWRITE));
}
/* initialize the new element
* instantiate pads and add them to element
* set pad calback functions
* initialize instance structure
*/
static void
gst_templatematch_init (GstTemplateMatch * filter,
- GstTemplateMatchClass * gclass)
+ GstTemplateMatchClass * gclass)
{
- filter->sinkpad = gst_pad_new_from_static_template (&sink_factory, "sink");
- gst_pad_set_setcaps_function (filter->sinkpad,
- GST_DEBUG_FUNCPTR(gst_templatematch_set_caps));
- gst_pad_set_getcaps_function (filter->sinkpad,
- GST_DEBUG_FUNCPTR(gst_pad_proxy_getcaps));
- gst_pad_set_chain_function (filter->sinkpad,
- GST_DEBUG_FUNCPTR(gst_templatematch_chain));
-
- filter->srcpad = gst_pad_new_from_static_template (&src_factory, "src");
- gst_pad_set_getcaps_function (filter->srcpad,
- GST_DEBUG_FUNCPTR(gst_pad_proxy_getcaps));
-
- gst_element_add_pad (GST_ELEMENT (filter), filter->sinkpad);
- gst_element_add_pad (GST_ELEMENT (filter), filter->srcpad);
- filter->template = NULL;
- filter->display = TRUE;
- filter->cvTemplateImage = NULL;
- filter->cvDistImage = NULL;
- filter->cvImage = NULL;
- filter->method = DEFAULT_METHOD;
- gst_templatematch_load_template(filter);
+ filter->sinkpad = gst_pad_new_from_static_template (&sink_factory, "sink");
+ gst_pad_set_setcaps_function (filter->sinkpad,
+ GST_DEBUG_FUNCPTR (gst_templatematch_set_caps));
+ gst_pad_set_getcaps_function (filter->sinkpad,
+ GST_DEBUG_FUNCPTR (gst_pad_proxy_getcaps));
+ gst_pad_set_chain_function (filter->sinkpad,
+ GST_DEBUG_FUNCPTR (gst_templatematch_chain));
+
+ filter->srcpad = gst_pad_new_from_static_template (&src_factory, "src");
+ gst_pad_set_getcaps_function (filter->srcpad,
+ GST_DEBUG_FUNCPTR (gst_pad_proxy_getcaps));
+
+ gst_element_add_pad (GST_ELEMENT (filter), filter->sinkpad);
+ gst_element_add_pad (GST_ELEMENT (filter), filter->srcpad);
+ filter->template = NULL;
+ filter->display = TRUE;
+ filter->cvTemplateImage = NULL;
+ filter->cvDistImage = NULL;
+ filter->cvImage = NULL;
+ filter->method = DEFAULT_METHOD;
+ gst_templatematch_load_template (filter);
}
static void
gst_templatematch_set_property (GObject * object, guint prop_id,
- const GValue * value, GParamSpec * pspec)
+ const GValue * value, GParamSpec * pspec)
{
- GstTemplateMatch *filter = GST_TEMPLATEMATCH (object);
+ GstTemplateMatch *filter = GST_TEMPLATEMATCH (object);
- switch (prop_id) {
+ switch (prop_id) {
case PROP_METHOD:
- switch (g_value_get_int (value)) {
+ switch (g_value_get_int (value)) {
case 0:
- filter->method = CV_TM_SQDIFF; break;
+ filter->method = CV_TM_SQDIFF;
+ break;
case 1:
- filter->method = CV_TM_SQDIFF_NORMED; break;
+ filter->method = CV_TM_SQDIFF_NORMED;
+ break;
case 2:
- filter->method = CV_TM_CCORR; break;
+ filter->method = CV_TM_CCORR;
+ break;
case 3:
- filter->method = CV_TM_CCORR_NORMED; break;
+ filter->method = CV_TM_CCORR_NORMED;
+ break;
case 4:
- filter->method = CV_TM_CCOEFF; break;
+ filter->method = CV_TM_CCOEFF;
+ break;
case 5:
- filter->method = CV_TM_CCOEFF_NORMED; break;
- }
- break;
+ filter->method = CV_TM_CCOEFF_NORMED;
+ break;
+ }
+ break;
case PROP_TEMPLATE:
- filter->template = g_value_get_string (value);
- gst_templatematch_load_template(filter);
- break;
+ filter->template = g_value_get_string (value);
+ gst_templatematch_load_template (filter);
+ break;
case PROP_DISPLAY:
- filter->display = g_value_get_boolean (value);
- break;
+ filter->display = g_value_get_boolean (value);
+ break;
default:
- G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
- break;
- }
+ G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
+ break;
+ }
}
static void
gst_templatematch_get_property (GObject * object, guint prop_id,
- GValue * value, GParamSpec * pspec)
+ GValue * value, GParamSpec * pspec)
{
- GstTemplateMatch *filter = GST_TEMPLATEMATCH (object);
+ GstTemplateMatch *filter = GST_TEMPLATEMATCH (object);
- switch (prop_id) {
+ switch (prop_id) {
case PROP_METHOD:
- g_value_set_int(value, filter->method);
- break;
+ g_value_set_int (value, filter->method);
+ break;
case PROP_TEMPLATE:
- g_value_set_string (value, filter->template);
- break;
+ g_value_set_string (value, filter->template);
+ break;
case PROP_DISPLAY:
- g_value_set_boolean (value, filter->display);
- break;
+ g_value_set_boolean (value, filter->display);
+ break;
default:
- G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
- break;
- }
+ G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
+ break;
+ }
}
/* GstElement vmethod implementations */
/* this function handles the link with other elements */
static gboolean
gst_templatematch_set_caps (GstPad * pad, GstCaps * caps)
{
- GstTemplateMatch *filter;
- GstPad *otherpad;
- gint width, height;
- GstStructure *structure;
+ GstTemplateMatch *filter;
+ GstPad *otherpad;
+ gint width, height;
+ GstStructure *structure;
- filter = GST_TEMPLATEMATCH (gst_pad_get_parent (pad));
- structure = gst_caps_get_structure (caps, 0);
- gst_structure_get_int (structure, "width", &width);
- gst_structure_get_int (structure, "height", &height);
+ filter = GST_TEMPLATEMATCH (gst_pad_get_parent (pad));
+ structure = gst_caps_get_structure (caps, 0);
+ gst_structure_get_int (structure, "width", &width);
+ gst_structure_get_int (structure, "height", &height);
- filter->cvImage = cvCreateImageHeader(cvSize(width, height), IPL_DEPTH_8U, 3);
+ filter->cvImage =
+ cvCreateImageHeader (cvSize (width, height), IPL_DEPTH_8U, 3);
- otherpad = (pad == filter->srcpad) ? filter->sinkpad : filter->srcpad;
- gst_object_unref (filter);
+ otherpad = (pad == filter->srcpad) ? filter->sinkpad : filter->srcpad;
+ gst_object_unref (filter);
- return gst_pad_set_caps (otherpad, caps);
+ return gst_pad_set_caps (otherpad, caps);
}
-static void gst_templatematch_finalize (GObject * object)
+static void
+gst_templatematch_finalize (GObject * object)
{
- GstTemplateMatch *filter;
- filter = GST_TEMPLATEMATCH (object);
-
- if (filter->cvImage) {
- cvReleaseImageHeader(&filter->cvImage);
- }
- if (filter->cvDistImage) {
- cvReleaseImage(&filter->cvDistImage);
- }
- if (filter->cvTemplateImage) {
- cvReleaseImage(&filter->cvTemplateImage);
- }
+ GstTemplateMatch *filter;
+ filter = GST_TEMPLATEMATCH (object);
+
+ if (filter->cvImage) {
+ cvReleaseImageHeader (&filter->cvImage);
+ }
+ if (filter->cvDistImage) {
+ cvReleaseImage (&filter->cvDistImage);
+ }
+ if (filter->cvTemplateImage) {
+ cvReleaseImage (&filter->cvTemplateImage);
+ }
}
/* chain function
* this function does the actual processing
*/
static GstFlowReturn
gst_templatematch_chain (GstPad * pad, GstBuffer * buf)
{
- GstTemplateMatch *filter;
- CvPoint best_pos;
- double best_res;
- int i;
-
- filter = GST_TEMPLATEMATCH (GST_OBJECT_PARENT (pad));
- buf = gst_buffer_make_writable(buf);
- if ((!filter) || (!buf) || filter->template == NULL) {
- return GST_FLOW_OK;
- }
- filter->cvImage->imageData = (char *) GST_BUFFER_DATA (buf);
-
-
+ GstTemplateMatch *filter;
+ CvPoint best_pos;
+ double best_res;
+ int i;
+
+ filter = GST_TEMPLATEMATCH (GST_OBJECT_PARENT (pad));
+ buf = gst_buffer_make_writable (buf);
+ if ((!filter) || (!buf) || filter->template == NULL) {
+ return GST_FLOW_OK;
+ }
+ filter->cvImage->imageData = (char *) GST_BUFFER_DATA (buf);
+
+
+ if (!filter->cvDistImage) {
+ filter->cvDistImage =
+ cvCreateImage (cvSize (filter->cvImage->width -
+ filter->cvTemplateImage->width + 1,
+ filter->cvImage->height - filter->cvTemplateImage->height + 1),
+ IPL_DEPTH_32F, 1);
if (!filter->cvDistImage) {
- filter->cvDistImage = cvCreateImage( cvSize(filter->cvImage->width - filter->cvTemplateImage->width + 1,
- filter->cvImage->height - filter->cvTemplateImage->height + 1),
- IPL_DEPTH_32F, 1);
- if (!filter->cvDistImage) {
- GST_WARNING ("Couldn't create dist image.");
- }
+ GST_WARNING ("Couldn't create dist image.");
}
- if (filter->cvTemplateImage) {
- gst_templatematch_match(filter->cvImage, filter->cvTemplateImage,
- filter->cvDistImage, &best_res, &best_pos, filter->method);
-
- GstStructure *s = gst_structure_new ("template_match",
- "x", G_TYPE_UINT, best_pos.x,
- "y", G_TYPE_UINT, best_pos.y,
- "width", G_TYPE_UINT, filter->cvTemplateImage->width,
- "height", G_TYPE_UINT, filter->cvTemplateImage->height,
- "result", G_TYPE_DOUBLE, best_res,
- NULL);
-
- GstMessage *m = gst_message_new_element (GST_OBJECT (filter), s);
- gst_element_post_message (GST_ELEMENT (filter), m);
-
- if (filter->display) {
- CvPoint corner = best_pos;
- corner.x += filter->cvTemplateImage->width;
- corner.y += filter->cvTemplateImage->height;
- cvRectangle(filter->cvImage, best_pos, corner, CV_RGB(255, 32, 32), 3, 8, 0);
- }
-
+ }
+ if (filter->cvTemplateImage) {
+ gst_templatematch_match (filter->cvImage, filter->cvTemplateImage,
+ filter->cvDistImage, &best_res, &best_pos, filter->method);
+
+ GstStructure *s = gst_structure_new ("template_match",
+ "x", G_TYPE_UINT, best_pos.x,
+ "y", G_TYPE_UINT, best_pos.y,
+ "width", G_TYPE_UINT, filter->cvTemplateImage->width,
+ "height", G_TYPE_UINT, filter->cvTemplateImage->height,
+ "result", G_TYPE_DOUBLE, best_res,
+ NULL);
+
+ GstMessage *m = gst_message_new_element (GST_OBJECT (filter), s);
+ gst_element_post_message (GST_ELEMENT (filter), m);
+
+ if (filter->display) {
+ CvPoint corner = best_pos;
+ corner.x += filter->cvTemplateImage->width;
+ corner.y += filter->cvTemplateImage->height;
+ cvRectangle (filter->cvImage, best_pos, corner, CV_RGB (255, 32, 32), 3,
+ 8, 0);
}
-
- gst_buffer_set_data(buf, filter->cvImage->imageData, filter->cvImage->imageSize);
+ }
+
+
+ gst_buffer_set_data (buf, filter->cvImage->imageData,
+ filter->cvImage->imageSize);
- return gst_pad_push (filter->srcpad, buf);
+ return gst_pad_push (filter->srcpad, buf);
}
-static void gst_templatematch_match(IplImage *input, IplImage *template,
- IplImage *dist_image, double *best_res, CvPoint *best_pos, int method)
+static void
+gst_templatematch_match (IplImage * input, IplImage * template,
+ IplImage * dist_image, double *best_res, CvPoint * best_pos, int method)
{
- double dist_min = 0, dist_max = 0;
- CvPoint min_pos, max_pos;
- cvMatchTemplate(input, template, dist_image, method);
- cvMinMaxLoc(dist_image, &dist_min, &dist_max, &min_pos, &max_pos, NULL);
- if ((CV_TM_SQDIFF_NORMED == method) || (CV_TM_SQDIFF == method))
- {
- *best_res = dist_min;
- *best_pos = min_pos;
- if (CV_TM_SQDIFF_NORMED == method) {
- *best_res = 1-*best_res;
- }
- }
- else {
- *best_res = dist_max;
- *best_pos = max_pos;
+ double dist_min = 0, dist_max = 0;
+ CvPoint min_pos, max_pos;
+ cvMatchTemplate (input, template, dist_image, method);
+ cvMinMaxLoc (dist_image, &dist_min, &dist_max, &min_pos, &max_pos, NULL);
+ if ((CV_TM_SQDIFF_NORMED == method) || (CV_TM_SQDIFF == method)) {
+ *best_res = dist_min;
+ *best_pos = min_pos;
+ if (CV_TM_SQDIFF_NORMED == method) {
+ *best_res = 1 - *best_res;
}
+ } else {
+ *best_res = dist_max;
+ *best_pos = max_pos;
+ }
}
-static void gst_templatematch_load_template(GstTemplateMatch *filter) {
- if (filter->template) {
- filter->cvTemplateImage = cvLoadImage(filter->template, CV_LOAD_IMAGE_COLOR);
- if (!filter->cvTemplateImage) {
- GST_WARNING ("Couldn't load template image: %s.", filter->template);
- }
+static void
+gst_templatematch_load_template (GstTemplateMatch * filter)
+{
+ if (filter->template) {
+ filter->cvTemplateImage =
+ cvLoadImage (filter->template, CV_LOAD_IMAGE_COLOR);
+ if (!filter->cvTemplateImage) {
+ GST_WARNING ("Couldn't load template image: %s.", filter->template);
}
+ }
}
/* entry point to initialize the plug-in
* initialize the plug-in itself
* register the element factories and other features
*/
-gboolean gst_templatematch_plugin_init (GstPlugin * templatematch)
+gboolean
+gst_templatematch_plugin_init (GstPlugin * templatematch)
{
- /* debug category for fltering log messages */
- GST_DEBUG_CATEGORY_INIT (gst_templatematch_debug, "templatematch",
- 0, "Performs template matching on videos and images, providing detected positions via bus messages");
+ /* debug category for fltering log messages */
+ GST_DEBUG_CATEGORY_INIT (gst_templatematch_debug, "templatematch",
+ 0,
+ "Performs template matching on videos and images, providing detected positions via bus messages");
- return gst_element_register (templatematch, "templatematch", GST_RANK_NONE,
- GST_TYPE_TEMPLATEMATCH);
+ return gst_element_register (templatematch, "templatematch", GST_RANK_NONE,
+ GST_TYPE_TEMPLATEMATCH);
}
-
-
diff --git a/src/templatematch/gsttemplatematch.h b/src/templatematch/gsttemplatematch.h
index 35b001d..d4f8414 100644
--- a/src/templatematch/gsttemplatematch.h
+++ b/src/templatematch/gsttemplatematch.h
@@ -1,95 +1,92 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2008 Michael Sheldon <mike@mikeasoft.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#ifndef __GST_TEMPLATEMATCH_H__
#define __GST_TEMPLATEMATCH_H__
#include <gst/gst.h>
#include <opencv/cv.h>
#include <opencv/highgui.h>
G_BEGIN_DECLS
-
/* #defines don't like whitespacey bits */
#define GST_TYPE_TEMPLATEMATCH \
(gst_templatematch_get_type())
#define GST_TEMPLATEMATCH(obj) \
(G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_TEMPLATEMATCH,GstTemplateMatch))
#define GST_TEMPLATEMATCH_CLASS(klass) \
(G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_TEMPLATEMATCH,GstTemplateMatchClass))
#define GST_IS_TEMPLATEMATCH(obj) \
(G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_TEMPLATEMATCH))
#define GST_IS_TEMPLATEMATCH_CLASS(klass) \
(G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_TEMPLATEMATCH))
-
-typedef struct _GstTemplateMatch GstTemplateMatch;
+typedef struct _GstTemplateMatch GstTemplateMatch;
typedef struct _GstTemplateMatchClass GstTemplateMatchClass;
struct _GstTemplateMatch
{
GstElement element;
GstPad *sinkpad, *srcpad;
- gint method;
+ gint method;
gboolean display;
gchar *template;
- IplImage *cvImage, *cvGray, *cvTemplateImage, *cvDistImage;
+ IplImage *cvImage, *cvGray, *cvTemplateImage, *cvDistImage;
};
-struct _GstTemplateMatchClass
+struct _GstTemplateMatchClass
{
GstElementClass parent_class;
};
GType gst_templatematch_get_type (void);
gboolean gst_templatematch_plugin_init (GstPlugin * templatematch);
G_END_DECLS
-
#endif /* __GST_TEMPLATEMATCH_H__ */
|
Elleo/gst-opencv
|
dcdc07127da7a85359530a7e520c17554b0f710c
|
Add all current contributors to the authors list
|
diff --git a/AUTHORS b/AUTHORS
index 1bb7449..140d640 100644
--- a/AUTHORS
+++ b/AUTHORS
@@ -1 +1,4 @@
+Mike Sheldon <mike@mikeasoft.com>
+Noam Lewis <jones.noamle@gmail.com>
+Kapil Agrawal <kapil@mediamagictechnologies.com>
Thomas Vander Stichele <thomas@apestaart.org>
diff --git a/ChangeLog b/ChangeLog
index 6699d28..a871587 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,63 +1,68 @@
+2009-05-26 Mike Sheldon <mike@mikeasoft.com>
+
+ * AUTHORS:
+ Add all current contributors to the authors list
+
2009-05-25 Mike Sheldon <mike@mikeasoft.com>
* configure.ac:
* src/Makefile.am:
* src/gstopencv.c:
* src/faceblur/gstfaceblur.c:
* src/faceblur/gstfaceblur.h:
* src/faceblur/Makefile.am:
Add face blurring element
* debian/control:
* debian/changelog:
Fix dependencies and package section for debian package
* src/templatematch/gsttemplatematch.c:
Fix segfault when no template is loaded
Update example launch line to load a template
* examples/python/templatematch.py:
* examples/python/template.jpg:
Add example usage of the template matching element
2009-05-13 Noam Lewis <jones.noamle@gmail.com>
* configure.ac:
* src/Makefile.am:
* src/gstopencv.c:
* src/templatematch/gsttemplatematch.c:
* src/templatematch/gsttemplatematch.h:
* src/tempaltematch/Makefile.am:
Add template matching element
2009-05-08 Kapil Agrawal <kapil@mediamagictechnologies.com>
* configure.ac:
* src/Makefile.am:
* src/gstopencv.c:
* src/edgedetect/Makefile.am:
* src/edgedetect/gstedgedetect.c:
* src/facedetect/Makefile.am:
* src/facedetect/gstfacedetect.c:
* src/pyramidsegment/Makefile.am:
* src/pyramidsegment/gstpyramidsegment.c:
All elements will register as features of opencv plugin.
2009-05-06 Mike Sheldon <mike@mikeasoft.com>
* src/facedetect/gstfacedetect.c:
Fix "profile" parameter in face detect element to accept a string correctly
(was using char param instead of string param)
* src/edgedetect/gstedgedetect.c:
* src/pyramidsegment/gstpyramidsegment.c:
* src/facedetect/gstfacedetect.c:
Release OpenCV images when finalizing
2009-05-06 Kapil Agrawal <kapil@mediamagictechnologies.com>
* configure.ac: Added an error check for opencv.
* src/edgedetect/gstedgedetect.h:
* src/facedetect/gstfacedetect.h:
* src/pyramidsegment/gstpyramidsegment.h: Fixed the included path.
Fixed some compilation errors.
|
Elleo/gst-opencv
|
a051b13c30d081c3c4da0e50ff77165b076d4fe2
|
Fix segfault in template match element if no template has been set Add template matching python example Add autotool, libtool and pkgconfig dependencies to debian control file
|
diff --git a/ChangeLog b/ChangeLog
index bcb6ed0..6699d28 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,51 +1,63 @@
2009-05-25 Mike Sheldon <mike@mikeasoft.com>
* configure.ac:
* src/Makefile.am:
* src/gstopencv.c:
* src/faceblur/gstfaceblur.c:
* src/faceblur/gstfaceblur.h:
* src/faceblur/Makefile.am:
Add face blurring element
+ * debian/control:
+ * debian/changelog:
+ Fix dependencies and package section for debian package
+
+ * src/templatematch/gsttemplatematch.c:
+ Fix segfault when no template is loaded
+ Update example launch line to load a template
+
+ * examples/python/templatematch.py:
+ * examples/python/template.jpg:
+ Add example usage of the template matching element
+
2009-05-13 Noam Lewis <jones.noamle@gmail.com>
* configure.ac:
* src/Makefile.am:
* src/gstopencv.c:
* src/templatematch/gsttemplatematch.c:
* src/templatematch/gsttemplatematch.h:
* src/tempaltematch/Makefile.am:
Add template matching element
2009-05-08 Kapil Agrawal <kapil@mediamagictechnologies.com>
* configure.ac:
* src/Makefile.am:
* src/gstopencv.c:
* src/edgedetect/Makefile.am:
* src/edgedetect/gstedgedetect.c:
* src/facedetect/Makefile.am:
* src/facedetect/gstfacedetect.c:
* src/pyramidsegment/Makefile.am:
* src/pyramidsegment/gstpyramidsegment.c:
All elements will register as features of opencv plugin.
2009-05-06 Mike Sheldon <mike@mikeasoft.com>
* src/facedetect/gstfacedetect.c:
Fix "profile" parameter in face detect element to accept a string correctly
(was using char param instead of string param)
* src/edgedetect/gstedgedetect.c:
* src/pyramidsegment/gstpyramidsegment.c:
* src/facedetect/gstfacedetect.c:
Release OpenCV images when finalizing
2009-05-06 Kapil Agrawal <kapil@mediamagictechnologies.com>
* configure.ac: Added an error check for opencv.
* src/edgedetect/gstedgedetect.h:
* src/facedetect/gstfacedetect.h:
* src/pyramidsegment/gstpyramidsegment.h: Fixed the included path.
Fixed some compilation errors.
diff --git a/debian/changelog b/debian/changelog
index c8db1a9..77ff0b4 100644
--- a/debian/changelog
+++ b/debian/changelog
@@ -1,17 +1,23 @@
+gst-opencv (0.1+git20090525ubuntu5) jaunty; urgency=low
+
+ * Add autotools, libtool and pkgconfig to package dependencies
+
+ -- Mike Sheldon <mike@mikeasoft.com> Mon, 25 May 2009 12:22:43 +0100
+
gst-opencv (0.1+git20090525ubuntu2) jaunty; urgency=low
* Fix package section
-- Mike Sheldon <mike@mikeasoft.com> Mon, 25 May 2009 12:04:33 +0100
gst-opencv (0.1+git20090525ubuntu1) jaunty; urgency=low
* Add face blurring element
-- Mike Sheldon <mike@mikeasoft.com> Mon, 25 May 2009 11:34:39 +0100
gst-opencv (0.1-1) jaunty; urgency=low
* Initial release
-- Noam Lewis <jones.noamle@gmail.com> Mon, 27 Apr 2009 23:26:11 +0300
diff --git a/debian/control b/debian/control
index 1807fb2..e4637c6 100644
--- a/debian/control
+++ b/debian/control
@@ -1,13 +1,13 @@
Source: gst-opencv
Section: libs
Priority: extra
Maintainer: Noam Lewis <jones.noamle@gmail.com>
-Build-Depends: debhelper (>= 7), libcv-dev, libgstreamer-plugins-base0.10-dev,
+Build-Depends: autoconf (>= 2.52), automake (>= 1.7), libtool (>= 1.5.0), pkg-config (>= 0.11.0), debhelper (>= 7), libcv-dev, libgstreamer-plugins-base0.10-dev,
Standards-Version: 3.8.0
Homepage: https://launchpad.net/gst-opencv
Package: gst-opencv
Architecture: any
Depends: ${shlibs:Depends}, ${misc:Depends}, libcv1, gstreamer0.10-plugins-base
Description: Gstreamer plugins using opencv
A collection of Gstreamer plugins making computer vision techniques from OpenCV available to Gstreamer based applications.
diff --git a/examples/python/template.jpg b/examples/python/template.jpg
new file mode 100644
index 0000000..f0f791b
Binary files /dev/null and b/examples/python/template.jpg differ
diff --git a/examples/python/templatematch.py b/examples/python/templatematch.py
new file mode 100755
index 0000000..2f26a70
--- /dev/null
+++ b/examples/python/templatematch.py
@@ -0,0 +1,26 @@
+#!/usr/bin/env python
+import pygst
+pygst.require("0.10")
+import gst
+import gtk
+
+class TemplateMatch:
+
+ def __init__(self):
+ pipe = """filesrc location=mike-boat.jpg ! decodebin ! ffmpegcolorspace ! templatematch template=template.jpg ! ffmpegcolorspace ! ximagesink"""
+ self.pipeline = gst.parse_launch(pipe)
+
+ self.bus = self.pipeline.get_bus()
+ self.bus.add_signal_watch()
+ self.bus.connect("message::element", self.bus_message)
+
+ self.pipeline.set_state(gst.STATE_PLAYING)
+
+ def bus_message(self, bus, message):
+ st = message.structure
+ if st.get_name() == "template_match":
+ print "Template found at %d,%d with dimensions %dx%d" % (st["x"], st["y"], st["width"], st["height"])
+
+if __name__ == "__main__":
+ f = TemplateMatch()
+ gtk.main()
diff --git a/src/templatematch/gsttemplatematch.c b/src/templatematch/gsttemplatematch.c
index 84675d5..8db28f7 100644
--- a/src/templatematch/gsttemplatematch.c
+++ b/src/templatematch/gsttemplatematch.c
@@ -1,402 +1,401 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2008 Michael Sheldon <mike@mikeasoft.com>
* Copyright (C) 2009 Noam Lewis <jones.noamle@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/**
* SECTION:element-templatematch
*
* FIXME:Describe templatematch here.
*
* <refsect2>
* <title>Example launch line</title>
* |[
- * gst-launch-0.10 videotestsrc ! decodebin ! ffmpegcolorspace ! templatematch ! ffmpegcolorspace ! xvimagesink
+ * gst-launch-0.10 videotestsrc ! decodebin ! ffmpegcolorspace ! templatematch template=/path/to/file.jpg ! ffmpegcolorspace ! xvimagesink
* ]|
* </refsect2>
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <gst/gst.h>
#include "gsttemplatematch.h"
GST_DEBUG_CATEGORY_STATIC (gst_templatematch_debug);
#define GST_CAT_DEFAULT gst_templatematch_debug
-#define DEFAULT_TEMPLATE NULL
#define DEFAULT_METHOD (3)
/* Filter signals and args */
enum
{
/* FILL ME */
LAST_SIGNAL
};
enum
{
PROP_0,
PROP_METHOD,
PROP_TEMPLATE,
PROP_DISPLAY,
};
/* the capabilities of the inputs and outputs.
*/
static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
GST_PAD_SINK,
GST_PAD_ALWAYS,
GST_STATIC_CAPS (
"video/x-raw-rgb"
)
);
static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
GST_PAD_SRC,
GST_PAD_ALWAYS,
GST_STATIC_CAPS (
"video/x-raw-rgb"
)
);
GST_BOILERPLATE (GstTemplateMatch, gst_templatematch, GstElement,
GST_TYPE_ELEMENT);
static void gst_templatematch_finalize (GObject * object);
static void gst_templatematch_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec);
static void gst_templatematch_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec);
static gboolean gst_templatematch_set_caps (GstPad * pad, GstCaps * caps);
static GstFlowReturn gst_templatematch_chain (GstPad * pad, GstBuffer * buf);
static void gst_templatematch_load_template(GstTemplateMatch *filter);
static void gst_templatematch_match(IplImage *input, IplImage *template,
IplImage *dist_image, double *best_res, CvPoint *best_pos, int method);
/* GObject vmethod implementations */
static void
gst_templatematch_base_init (gpointer gclass)
{
GstElementClass *element_class = GST_ELEMENT_CLASS (gclass);
gst_element_class_set_details_simple(element_class,
"templatematch",
"Filter/Effect/Video",
"Performs template matching on videos and images, providing detected positions via bus messages",
"Noam Lewis <jones.noamle@gmail.com>");
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&src_factory));
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&sink_factory));
}
/* initialize the templatematch's class */
static void
gst_templatematch_class_init (GstTemplateMatchClass * klass)
{
GObjectClass *gobject_class;
GstElementClass *gstelement_class;
gobject_class = (GObjectClass *) klass;
gstelement_class = (GstElementClass *) klass;
gobject_class->finalize = gst_templatematch_finalize;
gobject_class->set_property = gst_templatematch_set_property;
gobject_class->get_property = gst_templatematch_get_property;
g_object_class_install_property (gobject_class, PROP_METHOD,
g_param_spec_int ("method", "Method", "Specifies the way the template must be compared with image regions. 0=SQDIFF, 1=SQDIFF_NORMED, 2=CCOR, 3=CCOR_NORMED, 4=CCOEFF, 5=CCOEFF_NORMED.",
0, 5, DEFAULT_METHOD, G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_TEMPLATE,
g_param_spec_string ("template", "Template", "Filename of template image",
- DEFAULT_TEMPLATE, G_PARAM_READWRITE));
+ NULL, G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_DISPLAY,
g_param_spec_boolean ("display", "Display", "Sets whether the detected template should be highlighted in the output",
TRUE, G_PARAM_READWRITE));
}
/* initialize the new element
* instantiate pads and add them to element
* set pad calback functions
* initialize instance structure
*/
static void
gst_templatematch_init (GstTemplateMatch * filter,
GstTemplateMatchClass * gclass)
{
filter->sinkpad = gst_pad_new_from_static_template (&sink_factory, "sink");
gst_pad_set_setcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR(gst_templatematch_set_caps));
gst_pad_set_getcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR(gst_pad_proxy_getcaps));
gst_pad_set_chain_function (filter->sinkpad,
GST_DEBUG_FUNCPTR(gst_templatematch_chain));
filter->srcpad = gst_pad_new_from_static_template (&src_factory, "src");
gst_pad_set_getcaps_function (filter->srcpad,
GST_DEBUG_FUNCPTR(gst_pad_proxy_getcaps));
gst_element_add_pad (GST_ELEMENT (filter), filter->sinkpad);
gst_element_add_pad (GST_ELEMENT (filter), filter->srcpad);
- filter->template = DEFAULT_TEMPLATE;
+ filter->template = NULL;
filter->display = TRUE;
filter->cvTemplateImage = NULL;
filter->cvDistImage = NULL;
filter->cvImage = NULL;
filter->method = DEFAULT_METHOD;
gst_templatematch_load_template(filter);
}
static void
gst_templatematch_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec)
{
GstTemplateMatch *filter = GST_TEMPLATEMATCH (object);
switch (prop_id) {
case PROP_METHOD:
switch (g_value_get_int (value)) {
case 0:
filter->method = CV_TM_SQDIFF; break;
case 1:
filter->method = CV_TM_SQDIFF_NORMED; break;
case 2:
filter->method = CV_TM_CCORR; break;
case 3:
filter->method = CV_TM_CCORR_NORMED; break;
case 4:
filter->method = CV_TM_CCOEFF; break;
case 5:
filter->method = CV_TM_CCOEFF_NORMED; break;
}
break;
case PROP_TEMPLATE:
filter->template = g_value_get_string (value);
gst_templatematch_load_template(filter);
break;
case PROP_DISPLAY:
filter->display = g_value_get_boolean (value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gst_templatematch_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec)
{
GstTemplateMatch *filter = GST_TEMPLATEMATCH (object);
switch (prop_id) {
case PROP_METHOD:
g_value_set_int(value, filter->method);
break;
case PROP_TEMPLATE:
g_value_set_string (value, filter->template);
break;
case PROP_DISPLAY:
g_value_set_boolean (value, filter->display);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
/* GstElement vmethod implementations */
/* this function handles the link with other elements */
static gboolean
gst_templatematch_set_caps (GstPad * pad, GstCaps * caps)
{
GstTemplateMatch *filter;
GstPad *otherpad;
gint width, height;
GstStructure *structure;
filter = GST_TEMPLATEMATCH (gst_pad_get_parent (pad));
structure = gst_caps_get_structure (caps, 0);
gst_structure_get_int (structure, "width", &width);
gst_structure_get_int (structure, "height", &height);
filter->cvImage = cvCreateImageHeader(cvSize(width, height), IPL_DEPTH_8U, 3);
otherpad = (pad == filter->srcpad) ? filter->sinkpad : filter->srcpad;
gst_object_unref (filter);
return gst_pad_set_caps (otherpad, caps);
}
static void gst_templatematch_finalize (GObject * object)
{
GstTemplateMatch *filter;
filter = GST_TEMPLATEMATCH (object);
if (filter->cvImage) {
cvReleaseImageHeader(&filter->cvImage);
}
if (filter->cvDistImage) {
cvReleaseImage(&filter->cvDistImage);
}
if (filter->cvTemplateImage) {
cvReleaseImage(&filter->cvTemplateImage);
}
}
/* chain function
* this function does the actual processing
*/
static GstFlowReturn
gst_templatematch_chain (GstPad * pad, GstBuffer * buf)
{
GstTemplateMatch *filter;
CvPoint best_pos;
double best_res;
int i;
filter = GST_TEMPLATEMATCH (GST_OBJECT_PARENT (pad));
buf = gst_buffer_make_writable(buf);
- if ((!filter) || (!buf)) {
+ if ((!filter) || (!buf) || filter->template == NULL) {
return GST_FLOW_OK;
}
filter->cvImage->imageData = (char *) GST_BUFFER_DATA (buf);
if (!filter->cvDistImage) {
filter->cvDistImage = cvCreateImage( cvSize(filter->cvImage->width - filter->cvTemplateImage->width + 1,
filter->cvImage->height - filter->cvTemplateImage->height + 1),
IPL_DEPTH_32F, 1);
if (!filter->cvDistImage) {
GST_WARNING ("Couldn't create dist image.");
}
}
if (filter->cvTemplateImage) {
gst_templatematch_match(filter->cvImage, filter->cvTemplateImage,
filter->cvDistImage, &best_res, &best_pos, filter->method);
GstStructure *s = gst_structure_new ("template_match",
"x", G_TYPE_UINT, best_pos.x,
"y", G_TYPE_UINT, best_pos.y,
"width", G_TYPE_UINT, filter->cvTemplateImage->width,
"height", G_TYPE_UINT, filter->cvTemplateImage->height,
"result", G_TYPE_DOUBLE, best_res,
NULL);
GstMessage *m = gst_message_new_element (GST_OBJECT (filter), s);
gst_element_post_message (GST_ELEMENT (filter), m);
if (filter->display) {
CvPoint corner = best_pos;
corner.x += filter->cvTemplateImage->width;
corner.y += filter->cvTemplateImage->height;
cvRectangle(filter->cvImage, best_pos, corner, CV_RGB(255, 32, 32), 3, 8, 0);
}
}
gst_buffer_set_data(buf, filter->cvImage->imageData, filter->cvImage->imageSize);
return gst_pad_push (filter->srcpad, buf);
}
static void gst_templatematch_match(IplImage *input, IplImage *template,
IplImage *dist_image, double *best_res, CvPoint *best_pos, int method)
{
double dist_min = 0, dist_max = 0;
CvPoint min_pos, max_pos;
cvMatchTemplate(input, template, dist_image, method);
cvMinMaxLoc(dist_image, &dist_min, &dist_max, &min_pos, &max_pos, NULL);
if ((CV_TM_SQDIFF_NORMED == method) || (CV_TM_SQDIFF == method))
{
*best_res = dist_min;
*best_pos = min_pos;
if (CV_TM_SQDIFF_NORMED == method) {
*best_res = 1-*best_res;
}
}
else {
*best_res = dist_max;
*best_pos = max_pos;
}
}
static void gst_templatematch_load_template(GstTemplateMatch *filter) {
if (filter->template) {
filter->cvTemplateImage = cvLoadImage(filter->template, CV_LOAD_IMAGE_COLOR);
if (!filter->cvTemplateImage) {
GST_WARNING ("Couldn't load template image: %s.", filter->template);
}
}
}
/* entry point to initialize the plug-in
* initialize the plug-in itself
* register the element factories and other features
*/
gboolean gst_templatematch_plugin_init (GstPlugin * templatematch)
{
/* debug category for fltering log messages */
GST_DEBUG_CATEGORY_INIT (gst_templatematch_debug, "templatematch",
0, "Performs template matching on videos and images, providing detected positions via bus messages");
return gst_element_register (templatematch, "templatematch", GST_RANK_NONE,
GST_TYPE_TEMPLATEMATCH);
}
|
Elleo/gst-opencv
|
2715db91bec610813af21aacef387cdfb0197de2
|
Fix debian package section
|
diff --git a/debian/changelog b/debian/changelog
index 1f78575..c8db1a9 100644
--- a/debian/changelog
+++ b/debian/changelog
@@ -1,11 +1,17 @@
-gst-opencv (0.1+git20090525) jaunty; urgency=low
+gst-opencv (0.1+git20090525ubuntu2) jaunty; urgency=low
+
+ * Fix package section
+
+ -- Mike Sheldon <mike@mikeasoft.com> Mon, 25 May 2009 12:04:33 +0100
+
+gst-opencv (0.1+git20090525ubuntu1) jaunty; urgency=low
* Add face blurring element
-- Mike Sheldon <mike@mikeasoft.com> Mon, 25 May 2009 11:34:39 +0100
gst-opencv (0.1-1) jaunty; urgency=low
* Initial release
-- Noam Lewis <jones.noamle@gmail.com> Mon, 27 Apr 2009 23:26:11 +0300
diff --git a/debian/control b/debian/control
index 9505fff..1807fb2 100644
--- a/debian/control
+++ b/debian/control
@@ -1,13 +1,13 @@
Source: gst-opencv
-Section: unknown
+Section: libs
Priority: extra
Maintainer: Noam Lewis <jones.noamle@gmail.com>
Build-Depends: debhelper (>= 7), libcv-dev, libgstreamer-plugins-base0.10-dev,
Standards-Version: 3.8.0
Homepage: https://launchpad.net/gst-opencv
Package: gst-opencv
Architecture: any
Depends: ${shlibs:Depends}, ${misc:Depends}, libcv1, gstreamer0.10-plugins-base
Description: Gstreamer plugins using opencv
A collection of Gstreamer plugins making computer vision techniques from OpenCV available to Gstreamer based applications.
|
Elleo/gst-opencv
|
cee6db97f245c421fbe79593304e9d9d12ccf448
|
Add a plugin for automatically blurring faces in videos and images
|
diff --git a/configure.ac b/configure.ac
index 90c5c4b..e582dc8 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1,142 +1,142 @@
AC_INIT
dnl versions of gstreamer and plugins-base
GST_MAJORMINOR=0.10
GST_REQUIRED=0.10.0
GSTPB_REQUIRED=0.10.0
dnl fill in your package name and version here
dnl the fourth (nano) number should be 0 for a release, 1 for CVS,
dnl and 2... for a prerelease
dnl when going to/from release please set the nano correctly !
dnl releases only do Wall, cvs and prerelease does Werror too
AS_VERSION(gst-opencv, GST_PLUGIN_VERSION, 0, 10, 0, 1,
GST_PLUGIN_CVS="no", GST_PLUGIN_CVS="yes")
dnl AM_MAINTAINER_MODE provides the option to enable maintainer mode
AM_MAINTAINER_MODE
AM_INIT_AUTOMAKE($PACKAGE, $VERSION)
dnl make aclocal work in maintainer mode
AC_SUBST(ACLOCAL_AMFLAGS, "-I m4")
AM_CONFIG_HEADER(config.h)
dnl check for tools
AC_PROG_CC
AC_PROG_LIBTOOL
dnl decide on error flags
AS_COMPILER_FLAG(-Wall, GST_WALL="yes", GST_WALL="no")
if test "x$GST_WALL" = "xyes"; then
GST_ERROR="$GST_ERROR -Wall"
# if test "x$GST_PLUGIN_CVS" = "xyes"; then
# AS_COMPILER_FLAG(-Werror,GST_ERROR="$GST_ERROR -Werror",GST_ERROR="$GST_ERROR")
# fi
fi
dnl Check for pkgconfig first
AC_CHECK_PROG(HAVE_PKGCONFIG, pkg-config, yes, no)
dnl Give error and exit if we don't have pkgconfig
if test "x$HAVE_PKGCONFIG" = "xno"; then
AC_MSG_ERROR(you need to have pkgconfig installed !)
fi
dnl Now we're ready to ask for gstreamer libs and cflags
dnl And we can also ask for the right version of gstreamer
PKG_CHECK_MODULES(GST, \
gstreamer-$GST_MAJORMINOR >= $GST_REQUIRED,
HAVE_GST=yes,HAVE_GST=no)
dnl Give error and exit if we don't have gstreamer
if test "x$HAVE_GST" = "xno"; then
AC_MSG_ERROR(you need gstreamer development packages installed !)
fi
dnl append GST_ERROR cflags to GST_CFLAGS
GST_CFLAGS="$GST_CFLAGS $GST_ERROR"
dnl make GST_CFLAGS and GST_LIBS available
AC_SUBST(GST_CFLAGS)
AC_SUBST(GST_LIBS)
dnl make GST_MAJORMINOR available in Makefile.am
AC_SUBST(GST_MAJORMINOR)
dnl If we need them, we can also use the base class libraries
PKG_CHECK_MODULES(GST_BASE, gstreamer-base-$GST_MAJORMINOR >= $GST_REQUIRED,
HAVE_GST_BASE=yes, HAVE_GST_BASE=no)
dnl Give a warning if we don't have gstreamer libs
dnl you can turn this into an error if you need them
if test "x$HAVE_GST_BASE" = "xno"; then
AC_MSG_NOTICE(no GStreamer base class libraries found (gstreamer-base-$GST_MAJORMINOR))
fi
dnl make _CFLAGS and _LIBS available
AC_SUBST(GST_BASE_CFLAGS)
AC_SUBST(GST_BASE_LIBS)
PKG_CHECK_MODULES(OPENCV,
opencv,
HAVE_OPENCV=yes, HAVE_OPENCV=no)
AC_SUBST(OPENCV_CFLAGS)
AC_SUBST(OPENCV_LIBS)
if test "x$HAVE_OPENCV" = "xno"; then
AC_MSG_ERROR(OpenCV libraries could not be found)
fi
dnl If we need them, we can also use the gstreamer-plugins-base libraries
PKG_CHECK_MODULES(GSTPB_BASE,
gstreamer-plugins-base-$GST_MAJORMINOR >= $GSTPB_REQUIRED,
HAVE_GSTPB_BASE=yes, HAVE_GSTPB_BASE=no)
dnl Give a warning if we don't have gstreamer libs
dnl you can turn this into an error if you need them
if test "x$HAVE_GSTPB_BASE" = "xno"; then
AC_MSG_NOTICE(no GStreamer Plugins Base libraries found (gstreamer-plugins-base-$GST_MAJORMINOR))
fi
dnl make _CFLAGS and _LIBS available
AC_SUBST(GSTPB_BASE_CFLAGS)
AC_SUBST(GSTPB_BASE_LIBS)
dnl If we need them, we can also use the gstreamer-controller libraries
PKG_CHECK_MODULES(GSTCTRL,
gstreamer-controller-$GST_MAJORMINOR >= $GSTPB_REQUIRED,
HAVE_GSTCTRL=yes, HAVE_GSTCTRL=no)
dnl Give a warning if we don't have gstreamer-controller
dnl you can turn this into an error if you need them
if test "x$HAVE_GSTCTRL" = "xno"; then
AC_MSG_NOTICE(no GStreamer Controller libraries found (gstreamer-controller-$GST_MAJORMINOR))
fi
dnl make _CFLAGS and _LIBS available
AC_SUBST(GSTCTRL_CFLAGS)
AC_SUBST(GSTCTRL_LIBS)
dnl set the plugindir where plugins should be installed
if test "x${prefix}" = "x$HOME"; then
plugindir="$HOME/.gstreamer-$GST_MAJORMINOR/plugins"
else
plugindir="\$(libdir)/gstreamer-$GST_MAJORMINOR"
fi
AC_SUBST(plugindir)
dnl set proper LDFLAGS for plugins
GST_PLUGIN_LDFLAGS='-module -avoid-version -export-symbols-regex [_]*\(gst_\|Gst\|GST_\).*'
AC_SUBST(GST_PLUGIN_LDFLAGS)
-AC_OUTPUT(Makefile m4/Makefile src/Makefile src/edgedetect/Makefile src/pyramidsegment/Makefile src/facedetect/Makefile)
+AC_OUTPUT(Makefile m4/Makefile src/Makefile src/edgedetect/Makefile src/faceblur/Makefile src/facedetect/Makefile src/pyramidsegment/Makefile)
diff --git a/src/Makefile.am b/src/Makefile.am
index aa412a4..e9ddfa4 100644
--- a/src/Makefile.am
+++ b/src/Makefile.am
@@ -1,30 +1,33 @@
-SUBDIRS = edgedetect facedetect pyramidsegment
+SUBDIRS = edgedetect faceblur facedetect pyramidsegment
# plugindir is set in configure
plugin_LTLIBRARIES = libgstopencv.la
# sources used to compile this plug-in
libgstopencv_la_SOURCES = gstopencv.c
# flags used to compile this facedetect
# add other _CFLAGS and _LIBS as needed
libgstopencv_la_CFLAGS = $(GST_CFLAGS) $(OPENCV_CFLAGS) \
-I${top_srcdir}/src/edgedetect \
+ -I${top_srcdir}/src/faceblur \
-I${top_srcdir}/src/facedetect \
-I${top_srcdir}/src/pyramidsegment
libgstopencv_la_LIBADD = $(GST_LIBS) $(OPENCV_LIBS) \
$(top_builddir)/src/edgedetect/libgstedgedetect.la \
+ $(top_builddir)/src/faceblur/libgstfaceblur.la \
$(top_builddir)/src/facedetect/libgstfacedetect.la \
$(top_builddir)/src/pyramidsegment/libgstpyramidsegment.la
libgstopencv_la_LDFLAGS = $(GST_PLUGIN_LDFLAGS)
libgstopencv_la_DEPENDENCIES = \
$(top_builddir)/src/edgedetect/libgstedgedetect.la \
+ $(top_builddir)/src/faceblur/libgstfaceblur.la \
$(top_builddir)/src/facedetect/libgstfacedetect.la \
$(top_builddir)/src/pyramidsegment/libgstpyramidsegment.la
# headers we need but don't want installed
noinst_HEADERS =
diff --git a/src/faceblur/Makefile.am b/src/faceblur/Makefile.am
new file mode 100644
index 0000000..d9c7a2f
--- /dev/null
+++ b/src/faceblur/Makefile.am
@@ -0,0 +1,15 @@
+# plugindir is set in configure
+
+noinst_LTLIBRARIES = libgstfaceblur.la
+
+# sources used to compile this plug-in
+libgstfaceblur_la_SOURCES = gstfaceblur.c
+
+# flags used to compile this faceblur
+# add other _CFLAGS and _LIBS as needed
+libgstfaceblur_la_CFLAGS = $(GST_CFLAGS) $(OPENCV_CFLAGS)
+libgstfaceblur_la_LIBADD = $(GST_LIBS) $(OPENCV_LIBS)
+libgstfaceblur_la_LDFLAGS = $(GST_PLUGIN_LDFLAGS)
+
+# headers we need but don't want installed
+noinst_HEADERS = gstfaceblur.h
diff --git a/src/faceblur/gstfaceblur.c b/src/faceblur/gstfaceblur.c
new file mode 100644
index 0000000..7a878c1
--- /dev/null
+++ b/src/faceblur/gstfaceblur.c
@@ -0,0 +1,313 @@
+/*
+ * GStreamer
+ * Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
+ * Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
+ * Copyright (C) 2008 Michael Sheldon <mike@mikeasoft.com>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ * Alternatively, the contents of this file may be used under the
+ * GNU Lesser General Public License Version 2.1 (the "LGPL"), in
+ * which case the following provisions apply instead of the ones
+ * mentioned above:
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+/**
+ * SECTION:element-faceblur
+ *
+ * FIXME:Describe faceblur here.
+ *
+ * <refsect2>
+ * <title>Example launch line</title>
+ * |[
+ * gst-launch-0.10 videotestsrc ! decodebin ! ffmpegcolorspace ! faceblur ! ffmpegcolorspace ! xvimagesink
+ * ]|
+ * </refsect2>
+ */
+
+#ifdef HAVE_CONFIG_H
+# include <config.h>
+#endif
+
+#include <gst/gst.h>
+
+#include "gstfaceblur.h"
+
+GST_DEBUG_CATEGORY_STATIC (gst_faceblur_debug);
+#define GST_CAT_DEFAULT gst_faceblur_debug
+
+#define DEFAULT_PROFILE "/usr/share/opencv/haarcascades/haarcascade_frontalface_default.xml"
+
+/* Filter signals and args */
+enum
+{
+ /* FILL ME */
+ LAST_SIGNAL
+};
+
+enum
+{
+ PROP_0,
+ PROP_PROFILE
+};
+
+/* the capabilities of the inputs and outputs.
+ */
+static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
+ GST_PAD_SINK,
+ GST_PAD_ALWAYS,
+ GST_STATIC_CAPS (
+ "video/x-raw-rgb"
+ )
+);
+
+static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
+ GST_PAD_SRC,
+ GST_PAD_ALWAYS,
+ GST_STATIC_CAPS (
+ "video/x-raw-rgb"
+ )
+);
+
+GST_BOILERPLATE (Gstfaceblur, gst_faceblur, GstElement,
+ GST_TYPE_ELEMENT);
+
+static void gst_faceblur_set_property (GObject * object, guint prop_id,
+ const GValue * value, GParamSpec * pspec);
+static void gst_faceblur_get_property (GObject * object, guint prop_id,
+ GValue * value, GParamSpec * pspec);
+
+static gboolean gst_faceblur_set_caps (GstPad * pad, GstCaps * caps);
+static GstFlowReturn gst_faceblur_chain (GstPad * pad, GstBuffer * buf);
+
+static void gst_faceblur_load_profile (Gstfaceblur * filter);
+
+/* Clean up */
+static void
+gst_faceblur_finalize (GObject * obj)
+{
+ Gstfaceblur *filter = GST_FACEBLUR(obj);
+
+ if (filter->cvImage)
+ {
+ cvReleaseImage (&filter->cvImage);
+ cvReleaseImage (&filter->cvGray);
+ }
+
+ G_OBJECT_CLASS (parent_class)->finalize (obj);
+}
+
+
+/* GObject vmethod implementations */
+static void
+gst_faceblur_base_init (gpointer gclass)
+{
+ GstElementClass *element_class = GST_ELEMENT_CLASS (gclass);
+
+ gst_element_class_set_details_simple(element_class,
+ "faceblur",
+ "Filter/Effect/Video",
+ "Blurs faces in images and videos",
+ "Michael Sheldon <mike@mikeasoft.com>");
+
+ gst_element_class_add_pad_template (element_class,
+ gst_static_pad_template_get (&src_factory));
+ gst_element_class_add_pad_template (element_class,
+ gst_static_pad_template_get (&sink_factory));
+}
+
+/* initialize the faceblur's class */
+static void
+gst_faceblur_class_init (GstfaceblurClass * klass)
+{
+ GObjectClass *gobject_class;
+ GstElementClass *gstelement_class;
+
+ gobject_class = (GObjectClass *) klass;
+ gstelement_class = (GstElementClass *) klass;
+ parent_class = g_type_class_peek_parent (klass);
+
+ gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_faceblur_finalize);
+ gobject_class->set_property = gst_faceblur_set_property;
+ gobject_class->get_property = gst_faceblur_get_property;
+
+ g_object_class_install_property (gobject_class, PROP_PROFILE,
+ g_param_spec_string ("profile", "Profile", "Location of Haar cascade file to use for face blurion",
+ DEFAULT_PROFILE, G_PARAM_READWRITE));
+}
+
+/* initialize the new element
+ * instantiate pads and add them to element
+ * set pad calback functions
+ * initialize instance structure
+ */
+static void
+gst_faceblur_init (Gstfaceblur * filter,
+ GstfaceblurClass * gclass)
+{
+ filter->sinkpad = gst_pad_new_from_static_template (&sink_factory, "sink");
+ gst_pad_set_setcaps_function (filter->sinkpad,
+ GST_DEBUG_FUNCPTR(gst_faceblur_set_caps));
+ gst_pad_set_getcaps_function (filter->sinkpad,
+ GST_DEBUG_FUNCPTR(gst_pad_proxy_getcaps));
+ gst_pad_set_chain_function (filter->sinkpad,
+ GST_DEBUG_FUNCPTR(gst_faceblur_chain));
+
+ filter->srcpad = gst_pad_new_from_static_template (&src_factory, "src");
+ gst_pad_set_getcaps_function (filter->srcpad,
+ GST_DEBUG_FUNCPTR(gst_pad_proxy_getcaps));
+
+ gst_element_add_pad (GST_ELEMENT (filter), filter->sinkpad);
+ gst_element_add_pad (GST_ELEMENT (filter), filter->srcpad);
+ filter->profile = DEFAULT_PROFILE;
+ gst_faceblur_load_profile(filter);
+}
+
+static void
+gst_faceblur_set_property (GObject * object, guint prop_id,
+ const GValue * value, GParamSpec * pspec)
+{
+ Gstfaceblur *filter = GST_FACEBLUR (object);
+
+ switch (prop_id) {
+ case PROP_PROFILE:
+ filter->profile = g_value_dup_string (value);
+ gst_faceblur_load_profile(filter);
+ break;
+ default:
+ G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
+ break;
+ }
+}
+
+static void
+gst_faceblur_get_property (GObject * object, guint prop_id,
+ GValue * value, GParamSpec * pspec)
+{
+ Gstfaceblur *filter = GST_FACEBLUR (object);
+
+ switch (prop_id) {
+ case PROP_PROFILE:
+ g_value_take_string (value, filter->profile);
+ break;
+ default:
+ G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
+ break;
+ }
+}
+
+/* GstElement vmethod implementations */
+
+/* this function handles the link with other elements */
+static gboolean
+gst_faceblur_set_caps (GstPad * pad, GstCaps * caps)
+{
+ Gstfaceblur *filter;
+ GstPad *otherpad;
+ gint width, height;
+ GstStructure *structure;
+
+ filter = GST_FACEBLUR (gst_pad_get_parent (pad));
+ structure = gst_caps_get_structure (caps, 0);
+ gst_structure_get_int (structure, "width", &width);
+ gst_structure_get_int (structure, "height", &height);
+
+ filter->cvImage = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 3);
+ filter->cvGray = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 1);
+ filter->cvStorage = cvCreateMemStorage(0);
+
+ otherpad = (pad == filter->srcpad) ? filter->sinkpad : filter->srcpad;
+ gst_object_unref (filter);
+
+ return gst_pad_set_caps (otherpad, caps);
+}
+
+/* chain function
+ * this function does the actual processing
+ */
+static GstFlowReturn
+gst_faceblur_chain (GstPad * pad, GstBuffer * buf)
+{
+ Gstfaceblur *filter;
+ CvSeq *faces;
+ int i;
+
+ filter = GST_FACEBLUR (GST_OBJECT_PARENT (pad));
+
+ filter->cvImage->imageData = (char *) GST_BUFFER_DATA (buf);
+
+ cvCvtColor(filter->cvImage, filter->cvGray, CV_RGB2GRAY);
+ cvClearMemStorage(filter->cvStorage);
+
+ if (filter->cvCascade) {
+ faces = cvHaarDetectObjects(filter->cvGray, filter->cvCascade, filter->cvStorage, 1.1, 2, 0, cvSize(30, 30));
+
+ for (i = 0; i < (faces ? faces->total : 0); i++) {
+ CvRect* r = (CvRect *) cvGetSeqElem(faces, i);
+ cvSetImageROI(filter->cvImage, *r);
+ cvSmooth(filter->cvImage, filter->cvImage, CV_BLUR, 11, 11, 0, 0);
+ cvSmooth(filter->cvImage, filter->cvImage, CV_GAUSSIAN, 11, 11, 0, 0);
+ cvResetImageROI(filter->cvImage);
+ }
+
+ }
+
+ gst_buffer_set_data(buf, filter->cvImage->imageData, filter->cvImage->imageSize);
+
+ return gst_pad_push (filter->srcpad, buf);
+}
+
+
+static void gst_faceblur_load_profile(Gstfaceblur * filter) {
+ filter->cvCascade = (CvHaarClassifierCascade*)cvLoad(filter->profile, 0, 0, 0 );
+ if (!filter->cvCascade) {
+ GST_WARNING ("Couldn't load Haar classifier cascade: %s.", filter->profile);
+ }
+}
+
+
+/* entry point to initialize the plug-in
+ * initialize the plug-in itself
+ * register the element factories and other features
+ */
+gboolean
+gst_faceblur_plugin_init (GstPlugin * plugin)
+{
+ /* debug category for filtering log messages */
+ GST_DEBUG_CATEGORY_INIT (gst_faceblur_debug, "faceblur",
+ 0, "Blurs faces in images and videos");
+
+ return gst_element_register (plugin, "faceblur", GST_RANK_NONE,
+ GST_TYPE_FACEBLUR);
+}
diff --git a/src/faceblur/gstfaceblur.h b/src/faceblur/gstfaceblur.h
new file mode 100644
index 0000000..57d2c4c
--- /dev/null
+++ b/src/faceblur/gstfaceblur.h
@@ -0,0 +1,95 @@
+/*
+ * GStreamer
+ * Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
+ * Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
+ * Copyright (C) 2008 Michael Sheldon <mike@mikeasoft.com>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ * Alternatively, the contents of this file may be used under the
+ * GNU Lesser General Public License Version 2.1 (the "LGPL"), in
+ * which case the following provisions apply instead of the ones
+ * mentioned above:
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+#ifndef __GST_FACEBLUR_H__
+#define __GST_FACEBLUR_H__
+
+#include <gst/gst.h>
+#include <cv.h>
+
+G_BEGIN_DECLS
+
+/* #defines don't like whitespacey bits */
+#define GST_TYPE_FACEBLUR \
+ (gst_faceblur_get_type())
+#define GST_FACEBLUR(obj) \
+ (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_FACEBLUR,Gstfaceblur))
+#define GST_FACEBLUR_CLASS(klass) \
+ (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_FACEBLUR,GstfaceblurClass))
+#define GST_IS_FACEBLUR(obj) \
+ (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_FACEBLUR))
+#define GST_IS_FACEBLUR_CLASS(klass) \
+ (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_FACEBLUR))
+
+typedef struct _Gstfaceblur Gstfaceblur;
+typedef struct _GstfaceblurClass GstfaceblurClass;
+
+struct _Gstfaceblur
+{
+ GstElement element;
+
+ GstPad *sinkpad, *srcpad;
+
+ gboolean display;
+
+ gchar *profile;
+
+ IplImage *cvImage, *cvGray;
+ CvHaarClassifierCascade *cvCascade;
+ CvMemStorage *cvStorage;
+};
+
+struct _GstfaceblurClass
+{
+ GstElementClass parent_class;
+};
+
+GType gst_faceblur_get_type (void);
+
+gboolean gst_faceblur_plugin_init (GstPlugin * plugin);
+
+G_END_DECLS
+
+#endif /* __GST_FACEBLUR_H__ */
diff --git a/src/gstopencv.c b/src/gstopencv.c
index 8c03647..4890c5d 100644
--- a/src/gstopencv.c
+++ b/src/gstopencv.c
@@ -1,50 +1,54 @@
/* GStreamer
* Copyright (C) <2009> Kapil Agrawal <kapil@mediamagictechnologies.com>
*
* gstopencv.c: plugin registering
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "gstedgedetect.h"
+#include "gstfaceblur.h"
#include "gstfacedetect.h"
#include "gstpyramidsegment.h"
static gboolean
plugin_init (GstPlugin * plugin)
{
if (!gst_edgedetect_plugin_init (plugin))
return FALSE;
+ if (!gst_faceblur_plugin_init(plugin))
+ return FALSE;
+
if (!gst_facedetect_plugin_init (plugin))
return FALSE;
if (!gst_pyramidsegment_plugin_init (plugin))
return FALSE;
return TRUE;
}
GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
GST_VERSION_MINOR,
"opencv",
"GStreamer OpenCV Plugins",
plugin_init, VERSION, "LGPL", "OpenCv", "http://opencv.willowgarage.com")
|
Elleo/gst-opencv
|
a9367e00000e7b61cc139d7193cf9d776983e39b
|
Added control for changing method
|
diff --git a/src/templatematch/gsttemplatematch.c b/src/templatematch/gsttemplatematch.c
index b9f5779..84675d5 100644
--- a/src/templatematch/gsttemplatematch.c
+++ b/src/templatematch/gsttemplatematch.c
@@ -1,379 +1,402 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2008 Michael Sheldon <mike@mikeasoft.com>
* Copyright (C) 2009 Noam Lewis <jones.noamle@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/**
* SECTION:element-templatematch
*
* FIXME:Describe templatematch here.
*
* <refsect2>
* <title>Example launch line</title>
* |[
* gst-launch-0.10 videotestsrc ! decodebin ! ffmpegcolorspace ! templatematch ! ffmpegcolorspace ! xvimagesink
* ]|
* </refsect2>
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <gst/gst.h>
#include "gsttemplatematch.h"
GST_DEBUG_CATEGORY_STATIC (gst_templatematch_debug);
#define GST_CAT_DEFAULT gst_templatematch_debug
#define DEFAULT_TEMPLATE NULL
+#define DEFAULT_METHOD (3)
/* Filter signals and args */
enum
{
/* FILL ME */
LAST_SIGNAL
};
enum
{
PROP_0,
+ PROP_METHOD,
+ PROP_TEMPLATE,
PROP_DISPLAY,
- PROP_TEMPLATE
};
/* the capabilities of the inputs and outputs.
*/
static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
GST_PAD_SINK,
GST_PAD_ALWAYS,
GST_STATIC_CAPS (
"video/x-raw-rgb"
)
);
static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
GST_PAD_SRC,
GST_PAD_ALWAYS,
GST_STATIC_CAPS (
"video/x-raw-rgb"
)
);
GST_BOILERPLATE (GstTemplateMatch, gst_templatematch, GstElement,
GST_TYPE_ELEMENT);
static void gst_templatematch_finalize (GObject * object);
static void gst_templatematch_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec);
static void gst_templatematch_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec);
static gboolean gst_templatematch_set_caps (GstPad * pad, GstCaps * caps);
static GstFlowReturn gst_templatematch_chain (GstPad * pad, GstBuffer * buf);
-static void gst_templatematch_load_template (GObject * object);
+static void gst_templatematch_load_template(GstTemplateMatch *filter);
static void gst_templatematch_match(IplImage *input, IplImage *template,
IplImage *dist_image, double *best_res, CvPoint *best_pos, int method);
/* GObject vmethod implementations */
static void
gst_templatematch_base_init (gpointer gclass)
{
GstElementClass *element_class = GST_ELEMENT_CLASS (gclass);
gst_element_class_set_details_simple(element_class,
"templatematch",
"Filter/Effect/Video",
"Performs template matching on videos and images, providing detected positions via bus messages",
"Noam Lewis <jones.noamle@gmail.com>");
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&src_factory));
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&sink_factory));
}
/* initialize the templatematch's class */
static void
gst_templatematch_class_init (GstTemplateMatchClass * klass)
{
GObjectClass *gobject_class;
GstElementClass *gstelement_class;
gobject_class = (GObjectClass *) klass;
gstelement_class = (GstElementClass *) klass;
gobject_class->finalize = gst_templatematch_finalize;
gobject_class->set_property = gst_templatematch_set_property;
gobject_class->get_property = gst_templatematch_get_property;
- g_object_class_install_property (gobject_class, PROP_DISPLAY,
- g_param_spec_boolean ("display", "Display", "Sets whether the detected template should be highlighted in the output",
- TRUE, G_PARAM_READWRITE));
+ g_object_class_install_property (gobject_class, PROP_METHOD,
+ g_param_spec_int ("method", "Method", "Specifies the way the template must be compared with image regions. 0=SQDIFF, 1=SQDIFF_NORMED, 2=CCOR, 3=CCOR_NORMED, 4=CCOEFF, 5=CCOEFF_NORMED.",
+ 0, 5, DEFAULT_METHOD, G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_TEMPLATE,
g_param_spec_string ("template", "Template", "Filename of template image",
DEFAULT_TEMPLATE, G_PARAM_READWRITE));
+ g_object_class_install_property (gobject_class, PROP_DISPLAY,
+ g_param_spec_boolean ("display", "Display", "Sets whether the detected template should be highlighted in the output",
+ TRUE, G_PARAM_READWRITE));
}
/* initialize the new element
* instantiate pads and add them to element
* set pad calback functions
* initialize instance structure
*/
static void
gst_templatematch_init (GstTemplateMatch * filter,
GstTemplateMatchClass * gclass)
{
filter->sinkpad = gst_pad_new_from_static_template (&sink_factory, "sink");
gst_pad_set_setcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR(gst_templatematch_set_caps));
gst_pad_set_getcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR(gst_pad_proxy_getcaps));
gst_pad_set_chain_function (filter->sinkpad,
GST_DEBUG_FUNCPTR(gst_templatematch_chain));
filter->srcpad = gst_pad_new_from_static_template (&src_factory, "src");
gst_pad_set_getcaps_function (filter->srcpad,
GST_DEBUG_FUNCPTR(gst_pad_proxy_getcaps));
gst_element_add_pad (GST_ELEMENT (filter), filter->sinkpad);
gst_element_add_pad (GST_ELEMENT (filter), filter->srcpad);
filter->template = DEFAULT_TEMPLATE;
filter->display = TRUE;
filter->cvTemplateImage = NULL;
filter->cvDistImage = NULL;
filter->cvImage = NULL;
+ filter->method = DEFAULT_METHOD;
gst_templatematch_load_template(filter);
}
static void
gst_templatematch_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec)
{
GstTemplateMatch *filter = GST_TEMPLATEMATCH (object);
switch (prop_id) {
+ case PROP_METHOD:
+ switch (g_value_get_int (value)) {
+ case 0:
+ filter->method = CV_TM_SQDIFF; break;
+ case 1:
+ filter->method = CV_TM_SQDIFF_NORMED; break;
+ case 2:
+ filter->method = CV_TM_CCORR; break;
+ case 3:
+ filter->method = CV_TM_CCORR_NORMED; break;
+ case 4:
+ filter->method = CV_TM_CCOEFF; break;
+ case 5:
+ filter->method = CV_TM_CCOEFF_NORMED; break;
+ }
+ break;
case PROP_TEMPLATE:
filter->template = g_value_get_string (value);
gst_templatematch_load_template(filter);
break;
case PROP_DISPLAY:
filter->display = g_value_get_boolean (value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gst_templatematch_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec)
{
GstTemplateMatch *filter = GST_TEMPLATEMATCH (object);
switch (prop_id) {
+ case PROP_METHOD:
+ g_value_set_int(value, filter->method);
+ break;
case PROP_TEMPLATE:
g_value_set_string (value, filter->template);
break;
case PROP_DISPLAY:
g_value_set_boolean (value, filter->display);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
/* GstElement vmethod implementations */
/* this function handles the link with other elements */
static gboolean
gst_templatematch_set_caps (GstPad * pad, GstCaps * caps)
{
GstTemplateMatch *filter;
GstPad *otherpad;
gint width, height;
GstStructure *structure;
filter = GST_TEMPLATEMATCH (gst_pad_get_parent (pad));
structure = gst_caps_get_structure (caps, 0);
gst_structure_get_int (structure, "width", &width);
gst_structure_get_int (structure, "height", &height);
filter->cvImage = cvCreateImageHeader(cvSize(width, height), IPL_DEPTH_8U, 3);
otherpad = (pad == filter->srcpad) ? filter->sinkpad : filter->srcpad;
gst_object_unref (filter);
return gst_pad_set_caps (otherpad, caps);
}
static void gst_templatematch_finalize (GObject * object)
{
GstTemplateMatch *filter;
filter = GST_TEMPLATEMATCH (object);
if (filter->cvImage) {
cvReleaseImageHeader(&filter->cvImage);
}
if (filter->cvDistImage) {
cvReleaseImage(&filter->cvDistImage);
}
if (filter->cvTemplateImage) {
cvReleaseImage(&filter->cvTemplateImage);
}
}
/* chain function
* this function does the actual processing
*/
static GstFlowReturn
gst_templatematch_chain (GstPad * pad, GstBuffer * buf)
{
GstTemplateMatch *filter;
CvPoint best_pos;
double best_res;
int i;
filter = GST_TEMPLATEMATCH (GST_OBJECT_PARENT (pad));
buf = gst_buffer_make_writable(buf);
if ((!filter) || (!buf)) {
return GST_FLOW_OK;
}
filter->cvImage->imageData = (char *) GST_BUFFER_DATA (buf);
if (!filter->cvDistImage) {
filter->cvDistImage = cvCreateImage( cvSize(filter->cvImage->width - filter->cvTemplateImage->width + 1,
filter->cvImage->height - filter->cvTemplateImage->height + 1),
IPL_DEPTH_32F, 1);
if (!filter->cvDistImage) {
GST_WARNING ("Couldn't create dist image.");
}
}
if (filter->cvTemplateImage) {
gst_templatematch_match(filter->cvImage, filter->cvTemplateImage,
- filter->cvDistImage, &best_res, &best_pos, CV_TM_CCORR);
+ filter->cvDistImage, &best_res, &best_pos, filter->method);
GstStructure *s = gst_structure_new ("template_match",
"x", G_TYPE_UINT, best_pos.x,
"y", G_TYPE_UINT, best_pos.y,
"width", G_TYPE_UINT, filter->cvTemplateImage->width,
"height", G_TYPE_UINT, filter->cvTemplateImage->height,
"result", G_TYPE_DOUBLE, best_res,
NULL);
GstMessage *m = gst_message_new_element (GST_OBJECT (filter), s);
gst_element_post_message (GST_ELEMENT (filter), m);
if (filter->display) {
CvPoint corner = best_pos;
corner.x += filter->cvTemplateImage->width;
corner.y += filter->cvTemplateImage->height;
cvRectangle(filter->cvImage, best_pos, corner, CV_RGB(255, 32, 32), 3, 8, 0);
}
}
gst_buffer_set_data(buf, filter->cvImage->imageData, filter->cvImage->imageSize);
return gst_pad_push (filter->srcpad, buf);
}
static void gst_templatematch_match(IplImage *input, IplImage *template,
IplImage *dist_image, double *best_res, CvPoint *best_pos, int method)
{
double dist_min = 0, dist_max = 0;
CvPoint min_pos, max_pos;
cvMatchTemplate(input, template, dist_image, method);
cvMinMaxLoc(dist_image, &dist_min, &dist_max, &min_pos, &max_pos, NULL);
if ((CV_TM_SQDIFF_NORMED == method) || (CV_TM_SQDIFF == method))
{
*best_res = dist_min;
*best_pos = min_pos;
if (CV_TM_SQDIFF_NORMED == method) {
*best_res = 1-*best_res;
}
}
else {
*best_res = dist_max;
*best_pos = max_pos;
}
}
-static void gst_templatematch_load_template(GObject * object) {
- GstTemplateMatch *filter = GST_TEMPLATEMATCH (object);
-
+static void gst_templatematch_load_template(GstTemplateMatch *filter) {
if (filter->template) {
filter->cvTemplateImage = cvLoadImage(filter->template, CV_LOAD_IMAGE_COLOR);
if (!filter->cvTemplateImage) {
GST_WARNING ("Couldn't load template image: %s.", filter->template);
}
}
}
/* entry point to initialize the plug-in
* initialize the plug-in itself
* register the element factories and other features
*/
gboolean gst_templatematch_plugin_init (GstPlugin * templatematch)
{
/* debug category for fltering log messages */
GST_DEBUG_CATEGORY_INIT (gst_templatematch_debug, "templatematch",
0, "Performs template matching on videos and images, providing detected positions via bus messages");
return gst_element_register (templatematch, "templatematch", GST_RANK_NONE,
GST_TYPE_TEMPLATEMATCH);
}
diff --git a/src/templatematch/gsttemplatematch.h b/src/templatematch/gsttemplatematch.h
index cb2d166..35b001d 100644
--- a/src/templatematch/gsttemplatematch.h
+++ b/src/templatematch/gsttemplatematch.h
@@ -1,94 +1,95 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2008 Michael Sheldon <mike@mikeasoft.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#ifndef __GST_TEMPLATEMATCH_H__
#define __GST_TEMPLATEMATCH_H__
#include <gst/gst.h>
#include <opencv/cv.h>
#include <opencv/highgui.h>
G_BEGIN_DECLS
/* #defines don't like whitespacey bits */
#define GST_TYPE_TEMPLATEMATCH \
(gst_templatematch_get_type())
#define GST_TEMPLATEMATCH(obj) \
(G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_TEMPLATEMATCH,GstTemplateMatch))
#define GST_TEMPLATEMATCH_CLASS(klass) \
(G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_TEMPLATEMATCH,GstTemplateMatchClass))
#define GST_IS_TEMPLATEMATCH(obj) \
(G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_TEMPLATEMATCH))
#define GST_IS_TEMPLATEMATCH_CLASS(klass) \
(G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_TEMPLATEMATCH))
typedef struct _GstTemplateMatch GstTemplateMatch;
typedef struct _GstTemplateMatchClass GstTemplateMatchClass;
struct _GstTemplateMatch
{
GstElement element;
GstPad *sinkpad, *srcpad;
+ gint method;
gboolean display;
gchar *template;
IplImage *cvImage, *cvGray, *cvTemplateImage, *cvDistImage;
};
struct _GstTemplateMatchClass
{
GstElementClass parent_class;
};
GType gst_templatematch_get_type (void);
gboolean gst_templatematch_plugin_init (GstPlugin * templatematch);
G_END_DECLS
#endif /* __GST_TEMPLATEMATCH_H__ */
|
Elleo/gst-opencv
|
d837737abc9809f607f8b9412937cc4d5a3ca2a7
|
Added templatematch element
|
diff --git a/configure.ac b/configure.ac
index 90c5c4b..8d1eb8c 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1,142 +1,142 @@
AC_INIT
dnl versions of gstreamer and plugins-base
GST_MAJORMINOR=0.10
GST_REQUIRED=0.10.0
GSTPB_REQUIRED=0.10.0
dnl fill in your package name and version here
dnl the fourth (nano) number should be 0 for a release, 1 for CVS,
dnl and 2... for a prerelease
dnl when going to/from release please set the nano correctly !
dnl releases only do Wall, cvs and prerelease does Werror too
AS_VERSION(gst-opencv, GST_PLUGIN_VERSION, 0, 10, 0, 1,
GST_PLUGIN_CVS="no", GST_PLUGIN_CVS="yes")
dnl AM_MAINTAINER_MODE provides the option to enable maintainer mode
AM_MAINTAINER_MODE
AM_INIT_AUTOMAKE($PACKAGE, $VERSION)
dnl make aclocal work in maintainer mode
AC_SUBST(ACLOCAL_AMFLAGS, "-I m4")
AM_CONFIG_HEADER(config.h)
dnl check for tools
AC_PROG_CC
AC_PROG_LIBTOOL
dnl decide on error flags
AS_COMPILER_FLAG(-Wall, GST_WALL="yes", GST_WALL="no")
if test "x$GST_WALL" = "xyes"; then
GST_ERROR="$GST_ERROR -Wall"
# if test "x$GST_PLUGIN_CVS" = "xyes"; then
# AS_COMPILER_FLAG(-Werror,GST_ERROR="$GST_ERROR -Werror",GST_ERROR="$GST_ERROR")
# fi
fi
dnl Check for pkgconfig first
AC_CHECK_PROG(HAVE_PKGCONFIG, pkg-config, yes, no)
dnl Give error and exit if we don't have pkgconfig
if test "x$HAVE_PKGCONFIG" = "xno"; then
AC_MSG_ERROR(you need to have pkgconfig installed !)
fi
dnl Now we're ready to ask for gstreamer libs and cflags
dnl And we can also ask for the right version of gstreamer
PKG_CHECK_MODULES(GST, \
gstreamer-$GST_MAJORMINOR >= $GST_REQUIRED,
HAVE_GST=yes,HAVE_GST=no)
dnl Give error and exit if we don't have gstreamer
if test "x$HAVE_GST" = "xno"; then
AC_MSG_ERROR(you need gstreamer development packages installed !)
fi
dnl append GST_ERROR cflags to GST_CFLAGS
GST_CFLAGS="$GST_CFLAGS $GST_ERROR"
dnl make GST_CFLAGS and GST_LIBS available
AC_SUBST(GST_CFLAGS)
AC_SUBST(GST_LIBS)
dnl make GST_MAJORMINOR available in Makefile.am
AC_SUBST(GST_MAJORMINOR)
dnl If we need them, we can also use the base class libraries
PKG_CHECK_MODULES(GST_BASE, gstreamer-base-$GST_MAJORMINOR >= $GST_REQUIRED,
HAVE_GST_BASE=yes, HAVE_GST_BASE=no)
dnl Give a warning if we don't have gstreamer libs
dnl you can turn this into an error if you need them
if test "x$HAVE_GST_BASE" = "xno"; then
AC_MSG_NOTICE(no GStreamer base class libraries found (gstreamer-base-$GST_MAJORMINOR))
fi
dnl make _CFLAGS and _LIBS available
AC_SUBST(GST_BASE_CFLAGS)
AC_SUBST(GST_BASE_LIBS)
PKG_CHECK_MODULES(OPENCV,
opencv,
HAVE_OPENCV=yes, HAVE_OPENCV=no)
AC_SUBST(OPENCV_CFLAGS)
AC_SUBST(OPENCV_LIBS)
if test "x$HAVE_OPENCV" = "xno"; then
AC_MSG_ERROR(OpenCV libraries could not be found)
fi
dnl If we need them, we can also use the gstreamer-plugins-base libraries
PKG_CHECK_MODULES(GSTPB_BASE,
gstreamer-plugins-base-$GST_MAJORMINOR >= $GSTPB_REQUIRED,
HAVE_GSTPB_BASE=yes, HAVE_GSTPB_BASE=no)
dnl Give a warning if we don't have gstreamer libs
dnl you can turn this into an error if you need them
if test "x$HAVE_GSTPB_BASE" = "xno"; then
AC_MSG_NOTICE(no GStreamer Plugins Base libraries found (gstreamer-plugins-base-$GST_MAJORMINOR))
fi
dnl make _CFLAGS and _LIBS available
AC_SUBST(GSTPB_BASE_CFLAGS)
AC_SUBST(GSTPB_BASE_LIBS)
dnl If we need them, we can also use the gstreamer-controller libraries
PKG_CHECK_MODULES(GSTCTRL,
gstreamer-controller-$GST_MAJORMINOR >= $GSTPB_REQUIRED,
HAVE_GSTCTRL=yes, HAVE_GSTCTRL=no)
dnl Give a warning if we don't have gstreamer-controller
dnl you can turn this into an error if you need them
if test "x$HAVE_GSTCTRL" = "xno"; then
AC_MSG_NOTICE(no GStreamer Controller libraries found (gstreamer-controller-$GST_MAJORMINOR))
fi
dnl make _CFLAGS and _LIBS available
AC_SUBST(GSTCTRL_CFLAGS)
AC_SUBST(GSTCTRL_LIBS)
dnl set the plugindir where plugins should be installed
if test "x${prefix}" = "x$HOME"; then
plugindir="$HOME/.gstreamer-$GST_MAJORMINOR/plugins"
else
plugindir="\$(libdir)/gstreamer-$GST_MAJORMINOR"
fi
AC_SUBST(plugindir)
dnl set proper LDFLAGS for plugins
GST_PLUGIN_LDFLAGS='-module -avoid-version -export-symbols-regex [_]*\(gst_\|Gst\|GST_\).*'
AC_SUBST(GST_PLUGIN_LDFLAGS)
-AC_OUTPUT(Makefile m4/Makefile src/Makefile src/edgedetect/Makefile src/pyramidsegment/Makefile src/facedetect/Makefile)
+AC_OUTPUT(Makefile m4/Makefile src/Makefile src/edgedetect/Makefile src/pyramidsegment/Makefile src/facedetect/Makefile src/templatematch/Makefile)
diff --git a/src/Makefile.am b/src/Makefile.am
index aa412a4..6baf742 100644
--- a/src/Makefile.am
+++ b/src/Makefile.am
@@ -1,30 +1,33 @@
-SUBDIRS = edgedetect facedetect pyramidsegment
+SUBDIRS = edgedetect facedetect pyramidsegment templatematch
# plugindir is set in configure
plugin_LTLIBRARIES = libgstopencv.la
# sources used to compile this plug-in
libgstopencv_la_SOURCES = gstopencv.c
# flags used to compile this facedetect
# add other _CFLAGS and _LIBS as needed
libgstopencv_la_CFLAGS = $(GST_CFLAGS) $(OPENCV_CFLAGS) \
-I${top_srcdir}/src/edgedetect \
-I${top_srcdir}/src/facedetect \
- -I${top_srcdir}/src/pyramidsegment
+ -I${top_srcdir}/src/pyramidsegment \
+ -I${top_srcdir}/src/templatematch
libgstopencv_la_LIBADD = $(GST_LIBS) $(OPENCV_LIBS) \
$(top_builddir)/src/edgedetect/libgstedgedetect.la \
$(top_builddir)/src/facedetect/libgstfacedetect.la \
- $(top_builddir)/src/pyramidsegment/libgstpyramidsegment.la
+ $(top_builddir)/src/pyramidsegment/libgstpyramidsegment.la \
+ $(top_builddir)/src/templatematch/libgsttemplatematch.la
libgstopencv_la_LDFLAGS = $(GST_PLUGIN_LDFLAGS)
libgstopencv_la_DEPENDENCIES = \
$(top_builddir)/src/edgedetect/libgstedgedetect.la \
$(top_builddir)/src/facedetect/libgstfacedetect.la \
- $(top_builddir)/src/pyramidsegment/libgstpyramidsegment.la
+ $(top_builddir)/src/pyramidsegment/libgstpyramidsegment.la \
+ $(top_builddir)/src/templatematch/libgsttemplatematch.la
# headers we need but don't want installed
noinst_HEADERS =
diff --git a/src/gstopencv.c b/src/gstopencv.c
index 8c03647..6cf2676 100644
--- a/src/gstopencv.c
+++ b/src/gstopencv.c
@@ -1,50 +1,54 @@
/* GStreamer
* Copyright (C) <2009> Kapil Agrawal <kapil@mediamagictechnologies.com>
*
* gstopencv.c: plugin registering
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "gstedgedetect.h"
#include "gstfacedetect.h"
#include "gstpyramidsegment.h"
+#include "gsttemplatematch.h"
static gboolean
plugin_init (GstPlugin * plugin)
{
if (!gst_edgedetect_plugin_init (plugin))
return FALSE;
if (!gst_facedetect_plugin_init (plugin))
return FALSE;
if (!gst_pyramidsegment_plugin_init (plugin))
return FALSE;
+ if (!gst_templatematch_plugin_init (plugin))
+ return FALSE;
+
return TRUE;
}
GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
GST_VERSION_MINOR,
"opencv",
"GStreamer OpenCV Plugins",
plugin_init, VERSION, "LGPL", "OpenCv", "http://opencv.willowgarage.com")
diff --git a/src/templatematch/Makefile.am b/src/templatematch/Makefile.am
new file mode 100644
index 0000000..af80703
--- /dev/null
+++ b/src/templatematch/Makefile.am
@@ -0,0 +1,15 @@
+# plugindir is set in configure
+
+noinst_LTLIBRARIES = libgsttemplatematch.la
+
+# sources used to compile this plug-in
+libgsttemplatematch_la_SOURCES = gsttemplatematch.c
+
+# flags used to compile this templatematch
+# add other _CFLAGS and _LIBS as needed
+libgsttemplatematch_la_CFLAGS = $(GST_CFLAGS) $(OPENCV_CFLAGS)
+libgsttemplatematch_la_LIBADD = $(GST_LIBS) $(OPENCV_LIBS)
+libgsttemplatematch_la_LDFLAGS = $(GST_PLUGIN_LDFLAGS)
+
+# headers we need but don't want installed
+noinst_HEADERS = gsttemplatematch.h
diff --git a/src/templatematch/gsttemplatematch.c b/src/templatematch/gsttemplatematch.c
new file mode 100644
index 0000000..b9f5779
--- /dev/null
+++ b/src/templatematch/gsttemplatematch.c
@@ -0,0 +1,379 @@
+/*
+ * GStreamer
+ * Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
+ * Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
+ * Copyright (C) 2008 Michael Sheldon <mike@mikeasoft.com>
+ * Copyright (C) 2009 Noam Lewis <jones.noamle@gmail.com>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ * Alternatively, the contents of this file may be used under the
+ * GNU Lesser General Public License Version 2.1 (the "LGPL"), in
+ * which case the following provisions apply instead of the ones
+ * mentioned above:
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+/**
+ * SECTION:element-templatematch
+ *
+ * FIXME:Describe templatematch here.
+ *
+ * <refsect2>
+ * <title>Example launch line</title>
+ * |[
+ * gst-launch-0.10 videotestsrc ! decodebin ! ffmpegcolorspace ! templatematch ! ffmpegcolorspace ! xvimagesink
+ * ]|
+ * </refsect2>
+ */
+
+#ifdef HAVE_CONFIG_H
+# include <config.h>
+#endif
+
+#include <gst/gst.h>
+
+#include "gsttemplatematch.h"
+
+GST_DEBUG_CATEGORY_STATIC (gst_templatematch_debug);
+#define GST_CAT_DEFAULT gst_templatematch_debug
+
+#define DEFAULT_TEMPLATE NULL
+
+/* Filter signals and args */
+enum
+{
+ /* FILL ME */
+ LAST_SIGNAL
+};
+
+enum
+{
+ PROP_0,
+ PROP_DISPLAY,
+ PROP_TEMPLATE
+};
+
+/* the capabilities of the inputs and outputs.
+ */
+static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
+ GST_PAD_SINK,
+ GST_PAD_ALWAYS,
+ GST_STATIC_CAPS (
+ "video/x-raw-rgb"
+ )
+ );
+
+static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
+ GST_PAD_SRC,
+ GST_PAD_ALWAYS,
+ GST_STATIC_CAPS (
+ "video/x-raw-rgb"
+ )
+ );
+
+GST_BOILERPLATE (GstTemplateMatch, gst_templatematch, GstElement,
+ GST_TYPE_ELEMENT);
+
+static void gst_templatematch_finalize (GObject * object);
+static void gst_templatematch_set_property (GObject * object, guint prop_id,
+ const GValue * value, GParamSpec * pspec);
+static void gst_templatematch_get_property (GObject * object, guint prop_id,
+ GValue * value, GParamSpec * pspec);
+
+static gboolean gst_templatematch_set_caps (GstPad * pad, GstCaps * caps);
+static GstFlowReturn gst_templatematch_chain (GstPad * pad, GstBuffer * buf);
+
+static void gst_templatematch_load_template (GObject * object);
+static void gst_templatematch_match(IplImage *input, IplImage *template,
+ IplImage *dist_image, double *best_res, CvPoint *best_pos, int method);
+
+/* GObject vmethod implementations */
+
+static void
+gst_templatematch_base_init (gpointer gclass)
+{
+ GstElementClass *element_class = GST_ELEMENT_CLASS (gclass);
+
+ gst_element_class_set_details_simple(element_class,
+ "templatematch",
+ "Filter/Effect/Video",
+ "Performs template matching on videos and images, providing detected positions via bus messages",
+ "Noam Lewis <jones.noamle@gmail.com>");
+
+ gst_element_class_add_pad_template (element_class,
+ gst_static_pad_template_get (&src_factory));
+ gst_element_class_add_pad_template (element_class,
+ gst_static_pad_template_get (&sink_factory));
+}
+
+/* initialize the templatematch's class */
+static void
+gst_templatematch_class_init (GstTemplateMatchClass * klass)
+{
+ GObjectClass *gobject_class;
+ GstElementClass *gstelement_class;
+
+ gobject_class = (GObjectClass *) klass;
+ gstelement_class = (GstElementClass *) klass;
+
+ gobject_class->finalize = gst_templatematch_finalize;
+ gobject_class->set_property = gst_templatematch_set_property;
+ gobject_class->get_property = gst_templatematch_get_property;
+
+ g_object_class_install_property (gobject_class, PROP_DISPLAY,
+ g_param_spec_boolean ("display", "Display", "Sets whether the detected template should be highlighted in the output",
+ TRUE, G_PARAM_READWRITE));
+ g_object_class_install_property (gobject_class, PROP_TEMPLATE,
+ g_param_spec_string ("template", "Template", "Filename of template image",
+ DEFAULT_TEMPLATE, G_PARAM_READWRITE));
+}
+
+/* initialize the new element
+ * instantiate pads and add them to element
+ * set pad calback functions
+ * initialize instance structure
+ */
+static void
+gst_templatematch_init (GstTemplateMatch * filter,
+ GstTemplateMatchClass * gclass)
+{
+ filter->sinkpad = gst_pad_new_from_static_template (&sink_factory, "sink");
+ gst_pad_set_setcaps_function (filter->sinkpad,
+ GST_DEBUG_FUNCPTR(gst_templatematch_set_caps));
+ gst_pad_set_getcaps_function (filter->sinkpad,
+ GST_DEBUG_FUNCPTR(gst_pad_proxy_getcaps));
+ gst_pad_set_chain_function (filter->sinkpad,
+ GST_DEBUG_FUNCPTR(gst_templatematch_chain));
+
+ filter->srcpad = gst_pad_new_from_static_template (&src_factory, "src");
+ gst_pad_set_getcaps_function (filter->srcpad,
+ GST_DEBUG_FUNCPTR(gst_pad_proxy_getcaps));
+
+ gst_element_add_pad (GST_ELEMENT (filter), filter->sinkpad);
+ gst_element_add_pad (GST_ELEMENT (filter), filter->srcpad);
+ filter->template = DEFAULT_TEMPLATE;
+ filter->display = TRUE;
+ filter->cvTemplateImage = NULL;
+ filter->cvDistImage = NULL;
+ filter->cvImage = NULL;
+ gst_templatematch_load_template(filter);
+}
+
+static void
+gst_templatematch_set_property (GObject * object, guint prop_id,
+ const GValue * value, GParamSpec * pspec)
+{
+ GstTemplateMatch *filter = GST_TEMPLATEMATCH (object);
+
+ switch (prop_id) {
+ case PROP_TEMPLATE:
+ filter->template = g_value_get_string (value);
+ gst_templatematch_load_template(filter);
+ break;
+ case PROP_DISPLAY:
+ filter->display = g_value_get_boolean (value);
+ break;
+ default:
+ G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
+ break;
+ }
+}
+
+static void
+gst_templatematch_get_property (GObject * object, guint prop_id,
+ GValue * value, GParamSpec * pspec)
+{
+ GstTemplateMatch *filter = GST_TEMPLATEMATCH (object);
+
+ switch (prop_id) {
+ case PROP_TEMPLATE:
+ g_value_set_string (value, filter->template);
+ break;
+ case PROP_DISPLAY:
+ g_value_set_boolean (value, filter->display);
+ break;
+ default:
+ G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
+ break;
+ }
+}
+
+/* GstElement vmethod implementations */
+
+/* this function handles the link with other elements */
+static gboolean
+gst_templatematch_set_caps (GstPad * pad, GstCaps * caps)
+{
+ GstTemplateMatch *filter;
+ GstPad *otherpad;
+ gint width, height;
+ GstStructure *structure;
+
+ filter = GST_TEMPLATEMATCH (gst_pad_get_parent (pad));
+ structure = gst_caps_get_structure (caps, 0);
+ gst_structure_get_int (structure, "width", &width);
+ gst_structure_get_int (structure, "height", &height);
+
+ filter->cvImage = cvCreateImageHeader(cvSize(width, height), IPL_DEPTH_8U, 3);
+
+ otherpad = (pad == filter->srcpad) ? filter->sinkpad : filter->srcpad;
+ gst_object_unref (filter);
+
+ return gst_pad_set_caps (otherpad, caps);
+}
+
+static void gst_templatematch_finalize (GObject * object)
+{
+ GstTemplateMatch *filter;
+ filter = GST_TEMPLATEMATCH (object);
+
+ if (filter->cvImage) {
+ cvReleaseImageHeader(&filter->cvImage);
+ }
+ if (filter->cvDistImage) {
+ cvReleaseImage(&filter->cvDistImage);
+ }
+ if (filter->cvTemplateImage) {
+ cvReleaseImage(&filter->cvTemplateImage);
+ }
+}
+
+/* chain function
+ * this function does the actual processing
+ */
+static GstFlowReturn
+gst_templatematch_chain (GstPad * pad, GstBuffer * buf)
+{
+ GstTemplateMatch *filter;
+ CvPoint best_pos;
+ double best_res;
+ int i;
+
+ filter = GST_TEMPLATEMATCH (GST_OBJECT_PARENT (pad));
+ buf = gst_buffer_make_writable(buf);
+ if ((!filter) || (!buf)) {
+ return GST_FLOW_OK;
+ }
+ filter->cvImage->imageData = (char *) GST_BUFFER_DATA (buf);
+
+
+ if (!filter->cvDistImage) {
+ filter->cvDistImage = cvCreateImage( cvSize(filter->cvImage->width - filter->cvTemplateImage->width + 1,
+ filter->cvImage->height - filter->cvTemplateImage->height + 1),
+ IPL_DEPTH_32F, 1);
+ if (!filter->cvDistImage) {
+ GST_WARNING ("Couldn't create dist image.");
+ }
+ }
+ if (filter->cvTemplateImage) {
+ gst_templatematch_match(filter->cvImage, filter->cvTemplateImage,
+ filter->cvDistImage, &best_res, &best_pos, CV_TM_CCORR);
+
+ GstStructure *s = gst_structure_new ("template_match",
+ "x", G_TYPE_UINT, best_pos.x,
+ "y", G_TYPE_UINT, best_pos.y,
+ "width", G_TYPE_UINT, filter->cvTemplateImage->width,
+ "height", G_TYPE_UINT, filter->cvTemplateImage->height,
+ "result", G_TYPE_DOUBLE, best_res,
+ NULL);
+
+ GstMessage *m = gst_message_new_element (GST_OBJECT (filter), s);
+ gst_element_post_message (GST_ELEMENT (filter), m);
+
+ if (filter->display) {
+ CvPoint corner = best_pos;
+ corner.x += filter->cvTemplateImage->width;
+ corner.y += filter->cvTemplateImage->height;
+ cvRectangle(filter->cvImage, best_pos, corner, CV_RGB(255, 32, 32), 3, 8, 0);
+ }
+
+ }
+
+
+ gst_buffer_set_data(buf, filter->cvImage->imageData, filter->cvImage->imageSize);
+
+ return gst_pad_push (filter->srcpad, buf);
+}
+
+
+
+static void gst_templatematch_match(IplImage *input, IplImage *template,
+ IplImage *dist_image, double *best_res, CvPoint *best_pos, int method)
+{
+ double dist_min = 0, dist_max = 0;
+ CvPoint min_pos, max_pos;
+ cvMatchTemplate(input, template, dist_image, method);
+ cvMinMaxLoc(dist_image, &dist_min, &dist_max, &min_pos, &max_pos, NULL);
+ if ((CV_TM_SQDIFF_NORMED == method) || (CV_TM_SQDIFF == method))
+ {
+ *best_res = dist_min;
+ *best_pos = min_pos;
+ if (CV_TM_SQDIFF_NORMED == method) {
+ *best_res = 1-*best_res;
+ }
+ }
+ else {
+ *best_res = dist_max;
+ *best_pos = max_pos;
+ }
+}
+
+
+static void gst_templatematch_load_template(GObject * object) {
+ GstTemplateMatch *filter = GST_TEMPLATEMATCH (object);
+
+ if (filter->template) {
+ filter->cvTemplateImage = cvLoadImage(filter->template, CV_LOAD_IMAGE_COLOR);
+ if (!filter->cvTemplateImage) {
+ GST_WARNING ("Couldn't load template image: %s.", filter->template);
+ }
+ }
+}
+
+
+/* entry point to initialize the plug-in
+ * initialize the plug-in itself
+ * register the element factories and other features
+ */
+gboolean gst_templatematch_plugin_init (GstPlugin * templatematch)
+{
+ /* debug category for fltering log messages */
+ GST_DEBUG_CATEGORY_INIT (gst_templatematch_debug, "templatematch",
+ 0, "Performs template matching on videos and images, providing detected positions via bus messages");
+
+ return gst_element_register (templatematch, "templatematch", GST_RANK_NONE,
+ GST_TYPE_TEMPLATEMATCH);
+}
+
+
diff --git a/src/templatematch/gsttemplatematch.h b/src/templatematch/gsttemplatematch.h
new file mode 100644
index 0000000..cb2d166
--- /dev/null
+++ b/src/templatematch/gsttemplatematch.h
@@ -0,0 +1,94 @@
+/*
+ * GStreamer
+ * Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
+ * Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
+ * Copyright (C) 2008 Michael Sheldon <mike@mikeasoft.com>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ * Alternatively, the contents of this file may be used under the
+ * GNU Lesser General Public License Version 2.1 (the "LGPL"), in
+ * which case the following provisions apply instead of the ones
+ * mentioned above:
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+#ifndef __GST_TEMPLATEMATCH_H__
+#define __GST_TEMPLATEMATCH_H__
+
+#include <gst/gst.h>
+#include <opencv/cv.h>
+#include <opencv/highgui.h>
+
+G_BEGIN_DECLS
+
+/* #defines don't like whitespacey bits */
+#define GST_TYPE_TEMPLATEMATCH \
+ (gst_templatematch_get_type())
+#define GST_TEMPLATEMATCH(obj) \
+ (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_TEMPLATEMATCH,GstTemplateMatch))
+#define GST_TEMPLATEMATCH_CLASS(klass) \
+ (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_TEMPLATEMATCH,GstTemplateMatchClass))
+#define GST_IS_TEMPLATEMATCH(obj) \
+ (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_TEMPLATEMATCH))
+#define GST_IS_TEMPLATEMATCH_CLASS(klass) \
+ (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_TEMPLATEMATCH))
+
+typedef struct _GstTemplateMatch GstTemplateMatch;
+typedef struct _GstTemplateMatchClass GstTemplateMatchClass;
+
+struct _GstTemplateMatch
+{
+ GstElement element;
+
+ GstPad *sinkpad, *srcpad;
+
+ gboolean display;
+
+ gchar *template;
+
+ IplImage *cvImage, *cvGray, *cvTemplateImage, *cvDistImage;
+};
+
+struct _GstTemplateMatchClass
+{
+ GstElementClass parent_class;
+};
+
+GType gst_templatematch_get_type (void);
+
+gboolean gst_templatematch_plugin_init (GstPlugin * templatematch);
+
+G_END_DECLS
+
+#endif /* __GST_TEMPLATEMATCH_H__ */
|
Elleo/gst-opencv
|
29bf3319e88791be4c3d349c786876185f02f7fc
|
Added debian dir for building a .deb
|
diff --git a/debian/changelog b/debian/changelog
new file mode 100644
index 0000000..990d1b0
--- /dev/null
+++ b/debian/changelog
@@ -0,0 +1,5 @@
+gst-opencv (0.5-1) jaunty; urgency=low
+
+ * Initial release (Closes: #nnnn) <nnnn is the bug number of your ITP>
+
+ -- Noam Lewis <jones.noamle@gmail.com> Mon, 27 Apr 2009 23:26:11 +0300
diff --git a/debian/compat b/debian/compat
new file mode 100644
index 0000000..7f8f011
--- /dev/null
+++ b/debian/compat
@@ -0,0 +1 @@
+7
diff --git a/debian/control b/debian/control
new file mode 100644
index 0000000..9505fff
--- /dev/null
+++ b/debian/control
@@ -0,0 +1,13 @@
+Source: gst-opencv
+Section: unknown
+Priority: extra
+Maintainer: Noam Lewis <jones.noamle@gmail.com>
+Build-Depends: debhelper (>= 7), libcv-dev, libgstreamer-plugins-base0.10-dev,
+Standards-Version: 3.8.0
+Homepage: https://launchpad.net/gst-opencv
+
+Package: gst-opencv
+Architecture: any
+Depends: ${shlibs:Depends}, ${misc:Depends}, libcv1, gstreamer0.10-plugins-base
+Description: Gstreamer plugins using opencv
+ A collection of Gstreamer plugins making computer vision techniques from OpenCV available to Gstreamer based applications.
diff --git a/debian/copyright b/debian/copyright
new file mode 100644
index 0000000..e167141
--- /dev/null
+++ b/debian/copyright
@@ -0,0 +1,23 @@
+This package was debianized by Noam Lewis <jones.noamle@gmail.com> on
+Mon, 27 Apr 2009 23:26:11 +0300.
+
+It was downloaded from <https://launchpad.net/gst-opencv>
+
+Upstream Author(s):
+
+ <put author's name and email here>
+ <likewise for another author>
+
+Copyright:
+
+ <Copyright (C) YYYY 2009 Noam Lewis>
+
+License:
+
+ <Put the license of the package here indented by 4 spaces>
+
+The Debian packaging is copyright 2009, Noam <jones.noamle@gmail.com> and
+is licensed under the GPL, see `/usr/share/common-licenses/GPL'.
+
+# Please also look if there are files or directories which have a
+# different copyright/license attached and list them here.
diff --git a/debian/cron.d.ex b/debian/cron.d.ex
new file mode 100644
index 0000000..0a0a9d9
--- /dev/null
+++ b/debian/cron.d.ex
@@ -0,0 +1,4 @@
+#
+# Regular cron jobs for the gst-opencv package
+#
+0 4 * * * root [ -x /usr/bin/gst-opencv_maintenance ] && /usr/bin/gst-opencv_maintenance
diff --git a/debian/dirs b/debian/dirs
new file mode 100644
index 0000000..ca882bb
--- /dev/null
+++ b/debian/dirs
@@ -0,0 +1,2 @@
+usr/bin
+usr/sbin
diff --git a/debian/docs b/debian/docs
new file mode 100644
index 0000000..50bd824
--- /dev/null
+++ b/debian/docs
@@ -0,0 +1,2 @@
+NEWS
+README
diff --git a/debian/manpage.1.ex b/debian/manpage.1.ex
new file mode 100644
index 0000000..e9d9588
--- /dev/null
+++ b/debian/manpage.1.ex
@@ -0,0 +1,59 @@
+.\" Hey, EMACS: -*- nroff -*-
+.\" First parameter, NAME, should be all caps
+.\" Second parameter, SECTION, should be 1-8, maybe w/ subsection
+.\" other parameters are allowed: see man(7), man(1)
+.TH GST-OPENCV SECTION "April 27, 2009"
+.\" Please adjust this date whenever revising the manpage.
+.\"
+.\" Some roff macros, for reference:
+.\" .nh disable hyphenation
+.\" .hy enable hyphenation
+.\" .ad l left justify
+.\" .ad b justify to both left and right margins
+.\" .nf disable filling
+.\" .fi enable filling
+.\" .br insert line break
+.\" .sp <n> insert n+1 empty lines
+.\" for manpage-specific macros, see man(7)
+.SH NAME
+gst-opencv \- program to do something
+.SH SYNOPSIS
+.B gst-opencv
+.RI [ options ] " files" ...
+.br
+.B bar
+.RI [ options ] " files" ...
+.SH DESCRIPTION
+This manual page documents briefly the
+.B gst-opencv
+and
+.B bar
+commands.
+.PP
+.\" TeX users may be more comfortable with the \fB<whatever>\fP and
+.\" \fI<whatever>\fP escape sequences to invode bold face and italics,
+.\" respectively.
+\fBgst-opencv\fP is a program that...
+.SH OPTIONS
+These programs follow the usual GNU command line syntax, with long
+options starting with two dashes (`-').
+A summary of options is included below.
+For a complete description, see the Info files.
+.TP
+.B \-h, \-\-help
+Show summary of options.
+.TP
+.B \-v, \-\-version
+Show version of program.
+.SH SEE ALSO
+.BR bar (1),
+.BR baz (1).
+.br
+The programs are documented fully by
+.IR "The Rise and Fall of a Fooish Bar" ,
+available via the Info system.
+.SH AUTHOR
+gst-opencv was written by <upstream author>.
+.PP
+This manual page was written by Noam <jones.noamle@gmail.com>,
+for the Debian project (and may be used by others).
diff --git a/debian/manpage.sgml.ex b/debian/manpage.sgml.ex
new file mode 100644
index 0000000..96e1e87
--- /dev/null
+++ b/debian/manpage.sgml.ex
@@ -0,0 +1,154 @@
+<!doctype refentry PUBLIC "-//OASIS//DTD DocBook V4.1//EN" [
+
+<!-- Process this file with docbook-to-man to generate an nroff manual
+ page: `docbook-to-man manpage.sgml > manpage.1'. You may view
+ the manual page with: `docbook-to-man manpage.sgml | nroff -man |
+ less'. A typical entry in a Makefile or Makefile.am is:
+
+manpage.1: manpage.sgml
+ docbook-to-man $< > $@
+
+
+ The docbook-to-man binary is found in the docbook-to-man package.
+ Please remember that if you create the nroff version in one of the
+ debian/rules file targets (such as build), you will need to include
+ docbook-to-man in your Build-Depends control field.
+
+ -->
+
+ <!-- Fill in your name for FIRSTNAME and SURNAME. -->
+ <!ENTITY dhfirstname "<firstname>FIRSTNAME</firstname>">
+ <!ENTITY dhsurname "<surname>SURNAME</surname>">
+ <!-- Please adjust the date whenever revising the manpage. -->
+ <!ENTITY dhdate "<date>April 27, 2009</date>">
+ <!-- SECTION should be 1-8, maybe w/ subsection other parameters are
+ allowed: see man(7), man(1). -->
+ <!ENTITY dhsection "<manvolnum>SECTION</manvolnum>">
+ <!ENTITY dhemail "<email>jones.noamle@gmail.com</email>">
+ <!ENTITY dhusername "Noam">
+ <!ENTITY dhucpackage "<refentrytitle>GST-OPENCV</refentrytitle>">
+ <!ENTITY dhpackage "gst-opencv">
+
+ <!ENTITY debian "<productname>Debian</productname>">
+ <!ENTITY gnu "<acronym>GNU</acronym>">
+ <!ENTITY gpl "&gnu; <acronym>GPL</acronym>">
+]>
+
+<refentry>
+ <refentryinfo>
+ <address>
+ &dhemail;
+ </address>
+ <author>
+ &dhfirstname;
+ &dhsurname;
+ </author>
+ <copyright>
+ <year>2003</year>
+ <holder>&dhusername;</holder>
+ </copyright>
+ &dhdate;
+ </refentryinfo>
+ <refmeta>
+ &dhucpackage;
+
+ &dhsection;
+ </refmeta>
+ <refnamediv>
+ <refname>&dhpackage;</refname>
+
+ <refpurpose>program to do something</refpurpose>
+ </refnamediv>
+ <refsynopsisdiv>
+ <cmdsynopsis>
+ <command>&dhpackage;</command>
+
+ <arg><option>-e <replaceable>this</replaceable></option></arg>
+
+ <arg><option>--example <replaceable>that</replaceable></option></arg>
+ </cmdsynopsis>
+ </refsynopsisdiv>
+ <refsect1>
+ <title>DESCRIPTION</title>
+
+ <para>This manual page documents briefly the
+ <command>&dhpackage;</command> and <command>bar</command>
+ commands.</para>
+
+ <para>This manual page was written for the &debian; distribution
+ because the original program does not have a manual page.
+ Instead, it has documentation in the &gnu;
+ <application>Info</application> format; see below.</para>
+
+ <para><command>&dhpackage;</command> is a program that...</para>
+
+ </refsect1>
+ <refsect1>
+ <title>OPTIONS</title>
+
+ <para>These programs follow the usual &gnu; command line syntax,
+ with long options starting with two dashes (`-'). A summary of
+ options is included below. For a complete description, see the
+ <application>Info</application> files.</para>
+
+ <variablelist>
+ <varlistentry>
+ <term><option>-h</option>
+ <option>--help</option>
+ </term>
+ <listitem>
+ <para>Show summary of options.</para>
+ </listitem>
+ </varlistentry>
+ <varlistentry>
+ <term><option>-v</option>
+ <option>--version</option>
+ </term>
+ <listitem>
+ <para>Show version of program.</para>
+ </listitem>
+ </varlistentry>
+ </variablelist>
+ </refsect1>
+ <refsect1>
+ <title>SEE ALSO</title>
+
+ <para>bar (1), baz (1).</para>
+
+ <para>The programs are documented fully by <citetitle>The Rise and
+ Fall of a Fooish Bar</citetitle> available via the
+ <application>Info</application> system.</para>
+ </refsect1>
+ <refsect1>
+ <title>AUTHOR</title>
+
+ <para>This manual page was written by &dhusername; &dhemail; for
+ the &debian; system (and may be used by others). Permission is
+ granted to copy, distribute and/or modify this document under
+ the terms of the &gnu; General Public License, Version 2 any
+ later version published by the Free Software Foundation.
+ </para>
+ <para>
+ On Debian systems, the complete text of the GNU General Public
+ License can be found in /usr/share/common-licenses/GPL.
+ </para>
+
+ </refsect1>
+</refentry>
+
+<!-- Keep this comment at the end of the file
+Local variables:
+mode: sgml
+sgml-omittag:t
+sgml-shorttag:t
+sgml-minimize-attributes:nil
+sgml-always-quote-attributes:t
+sgml-indent-step:2
+sgml-indent-data:t
+sgml-parent-document:nil
+sgml-default-dtd-file:nil
+sgml-exposed-tags:nil
+sgml-local-catalogs:nil
+sgml-local-ecat-files:nil
+End:
+-->
diff --git a/debian/manpage.xml.ex b/debian/manpage.xml.ex
new file mode 100644
index 0000000..8fd666d
--- /dev/null
+++ b/debian/manpage.xml.ex
@@ -0,0 +1,291 @@
+<?xml version='1.0' encoding='UTF-8'?>
+<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN"
+"http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" [
+
+<!--
+
+`xsltproc -''-nonet \
+ -''-param man.charmap.use.subset "0" \
+ -''-param make.year.ranges "1" \
+ -''-param make.single.year.ranges "1" \
+ /usr/share/xml/docbook/stylesheet/nwalsh/manpages/docbook.xsl \
+ manpage.xml'
+
+A manual page <package>.<section> will be generated. You may view the
+manual page with: nroff -man <package>.<section> | less'. A typical entry
+in a Makefile or Makefile.am is:
+
+DB2MAN = /usr/share/sgml/docbook/stylesheet/xsl/nwalsh/manpages/docbook.xsl
+XP = xsltproc -''-nonet -''-param man.charmap.use.subset "0"
+
+manpage.1: manpage.xml
+ $(XP) $(DB2MAN) $<
+
+The xsltproc binary is found in the xsltproc package. The XSL files are in
+docbook-xsl. A description of the parameters you can use can be found in the
+docbook-xsl-doc-* packages. Please remember that if you create the nroff
+version in one of the debian/rules file targets (such as build), you will need
+to include xsltproc and docbook-xsl in your Build-Depends control field.
+Alternatively use the xmlto command/package. That will also automatically
+pull in xsltproc and docbook-xsl.
+
+Notes for using docbook2x: docbook2x-man does not automatically create the
+AUTHOR(S) and COPYRIGHT sections. In this case, please add them manually as
+<refsect1> ... </refsect1>.
+
+To disable the automatic creation of the AUTHOR(S) and COPYRIGHT sections
+read /usr/share/doc/docbook-xsl/doc/manpages/authors.html. This file can be
+found in the docbook-xsl-doc-html package.
+
+Validation can be done using: `xmllint -''-noout -''-valid manpage.xml`
+
+General documentation about man-pages and man-page-formatting:
+man(1), man(7), http://www.tldp.org/HOWTO/Man-Page/
+
+-->
+
+ <!-- Fill in your name for FIRSTNAME and SURNAME. -->
+ <!ENTITY dhfirstname "FIRSTNAME">
+ <!ENTITY dhsurname "SURNAME">
+ <!-- dhusername could also be set to "&firstname; &surname;". -->
+ <!ENTITY dhusername "Noam">
+ <!ENTITY dhemail "jones.noamle@gmail.com">
+ <!-- SECTION should be 1-8, maybe w/ subsection other parameters are
+ allowed: see man(7), man(1) and
+ http://www.tldp.org/HOWTO/Man-Page/q2.html. -->
+ <!ENTITY dhsection "SECTION">
+ <!-- TITLE should be something like "User commands" or similar (see
+ http://www.tldp.org/HOWTO/Man-Page/q2.html). -->
+ <!ENTITY dhtitle "gst-opencv User Manual">
+ <!ENTITY dhucpackage "GST-OPENCV">
+ <!ENTITY dhpackage "gst-opencv">
+]>
+
+<refentry>
+ <refentryinfo>
+ <title>&dhtitle;</title>
+ <productname>&dhpackage;</productname>
+ <authorgroup>
+ <author>
+ <firstname>&dhfirstname;</firstname>
+ <surname>&dhsurname;</surname>
+ <contrib>Wrote this manpage for the Debian system.</contrib>
+ <address>
+ <email>&dhemail;</email>
+ </address>
+ </author>
+ </authorgroup>
+ <copyright>
+ <year>2007</year>
+ <holder>&dhusername;</holder>
+ </copyright>
+ <legalnotice>
+ <para>This manual page was written for the Debian system
+ (and may be used by others).</para>
+ <para>Permission is granted to copy, distribute and/or modify this
+ document under the terms of the GNU General Public License,
+ Version 2 or (at your option) any later version published by
+ the Free Software Foundation.</para>
+ <para>On Debian systems, the complete text of the GNU General Public
+ License can be found in
+ <filename>/usr/share/common-licenses/GPL</filename>.</para>
+ </legalnotice>
+ </refentryinfo>
+ <refmeta>
+ <refentrytitle>&dhucpackage;</refentrytitle>
+ <manvolnum>&dhsection;</manvolnum>
+ </refmeta>
+ <refnamediv>
+ <refname>&dhpackage;</refname>
+ <refpurpose>program to do something</refpurpose>
+ </refnamediv>
+ <refsynopsisdiv>
+ <cmdsynopsis>
+ <command>&dhpackage;</command>
+ <!-- These are several examples, how syntaxes could look -->
+ <arg choice="plain"><option>-e <replaceable>this</replaceable></option></arg>
+ <arg choice="opt"><option>--example=<parameter>that</parameter></option></arg>
+ <arg choice="opt">
+ <group choice="req">
+ <arg choice="plain"><option>-e</option></arg>
+ <arg choice="plain"><option>--example</option></arg>
+ </group>
+ <replaceable class="option">this</replaceable>
+ </arg>
+ <arg choice="opt">
+ <group choice="req">
+ <arg choice="plain"><option>-e</option></arg>
+ <arg choice="plain"><option>--example</option></arg>
+ </group>
+ <group choice="req">
+ <arg choice="plain"><replaceable>this</replaceable></arg>
+ <arg choice="plain"><replaceable>that</replaceable></arg>
+ </group>
+ </arg>
+ </cmdsynopsis>
+ <cmdsynopsis>
+ <command>&dhpackage;</command>
+ <!-- Normally the help and version options make the programs stop
+ right after outputting the requested information. -->
+ <group choice="opt">
+ <arg choice="plain">
+ <group choice="req">
+ <arg choice="plain"><option>-h</option></arg>
+ <arg choice="plain"><option>--help</option></arg>
+ </group>
+ </arg>
+ <arg choice="plain">
+ <group choice="req">
+ <arg choice="plain"><option>-v</option></arg>
+ <arg choice="plain"><option>--version</option></arg>
+ </group>
+ </arg>
+ </group>
+ </cmdsynopsis>
+ </refsynopsisdiv>
+ <refsect1 id="description">
+ <title>DESCRIPTION</title>
+ <para>This manual page documents briefly the
+ <command>&dhpackage;</command> and <command>bar</command>
+ commands.</para>
+ <para>This manual page was written for the Debian distribution
+ because the original program does not have a manual page.
+ Instead, it has documentation in the GNU <citerefentry>
+ <refentrytitle>info</refentrytitle>
+ <manvolnum>1</manvolnum>
+ </citerefentry> format; see below.</para>
+ <para><command>&dhpackage;</command> is a program that...</para>
+ </refsect1>
+ <refsect1 id="options">
+ <title>OPTIONS</title>
+ <para>The program follows the usual GNU command line syntax,
+ with long options starting with two dashes (`-'). A summary of
+ options is included below. For a complete description, see the
+ <citerefentry>
+ <refentrytitle>info</refentrytitle>
+ <manvolnum>1</manvolnum>
+ </citerefentry> files.</para>
+ <variablelist>
+ <!-- Use the variablelist.term.separator and the
+ variablelist.term.break.after parameters to
+ control the term elements. -->
+ <varlistentry>
+ <term><option>-e <replaceable>this</replaceable></option></term>
+ <term><option>--example=<replaceable>that</replaceable></option></term>
+ <listitem>
+ <para>Does this and that.</para>
+ </listitem>
+ </varlistentry>
+ <varlistentry>
+ <term><option>-h</option></term>
+ <term><option>--help</option></term>
+ <listitem>
+ <para>Show summary of options.</para>
+ </listitem>
+ </varlistentry>
+ <varlistentry>
+ <term><option>-v</option></term>
+ <term><option>--version</option></term>
+ <listitem>
+ <para>Show version of program.</para>
+ </listitem>
+ </varlistentry>
+ </variablelist>
+ </refsect1>
+ <refsect1 id="files">
+ <title>FILES</title>
+ <variablelist>
+ <varlistentry>
+ <term><filename>/etc/foo.conf</filename></term>
+ <listitem>
+ <para>The system-wide configuration file to control the
+ behaviour of <application>&dhpackage;</application>. See
+ <citerefentry>
+ <refentrytitle>foo.conf</refentrytitle>
+ <manvolnum>5</manvolnum>
+ </citerefentry> for further details.</para>
+ </listitem>
+ </varlistentry>
+ <varlistentry>
+ <term><filename>${HOME}/.foo.conf</filename></term>
+ <listitem>
+ <para>The per-user configuration file to control the
+ behaviour of <application>&dhpackage;</application>. See
+ <citerefentry>
+ <refentrytitle>foo.conf</refentrytitle>
+ <manvolnum>5</manvolnum>
+ </citerefentry> for further details.</para>
+ </listitem>
+ </varlistentry>
+ </variablelist>
+ </refsect1>
+ <refsect1 id="environment">
+ <title>ENVIONMENT</title>
+ <variablelist>
+ <varlistentry>
+ <term><envar>FOO_CONF</envar></term>
+ <listitem>
+ <para>If used, the defined file is used as configuration
+ file (see also <xref linkend="files"/>).</para>
+ </listitem>
+ </varlistentry>
+ </variablelist>
+ </refsect1>
+ <refsect1 id="diagnostics">
+ <title>DIAGNOSTICS</title>
+ <para>The following diagnostics may be issued
+ on <filename class="devicefile">stderr</filename>:</para>
+ <variablelist>
+ <varlistentry>
+ <term><errortext>Bad configuration file. Exiting.</errortext></term>
+ <listitem>
+ <para>The configuration file seems to contain a broken configuration
+ line. Use the <option>--verbose</option> option, to get more info.
+ </para>
+ </listitem>
+ </varlistentry>
+ </variablelist>
+ <para><command>&dhpackage;</command> provides some return codes, that can
+ be used in scripts:</para>
+ <segmentedlist>
+ <segtitle>Code</segtitle>
+ <segtitle>Diagnostic</segtitle>
+ <seglistitem>
+ <seg><errorcode>0</errorcode></seg>
+ <seg>Program exited successfully.</seg>
+ </seglistitem>
+ <seglistitem>
+ <seg><errorcode>1</errorcode></seg>
+ <seg>The configuration file seems to be broken.</seg>
+ </seglistitem>
+ </segmentedlist>
+ </refsect1>
+ <refsect1 id="bugs">
+ <!-- Or use this section to tell about upstream BTS. -->
+ <title>BUGS</title>
+ <para>The program is currently limited to only work
+ with the <package>foobar</package> library.</para>
+ <para>The upstreams <acronym>BTS</acronym> can be found
+ at <ulink url="http://bugzilla.foo.tld"/>.</para>
+ </refsect1>
+ <refsect1 id="see_also">
+ <title>SEE ALSO</title>
+ <!-- In alpabetical order. -->
+ <para><citerefentry>
+ <refentrytitle>bar</refentrytitle>
+ <manvolnum>1</manvolnum>
+ </citerefentry>, <citerefentry>
+ <refentrytitle>baz</refentrytitle>
+ <manvolnum>1</manvolnum>
+ </citerefentry>, <citerefentry>
+ <refentrytitle>foo.conf</refentrytitle>
+ <manvolnum>5</manvolnum>
+ </citerefentry></para>
+ <para>The programs are documented fully by <citetitle>The Rise and
+ Fall of a Fooish Bar</citetitle> available via the <citerefentry>
+ <refentrytitle>info</refentrytitle>
+ <manvolnum>1</manvolnum>
+ </citerefentry> system.</para>
+ </refsect1>
+</refentry>
+
diff --git a/debian/menu.ex b/debian/menu.ex
new file mode 100644
index 0000000..9c4492c
--- /dev/null
+++ b/debian/menu.ex
@@ -0,0 +1,2 @@
+?package(gst-opencv):needs="X11|text|vc|wm" section="Applications/see-menu-manual"\
+ title="gst-opencv" command="/usr/bin/gst-opencv"
diff --git a/debian/postinst.ex b/debian/postinst.ex
new file mode 100644
index 0000000..619789d
--- /dev/null
+++ b/debian/postinst.ex
@@ -0,0 +1,39 @@
+#!/bin/sh
+# postinst script for gst-opencv
+#
+# see: dh_installdeb(1)
+
+set -e
+
+# summary of how this script can be called:
+# * <postinst> `configure' <most-recently-configured-version>
+# * <old-postinst> `abort-upgrade' <new version>
+# * <conflictor's-postinst> `abort-remove' `in-favour' <package>
+# <new-version>
+# * <postinst> `abort-remove'
+# * <deconfigured's-postinst> `abort-deconfigure' `in-favour'
+# <failed-install-package> <version> `removing'
+# <conflicting-package> <version>
+# for details, see http://www.debian.org/doc/debian-policy/ or
+# the debian-policy package
+
+
+case "$1" in
+ configure)
+ ;;
+
+ abort-upgrade|abort-remove|abort-deconfigure)
+ ;;
+
+ *)
+ echo "postinst called with unknown argument \`$1'" >&2
+ exit 1
+ ;;
+esac
+
+# dh_installdeb will replace this with shell code automatically
+# generated by other debhelper scripts.
+
+#DEBHELPER#
+
+exit 0
diff --git a/debian/postrm.ex b/debian/postrm.ex
new file mode 100644
index 0000000..6aaa99f
--- /dev/null
+++ b/debian/postrm.ex
@@ -0,0 +1,37 @@
+#!/bin/sh
+# postrm script for gst-opencv
+#
+# see: dh_installdeb(1)
+
+set -e
+
+# summary of how this script can be called:
+# * <postrm> `remove'
+# * <postrm> `purge'
+# * <old-postrm> `upgrade' <new-version>
+# * <new-postrm> `failed-upgrade' <old-version>
+# * <new-postrm> `abort-install'
+# * <new-postrm> `abort-install' <old-version>
+# * <new-postrm> `abort-upgrade' <old-version>
+# * <disappearer's-postrm> `disappear' <overwriter>
+# <overwriter-version>
+# for details, see http://www.debian.org/doc/debian-policy/ or
+# the debian-policy package
+
+
+case "$1" in
+ purge|remove|upgrade|failed-upgrade|abort-install|abort-upgrade|disappear)
+ ;;
+
+ *)
+ echo "postrm called with unknown argument \`$1'" >&2
+ exit 1
+ ;;
+esac
+
+# dh_installdeb will replace this with shell code automatically
+# generated by other debhelper scripts.
+
+#DEBHELPER#
+
+exit 0
diff --git a/debian/preinst.ex b/debian/preinst.ex
new file mode 100644
index 0000000..3e476ac
--- /dev/null
+++ b/debian/preinst.ex
@@ -0,0 +1,35 @@
+#!/bin/sh
+# preinst script for gst-opencv
+#
+# see: dh_installdeb(1)
+
+set -e
+
+# summary of how this script can be called:
+# * <new-preinst> `install'
+# * <new-preinst> `install' <old-version>
+# * <new-preinst> `upgrade' <old-version>
+# * <old-preinst> `abort-upgrade' <new-version>
+# for details, see http://www.debian.org/doc/debian-policy/ or
+# the debian-policy package
+
+
+case "$1" in
+ install|upgrade)
+ ;;
+
+ abort-upgrade)
+ ;;
+
+ *)
+ echo "preinst called with unknown argument \`$1'" >&2
+ exit 1
+ ;;
+esac
+
+# dh_installdeb will replace this with shell code automatically
+# generated by other debhelper scripts.
+
+#DEBHELPER#
+
+exit 0
diff --git a/debian/prerm.ex b/debian/prerm.ex
new file mode 100644
index 0000000..ef64626
--- /dev/null
+++ b/debian/prerm.ex
@@ -0,0 +1,38 @@
+#!/bin/sh
+# prerm script for gst-opencv
+#
+# see: dh_installdeb(1)
+
+set -e
+
+# summary of how this script can be called:
+# * <prerm> `remove'
+# * <old-prerm> `upgrade' <new-version>
+# * <new-prerm> `failed-upgrade' <old-version>
+# * <conflictor's-prerm> `remove' `in-favour' <package> <new-version>
+# * <deconfigured's-prerm> `deconfigure' `in-favour'
+# <package-being-installed> <version> `removing'
+# <conflicting-package> <version>
+# for details, see http://www.debian.org/doc/debian-policy/ or
+# the debian-policy package
+
+
+case "$1" in
+ remove|upgrade|deconfigure)
+ ;;
+
+ failed-upgrade)
+ ;;
+
+ *)
+ echo "prerm called with unknown argument \`$1'" >&2
+ exit 1
+ ;;
+esac
+
+# dh_installdeb will replace this with shell code automatically
+# generated by other debhelper scripts.
+
+#DEBHELPER#
+
+exit 0
diff --git a/debian/rules b/debian/rules
new file mode 100755
index 0000000..0708a4d
--- /dev/null
+++ b/debian/rules
@@ -0,0 +1,92 @@
+#!/usr/bin/make -f
+# -*- makefile -*-
+# Sample debian/rules that uses debhelper.
+# This file was originally written by Joey Hess and Craig Small.
+# As a special exception, when this file is copied by dh-make into a
+# dh-make output file, you may use that output file without restriction.
+# This special exception was added by Craig Small in version 0.37 of dh-make.
+
+# Uncomment this to turn on verbose mode.
+#export DH_VERBOSE=1
+
+
+
+
+
+configure: configure-stamp
+configure-stamp:
+ dh_testdir
+ # Add here commands to configure the package.
+ ./autogen.sh --prefix=/usr
+ touch configure-stamp
+
+
+build: build-stamp
+
+build-stamp: configure-stamp
+ dh_testdir
+
+ # Add here commands to compile the package.
+ #$(MAKE)
+ make
+ #docbook-to-man debian/gst-opencv.sgml > gst-opencv.1
+
+ touch $@
+
+clean:
+ dh_testdir
+ dh_testroot
+ rm -f build-stamp configure-stamp
+
+ # Add here commands to clean up after the build process.
+ #$(MAKE) clean
+
+ dh_clean
+
+install: build
+ dh_testdir
+ dh_testroot
+ dh_prep
+ dh_installdirs
+
+ # Add here commands to install the package into debian/gst-opencv.
+ $(MAKE) DESTDIR=$(CURDIR)/debian/gst-opencv install
+
+
+# Build architecture-independent files here.
+binary-indep: install
+# We have nothing to do by default.
+
+# Build architecture-dependent files here.
+binary-arch: install
+ dh_testdir
+ dh_testroot
+ dh_installchangelogs ChangeLog
+ dh_installdocs
+ dh_installexamples
+# dh_install
+# dh_installmenu
+# dh_installdebconf
+# dh_installlogrotate
+# dh_installemacsen
+# dh_installpam
+# dh_installmime
+# dh_python
+# dh_installinit
+# dh_installcron
+# dh_installinfo
+ dh_installman
+ dh_link
+ dh_strip
+ dh_compress
+ dh_fixperms
+# dh_perl
+# dh_makeshlibs
+ dh_installdeb
+ dh_shlibdeps
+ dh_gencontrol
+ dh_md5sums
+ dh_builddeb
+
+binary: binary-indep binary-arch
+.PHONY: build clean binary-indep binary-arch binary install configure
diff --git a/debian/watch.ex b/debian/watch.ex
new file mode 100644
index 0000000..69b668f
--- /dev/null
+++ b/debian/watch.ex
@@ -0,0 +1,23 @@
+# Example watch control file for uscan
+# Rename this file to "watch" and then you can run the "uscan" command
+# to check for upstream updates and more.
+# See uscan(1) for format
+
+# Compulsory line, this is a version 3 file
+version=3
+
+# Uncomment to examine a Webpage
+# <Webpage URL> <string match>
+#http://www.example.com/downloads.php gst-opencv-(.*)\.tar\.gz
+
+# Uncomment to examine a Webserver directory
+#http://www.example.com/pub/gst-opencv-(.*)\.tar\.gz
+
+# Uncommment to examine a FTP server
+#ftp://ftp.example.com/pub/gst-opencv-(.*)\.tar\.gz debian uupdate
+
+# Uncomment to find new files on sourceforge, for devscripts >= 2.9
+# http://sf.net/gst-opencv/gst-opencv-(.*)\.tar\.gz
+
+# Uncomment to find new files on GooglePages
+# http://example.googlepages.com/foo.html gst-opencv-(.*)\.tar\.gz
|
Elleo/gst-opencv
|
80ab2679f1d56651d92ebca68eba2e8bd944b21f
|
Registering all elements under opencv plugin
|
diff --git a/ChangeLog b/ChangeLog
index 9214308..4169b4a 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,18 +1,31 @@
+2009-05-08 Kapil Agrawal <kapil@mediamagictechnologies.com>
+
+ * configure.ac:
+ * src/Makefile.am:
+ * src/gstopencv.c:
+ * src/edgedetect/Makefile.am:
+ * src/edgedetect/gstedgedetect.c:
+ * src/facedetect/Makefile.am:
+ * src/facedetect/gstfacedetect.c:
+ * src/pyramidsegment/Makefile.am:
+ * src/pyramidsegment/gstpyramidsegment.c:
+ All elements will register as features of opencv plugin.
+
2009-05-06 Mike Sheldon <mike@mikeasoft.com>
* src/facedetect/gstfacedetect.c:
Fix "profile" parameter in face detect element to accept a string correctly
(was using char param instead of string param)
* src/edgedetect/gstedgedetect.c:
* src/pyramidsegment/gstpyramidsegment.c:
* src/facedetect/gstfacedetect.c:
Release OpenCV images when finalizing
2009-05-06 Kapil Agrawal <kapil@mediamagictechnologies.com>
* configure.ac: Added an error check for opencv.
* src/edgedetect/gstedgedetect.h:
* src/facedetect/gstfacedetect.h:
* src/pyramidsegment/gstpyramidsegment.h: Fixed the included path.
Fixed some compilation errors.
diff --git a/configure.ac b/configure.ac
index afe64cb..90c5c4b 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1,142 +1,142 @@
AC_INIT
dnl versions of gstreamer and plugins-base
GST_MAJORMINOR=0.10
GST_REQUIRED=0.10.0
GSTPB_REQUIRED=0.10.0
dnl fill in your package name and version here
dnl the fourth (nano) number should be 0 for a release, 1 for CVS,
dnl and 2... for a prerelease
dnl when going to/from release please set the nano correctly !
dnl releases only do Wall, cvs and prerelease does Werror too
-AS_VERSION(gst-edgedetect, GST_PLUGIN_VERSION, 0, 10, 0, 1,
+AS_VERSION(gst-opencv, GST_PLUGIN_VERSION, 0, 10, 0, 1,
GST_PLUGIN_CVS="no", GST_PLUGIN_CVS="yes")
dnl AM_MAINTAINER_MODE provides the option to enable maintainer mode
AM_MAINTAINER_MODE
AM_INIT_AUTOMAKE($PACKAGE, $VERSION)
dnl make aclocal work in maintainer mode
AC_SUBST(ACLOCAL_AMFLAGS, "-I m4")
AM_CONFIG_HEADER(config.h)
dnl check for tools
AC_PROG_CC
AC_PROG_LIBTOOL
dnl decide on error flags
AS_COMPILER_FLAG(-Wall, GST_WALL="yes", GST_WALL="no")
if test "x$GST_WALL" = "xyes"; then
GST_ERROR="$GST_ERROR -Wall"
# if test "x$GST_PLUGIN_CVS" = "xyes"; then
# AS_COMPILER_FLAG(-Werror,GST_ERROR="$GST_ERROR -Werror",GST_ERROR="$GST_ERROR")
# fi
fi
dnl Check for pkgconfig first
AC_CHECK_PROG(HAVE_PKGCONFIG, pkg-config, yes, no)
dnl Give error and exit if we don't have pkgconfig
if test "x$HAVE_PKGCONFIG" = "xno"; then
AC_MSG_ERROR(you need to have pkgconfig installed !)
fi
dnl Now we're ready to ask for gstreamer libs and cflags
dnl And we can also ask for the right version of gstreamer
PKG_CHECK_MODULES(GST, \
gstreamer-$GST_MAJORMINOR >= $GST_REQUIRED,
HAVE_GST=yes,HAVE_GST=no)
dnl Give error and exit if we don't have gstreamer
if test "x$HAVE_GST" = "xno"; then
AC_MSG_ERROR(you need gstreamer development packages installed !)
fi
dnl append GST_ERROR cflags to GST_CFLAGS
GST_CFLAGS="$GST_CFLAGS $GST_ERROR"
dnl make GST_CFLAGS and GST_LIBS available
AC_SUBST(GST_CFLAGS)
AC_SUBST(GST_LIBS)
dnl make GST_MAJORMINOR available in Makefile.am
AC_SUBST(GST_MAJORMINOR)
dnl If we need them, we can also use the base class libraries
PKG_CHECK_MODULES(GST_BASE, gstreamer-base-$GST_MAJORMINOR >= $GST_REQUIRED,
HAVE_GST_BASE=yes, HAVE_GST_BASE=no)
dnl Give a warning if we don't have gstreamer libs
dnl you can turn this into an error if you need them
if test "x$HAVE_GST_BASE" = "xno"; then
AC_MSG_NOTICE(no GStreamer base class libraries found (gstreamer-base-$GST_MAJORMINOR))
fi
dnl make _CFLAGS and _LIBS available
AC_SUBST(GST_BASE_CFLAGS)
AC_SUBST(GST_BASE_LIBS)
PKG_CHECK_MODULES(OPENCV,
opencv,
HAVE_OPENCV=yes, HAVE_OPENCV=no)
AC_SUBST(OPENCV_CFLAGS)
AC_SUBST(OPENCV_LIBS)
if test "x$HAVE_OPENCV" = "xno"; then
AC_MSG_ERROR(OpenCV libraries could not be found)
fi
dnl If we need them, we can also use the gstreamer-plugins-base libraries
PKG_CHECK_MODULES(GSTPB_BASE,
gstreamer-plugins-base-$GST_MAJORMINOR >= $GSTPB_REQUIRED,
HAVE_GSTPB_BASE=yes, HAVE_GSTPB_BASE=no)
dnl Give a warning if we don't have gstreamer libs
dnl you can turn this into an error if you need them
if test "x$HAVE_GSTPB_BASE" = "xno"; then
AC_MSG_NOTICE(no GStreamer Plugins Base libraries found (gstreamer-plugins-base-$GST_MAJORMINOR))
fi
dnl make _CFLAGS and _LIBS available
AC_SUBST(GSTPB_BASE_CFLAGS)
AC_SUBST(GSTPB_BASE_LIBS)
dnl If we need them, we can also use the gstreamer-controller libraries
PKG_CHECK_MODULES(GSTCTRL,
gstreamer-controller-$GST_MAJORMINOR >= $GSTPB_REQUIRED,
HAVE_GSTCTRL=yes, HAVE_GSTCTRL=no)
dnl Give a warning if we don't have gstreamer-controller
dnl you can turn this into an error if you need them
if test "x$HAVE_GSTCTRL" = "xno"; then
AC_MSG_NOTICE(no GStreamer Controller libraries found (gstreamer-controller-$GST_MAJORMINOR))
fi
dnl make _CFLAGS and _LIBS available
AC_SUBST(GSTCTRL_CFLAGS)
AC_SUBST(GSTCTRL_LIBS)
dnl set the plugindir where plugins should be installed
if test "x${prefix}" = "x$HOME"; then
plugindir="$HOME/.gstreamer-$GST_MAJORMINOR/plugins"
else
plugindir="\$(libdir)/gstreamer-$GST_MAJORMINOR"
fi
AC_SUBST(plugindir)
dnl set proper LDFLAGS for plugins
GST_PLUGIN_LDFLAGS='-module -avoid-version -export-symbols-regex [_]*\(gst_\|Gst\|GST_\).*'
AC_SUBST(GST_PLUGIN_LDFLAGS)
AC_OUTPUT(Makefile m4/Makefile src/Makefile src/edgedetect/Makefile src/pyramidsegment/Makefile src/facedetect/Makefile)
diff --git a/src/Makefile.am b/src/Makefile.am
index 0061f7e..aa412a4 100644
--- a/src/Makefile.am
+++ b/src/Makefile.am
@@ -1 +1,30 @@
SUBDIRS = edgedetect facedetect pyramidsegment
+
+# plugindir is set in configure
+
+plugin_LTLIBRARIES = libgstopencv.la
+
+# sources used to compile this plug-in
+libgstopencv_la_SOURCES = gstopencv.c
+
+# flags used to compile this facedetect
+# add other _CFLAGS and _LIBS as needed
+libgstopencv_la_CFLAGS = $(GST_CFLAGS) $(OPENCV_CFLAGS) \
+ -I${top_srcdir}/src/edgedetect \
+ -I${top_srcdir}/src/facedetect \
+ -I${top_srcdir}/src/pyramidsegment
+
+libgstopencv_la_LIBADD = $(GST_LIBS) $(OPENCV_LIBS) \
+ $(top_builddir)/src/edgedetect/libgstedgedetect.la \
+ $(top_builddir)/src/facedetect/libgstfacedetect.la \
+ $(top_builddir)/src/pyramidsegment/libgstpyramidsegment.la
+
+libgstopencv_la_LDFLAGS = $(GST_PLUGIN_LDFLAGS)
+
+libgstopencv_la_DEPENDENCIES = \
+ $(top_builddir)/src/edgedetect/libgstedgedetect.la \
+ $(top_builddir)/src/facedetect/libgstfacedetect.la \
+ $(top_builddir)/src/pyramidsegment/libgstpyramidsegment.la
+
+# headers we need but don't want installed
+noinst_HEADERS =
diff --git a/src/edgedetect/Makefile.am b/src/edgedetect/Makefile.am
index 54c6657..6387502 100644
--- a/src/edgedetect/Makefile.am
+++ b/src/edgedetect/Makefile.am
@@ -1,15 +1,15 @@
# plugindir is set in configure
-plugin_LTLIBRARIES = libgstedgedetect.la
+noinst_LTLIBRARIES = libgstedgedetect.la
# sources used to compile this plug-in
libgstedgedetect_la_SOURCES = gstedgedetect.c
# flags used to compile this edgedetect
# add other _CFLAGS and _LIBS as needed
libgstedgedetect_la_CFLAGS = $(GST_CFLAGS) $(OPENCV_CFLAGS)
libgstedgedetect_la_LIBADD = $(GST_LIBS) $(OPENCV_LIBS)
libgstedgedetect_la_LDFLAGS = $(GST_PLUGIN_LDFLAGS)
# headers we need but don't want installed
noinst_HEADERS = gstedgedetect.h
diff --git a/src/edgedetect/gstedgedetect.c b/src/edgedetect/gstedgedetect.c
index 26b4f47..c5c226a 100644
--- a/src/edgedetect/gstedgedetect.c
+++ b/src/edgedetect/gstedgedetect.c
@@ -1,347 +1,331 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2008 Michael Sheldon <mike@mikeasoft.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/**
* SECTION:element-edgedetect
*
* FIXME:Describe edgedetect here.
*
* <refsect2>
* <title>Example launch line</title>
* |[
* gst-launch-0.10 videotestsrc ! decodebin ! ffmpegcolorspace ! edgedetect ! ffmpegcolorspace ! xvimagesink
* ]|
* </refsect2>
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <gst/gst.h>
#include "gstedgedetect.h"
GST_DEBUG_CATEGORY_STATIC (gst_edgedetect_debug);
#define GST_CAT_DEFAULT gst_edgedetect_debug
/* Filter signals and args */
enum
{
/* FILL ME */
LAST_SIGNAL
};
enum
{
PROP_0,
PROP_THRESHOLD1,
PROP_THRESHOLD2,
PROP_APERTURE,
PROP_MASK
};
/* the capabilities of the inputs and outputs.
*
* describe the real formats here.
*/
static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
GST_PAD_SINK,
GST_PAD_ALWAYS,
GST_STATIC_CAPS (
"video/x-raw-rgb"
)
);
static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
GST_PAD_SRC,
GST_PAD_ALWAYS,
GST_STATIC_CAPS (
"video/x-raw-rgb"
)
);
GST_BOILERPLATE (Gstedgedetect, gst_edgedetect, GstElement,
GST_TYPE_ELEMENT);
static void gst_edgedetect_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec);
static void gst_edgedetect_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec);
static gboolean gst_edgedetect_set_caps (GstPad * pad, GstCaps * caps);
static GstFlowReturn gst_edgedetect_chain (GstPad * pad, GstBuffer * buf);
/* Clean up */
static void
gst_edgedetect_finalize (GObject * obj)
{
Gstedgedetect *filter = GST_EDGEDETECT (obj);
if (filter->cvImage != NULL)
{
cvReleaseImage (&filter->cvImage);
cvReleaseImage (&filter->cvCEdge);
cvReleaseImage (&filter->cvGray);
cvReleaseImage (&filter->cvEdge);
}
G_OBJECT_CLASS (parent_class)->finalize (obj);
}
/* GObject vmethod implementations */
static void
gst_edgedetect_base_init (gpointer gclass)
{
GstElementClass *element_class = GST_ELEMENT_CLASS (gclass);
gst_element_class_set_details_simple(element_class,
"edgedetect",
"Filter/Effect/Video",
"Performs canny edge detection on videos and images.",
"Michael Sheldon <mike@mikeasoft.com>");
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&src_factory));
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&sink_factory));
}
/* initialize the edgedetect's class */
static void
gst_edgedetect_class_init (GstedgedetectClass * klass)
{
GObjectClass *gobject_class;
GstElementClass *gstelement_class;
gobject_class = (GObjectClass *) klass;
gstelement_class = (GstElementClass *) klass;
parent_class = g_type_class_peek_parent (klass);
gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_edgedetect_finalize);
gobject_class->set_property = gst_edgedetect_set_property;
gobject_class->get_property = gst_edgedetect_get_property;
g_object_class_install_property (gobject_class, PROP_MASK,
g_param_spec_boolean ("mask", "Mask", "Sets whether the detected edges should be used as a mask on the original input or not",
TRUE, G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_THRESHOLD1,
g_param_spec_int ("threshold1", "Threshold1", "Threshold value for canny edge detection",
0, 1000, 50, G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_THRESHOLD2,
g_param_spec_int ("threshold2", "Threshold2", "Second threshold value for canny edge detection",
0, 1000, 150, G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_APERTURE,
g_param_spec_int ("aperture", "Aperture", "Aperture size for Sobel operator (Must be either 3, 5 or 7",
3, 7, 3, G_PARAM_READWRITE));
}
/* initialize the new element
* instantiate pads and add them to element
* set pad calback functions
* initialize instance structure
*/
static void
gst_edgedetect_init (Gstedgedetect * filter,
GstedgedetectClass * gclass)
{
filter->sinkpad = gst_pad_new_from_static_template (&sink_factory, "sink");
gst_pad_set_setcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR(gst_edgedetect_set_caps));
gst_pad_set_getcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR(gst_pad_proxy_getcaps));
gst_pad_set_chain_function (filter->sinkpad,
GST_DEBUG_FUNCPTR(gst_edgedetect_chain));
filter->srcpad = gst_pad_new_from_static_template (&src_factory, "src");
gst_pad_set_getcaps_function (filter->srcpad,
GST_DEBUG_FUNCPTR(gst_pad_proxy_getcaps));
gst_element_add_pad (GST_ELEMENT (filter), filter->sinkpad);
gst_element_add_pad (GST_ELEMENT (filter), filter->srcpad);
filter->mask = TRUE;
filter->threshold1 = 50;
filter->threshold2 = 150;
filter->aperture = 3;
}
static void
gst_edgedetect_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec)
{
Gstedgedetect *filter = GST_EDGEDETECT (object);
switch (prop_id) {
case PROP_MASK:
filter->mask = g_value_get_boolean (value);
break;
case PROP_THRESHOLD1:
filter->threshold1 = g_value_get_int (value);
break;
case PROP_THRESHOLD2:
filter->threshold2 = g_value_get_int (value);
break;
case PROP_APERTURE:
filter->aperture = g_value_get_int (value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gst_edgedetect_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec)
{
Gstedgedetect *filter = GST_EDGEDETECT (object);
switch (prop_id) {
case PROP_MASK:
g_value_set_boolean (value, filter->mask);
break;
case PROP_THRESHOLD1:
g_value_set_int (value, filter->threshold1);
break;
case PROP_THRESHOLD2:
g_value_set_int (value, filter->threshold2);
break;
case PROP_APERTURE:
g_value_set_int (value, filter->aperture);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
/* GstElement vmethod implementations */
/* this function handles the link with other elements */
static gboolean
gst_edgedetect_set_caps (GstPad * pad, GstCaps * caps)
{
Gstedgedetect *filter;
GstPad *otherpad;
gint width, height;
GstStructure *structure;
filter = GST_EDGEDETECT (gst_pad_get_parent (pad));
structure = gst_caps_get_structure (caps, 0);
gst_structure_get_int (structure, "width", &width);
gst_structure_get_int (structure, "height", &height);
filter->cvImage = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 3);
filter->cvCEdge = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 3);
filter->cvGray = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 1);
filter->cvEdge = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 1);
otherpad = (pad == filter->srcpad) ? filter->sinkpad : filter->srcpad;
gst_object_unref (filter);
return gst_pad_set_caps (otherpad, caps);
}
/* chain function
* this function does the actual processing
*/
static GstFlowReturn
gst_edgedetect_chain (GstPad * pad, GstBuffer * buf)
{
Gstedgedetect *filter;
filter = GST_EDGEDETECT (GST_OBJECT_PARENT (pad));
filter->cvImage->imageData = (char *) GST_BUFFER_DATA (buf);
cvCvtColor(filter->cvImage, filter->cvGray, CV_RGB2GRAY);
cvSmooth(filter->cvGray, filter->cvEdge, CV_BLUR, 3, 3, 0, 0 );
cvNot(filter->cvGray, filter->cvEdge);
cvCanny(filter->cvGray, filter->cvEdge, filter->threshold1, filter->threshold2, filter->aperture);
cvZero(filter->cvCEdge);
if(filter-> mask) {
cvCopy(filter->cvImage, filter->cvCEdge, filter->cvEdge);
} else {
cvCvtColor(filter->cvEdge, filter->cvCEdge, CV_GRAY2RGB);
}
gst_buffer_set_data(buf, filter->cvCEdge->imageData, filter->cvCEdge->imageSize);
return gst_pad_push (filter->srcpad, buf);
}
/* entry point to initialize the plug-in
* initialize the plug-in itself
* register the element factories and other features
*/
-static gboolean
-edgedetect_init (GstPlugin * edgedetect)
+gboolean
+gst_edgedetect_plugin_init (GstPlugin * plugin)
{
/* debug category for fltering log messages
*
* exchange the string 'Template edgedetect' with your description
*/
GST_DEBUG_CATEGORY_INIT (gst_edgedetect_debug, "edgedetect",
0, "Performs canny edge detection on videos and images");
- return gst_element_register (edgedetect, "edgedetect", GST_RANK_NONE,
+ return gst_element_register (plugin, "edgedetect", GST_RANK_NONE,
GST_TYPE_EDGEDETECT);
}
-
-/* gstreamer looks for this structure to register edgedetects
- *
- * exchange the string 'Template edgedetect' with your edgedetect description
- */
-GST_PLUGIN_DEFINE (
- GST_VERSION_MAJOR,
- GST_VERSION_MINOR,
- "edgedetect",
- "Performs canny edge detection on videos and images",
- edgedetect_init,
- VERSION,
- "LGPL",
- "GStreamer OpenCV Plugins",
- "http://www.mikeasoft.com/"
-)
diff --git a/src/edgedetect/gstedgedetect.h b/src/edgedetect/gstedgedetect.h
index 5931bf1..9d17632 100644
--- a/src/edgedetect/gstedgedetect.h
+++ b/src/edgedetect/gstedgedetect.h
@@ -1,91 +1,93 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2008 Michael Sheldon <mike@mikeasoft.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#ifndef __GST_EDGEDETECT_H__
#define __GST_EDGEDETECT_H__
#include <gst/gst.h>
#include <cv.h>
G_BEGIN_DECLS
/* #defines don't like whitespacey bits */
#define GST_TYPE_EDGEDETECT \
(gst_edgedetect_get_type())
#define GST_EDGEDETECT(obj) \
(G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_EDGEDETECT,Gstedgedetect))
#define GST_EDGEDETECT_CLASS(klass) \
(G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_EDGEDETECT,GstedgedetectClass))
#define GST_IS_EDGEDETECT(obj) \
(G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_EDGEDETECT))
#define GST_IS_EDGEDETECT_CLASS(klass) \
(G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_EDGEDETECT))
typedef struct _Gstedgedetect Gstedgedetect;
typedef struct _GstedgedetectClass GstedgedetectClass;
struct _Gstedgedetect
{
GstElement element;
GstPad *sinkpad, *srcpad;
gboolean mask;
int threshold1, threshold2, aperture;
IplImage *cvEdge, *cvGray, *cvImage, *cvCEdge;
};
struct _GstedgedetectClass
{
GstElementClass parent_class;
};
GType gst_edgedetect_get_type (void);
+gboolean gst_edgedetect_plugin_init (GstPlugin * plugin);
+
G_END_DECLS
#endif /* __GST_EDGEDETECT_H__ */
diff --git a/src/facedetect/Makefile.am b/src/facedetect/Makefile.am
index 21097ef..b0a91ee 100644
--- a/src/facedetect/Makefile.am
+++ b/src/facedetect/Makefile.am
@@ -1,15 +1,15 @@
# plugindir is set in configure
-plugin_LTLIBRARIES = libgstfacedetect.la
+noinst_LTLIBRARIES = libgstfacedetect.la
# sources used to compile this plug-in
libgstfacedetect_la_SOURCES = gstfacedetect.c
# flags used to compile this facedetect
# add other _CFLAGS and _LIBS as needed
libgstfacedetect_la_CFLAGS = $(GST_CFLAGS) $(OPENCV_CFLAGS)
libgstfacedetect_la_LIBADD = $(GST_LIBS) $(OPENCV_LIBS)
libgstfacedetect_la_LDFLAGS = $(GST_PLUGIN_LDFLAGS)
# headers we need but don't want installed
noinst_HEADERS = gstfacedetect.h
diff --git a/src/facedetect/gstfacedetect.c b/src/facedetect/gstfacedetect.c
index 1e1af4c..03d29b1 100644
--- a/src/facedetect/gstfacedetect.c
+++ b/src/facedetect/gstfacedetect.c
@@ -1,353 +1,339 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2008 Michael Sheldon <mike@mikeasoft.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/**
* SECTION:element-facedetect
*
* FIXME:Describe facedetect here.
*
* <refsect2>
* <title>Example launch line</title>
* |[
* gst-launch-0.10 videotestsrc ! decodebin ! ffmpegcolorspace ! facedetect ! ffmpegcolorspace ! xvimagesink
* ]|
* </refsect2>
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <gst/gst.h>
#include "gstfacedetect.h"
GST_DEBUG_CATEGORY_STATIC (gst_facedetect_debug);
#define GST_CAT_DEFAULT gst_facedetect_debug
#define DEFAULT_PROFILE "/usr/share/opencv/haarcascades/haarcascade_frontalface_default.xml"
/* Filter signals and args */
enum
{
/* FILL ME */
LAST_SIGNAL
};
enum
{
PROP_0,
PROP_DISPLAY,
PROP_PROFILE
};
/* the capabilities of the inputs and outputs.
*/
static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
GST_PAD_SINK,
GST_PAD_ALWAYS,
GST_STATIC_CAPS (
"video/x-raw-rgb"
)
);
static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
GST_PAD_SRC,
GST_PAD_ALWAYS,
GST_STATIC_CAPS (
"video/x-raw-rgb"
)
);
GST_BOILERPLATE (Gstfacedetect, gst_facedetect, GstElement,
GST_TYPE_ELEMENT);
static void gst_facedetect_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec);
static void gst_facedetect_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec);
static gboolean gst_facedetect_set_caps (GstPad * pad, GstCaps * caps);
static GstFlowReturn gst_facedetect_chain (GstPad * pad, GstBuffer * buf);
static void gst_facedetect_load_profile (Gstfacedetect * filter);
/* Clean up */
static void
gst_facedetect_finalize (GObject * obj)
{
Gstfacedetect *filter = GST_FACEDETECT(obj);
if (filter->cvImage)
{
cvReleaseImage (&filter->cvImage);
cvReleaseImage (&filter->cvGray);
}
G_OBJECT_CLASS (parent_class)->finalize (obj);
}
/* GObject vmethod implementations */
static void
gst_facedetect_base_init (gpointer gclass)
{
GstElementClass *element_class = GST_ELEMENT_CLASS (gclass);
gst_element_class_set_details_simple(element_class,
"facedetect",
"Filter/Effect/Video",
"Performs face detection on videos and images, providing detected positions via bus messages",
"Michael Sheldon <mike@mikeasoft.com>");
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&src_factory));
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&sink_factory));
}
/* initialize the facedetect's class */
static void
gst_facedetect_class_init (GstfacedetectClass * klass)
{
GObjectClass *gobject_class;
GstElementClass *gstelement_class;
gobject_class = (GObjectClass *) klass;
gstelement_class = (GstElementClass *) klass;
parent_class = g_type_class_peek_parent (klass);
gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_facedetect_finalize);
gobject_class->set_property = gst_facedetect_set_property;
gobject_class->get_property = gst_facedetect_get_property;
g_object_class_install_property (gobject_class, PROP_DISPLAY,
g_param_spec_boolean ("display", "Display", "Sets whether the detected faces should be highlighted in the output",
TRUE, G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_PROFILE,
g_param_spec_string ("profile", "Profile", "Location of Haar cascade file to use for face detection",
DEFAULT_PROFILE, G_PARAM_READWRITE));
}
/* initialize the new element
* instantiate pads and add them to element
* set pad calback functions
* initialize instance structure
*/
static void
gst_facedetect_init (Gstfacedetect * filter,
GstfacedetectClass * gclass)
{
filter->sinkpad = gst_pad_new_from_static_template (&sink_factory, "sink");
gst_pad_set_setcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR(gst_facedetect_set_caps));
gst_pad_set_getcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR(gst_pad_proxy_getcaps));
gst_pad_set_chain_function (filter->sinkpad,
GST_DEBUG_FUNCPTR(gst_facedetect_chain));
filter->srcpad = gst_pad_new_from_static_template (&src_factory, "src");
gst_pad_set_getcaps_function (filter->srcpad,
GST_DEBUG_FUNCPTR(gst_pad_proxy_getcaps));
gst_element_add_pad (GST_ELEMENT (filter), filter->sinkpad);
gst_element_add_pad (GST_ELEMENT (filter), filter->srcpad);
filter->profile = DEFAULT_PROFILE;
filter->display = TRUE;
gst_facedetect_load_profile(filter);
}
static void
gst_facedetect_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec)
{
Gstfacedetect *filter = GST_FACEDETECT (object);
switch (prop_id) {
case PROP_PROFILE:
filter->profile = g_value_dup_string (value);
gst_facedetect_load_profile(filter);
break;
case PROP_DISPLAY:
filter->display = g_value_get_boolean (value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gst_facedetect_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec)
{
Gstfacedetect *filter = GST_FACEDETECT (object);
switch (prop_id) {
case PROP_PROFILE:
g_value_take_string (value, filter->profile);
break;
case PROP_DISPLAY:
g_value_set_boolean (value, filter->display);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
/* GstElement vmethod implementations */
/* this function handles the link with other elements */
static gboolean
gst_facedetect_set_caps (GstPad * pad, GstCaps * caps)
{
Gstfacedetect *filter;
GstPad *otherpad;
gint width, height;
GstStructure *structure;
filter = GST_FACEDETECT (gst_pad_get_parent (pad));
structure = gst_caps_get_structure (caps, 0);
gst_structure_get_int (structure, "width", &width);
gst_structure_get_int (structure, "height", &height);
filter->cvImage = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 3);
filter->cvGray = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 1);
filter->cvStorage = cvCreateMemStorage(0);
otherpad = (pad == filter->srcpad) ? filter->sinkpad : filter->srcpad;
gst_object_unref (filter);
return gst_pad_set_caps (otherpad, caps);
}
/* chain function
* this function does the actual processing
*/
static GstFlowReturn
gst_facedetect_chain (GstPad * pad, GstBuffer * buf)
{
Gstfacedetect *filter;
CvSeq *faces;
int i;
filter = GST_FACEDETECT (GST_OBJECT_PARENT (pad));
filter->cvImage->imageData = (char *) GST_BUFFER_DATA (buf);
cvCvtColor(filter->cvImage, filter->cvGray, CV_RGB2GRAY);
cvClearMemStorage(filter->cvStorage);
if (filter->cvCascade) {
faces = cvHaarDetectObjects(filter->cvGray, filter->cvCascade, filter->cvStorage, 1.1, 2, 0, cvSize(30, 30));
for (i = 0; i < (faces ? faces->total : 0); i++) {
CvRect* r = (CvRect *) cvGetSeqElem(faces, i);
GstStructure *s = gst_structure_new ("face",
"x", G_TYPE_UINT, r->x,
"y", G_TYPE_UINT, r->y,
"width", G_TYPE_UINT, r->width,
"height", G_TYPE_UINT, r->height, NULL);
GstMessage *m = gst_message_new_element (GST_OBJECT (filter), s);
gst_element_post_message (GST_ELEMENT (filter), m);
if (filter->display) {
CvPoint center;
int radius;
center.x = cvRound((r->x + r->width*0.5));
center.y = cvRound((r->y + r->height*0.5));
radius = cvRound((r->width + r->height)*0.25);
cvCircle(filter->cvImage, center, radius, CV_RGB(255, 32, 32), 3, 8, 0);
}
}
}
gst_buffer_set_data(buf, filter->cvImage->imageData, filter->cvImage->imageSize);
return gst_pad_push (filter->srcpad, buf);
}
static void gst_facedetect_load_profile(Gstfacedetect * filter) {
filter->cvCascade = (CvHaarClassifierCascade*)cvLoad(filter->profile, 0, 0, 0 );
if (!filter->cvCascade) {
GST_WARNING ("Couldn't load Haar classifier cascade: %s.", filter->profile);
}
}
/* entry point to initialize the plug-in
* initialize the plug-in itself
* register the element factories and other features
*/
-static gboolean
-facedetect_init (GstPlugin * facedetect)
+gboolean
+gst_facedetect_plugin_init (GstPlugin * plugin)
{
/* debug category for fltering log messages */
GST_DEBUG_CATEGORY_INIT (gst_facedetect_debug, "facedetect",
0, "Performs face detection on videos and images, providing detected positions via bus messages");
- return gst_element_register (facedetect, "facedetect", GST_RANK_NONE,
+ return gst_element_register (plugin, "facedetect", GST_RANK_NONE,
GST_TYPE_FACEDETECT);
}
-
-
-/* gstreamer looks for this structure to register facedetect */
-GST_PLUGIN_DEFINE (
- GST_VERSION_MAJOR,
- GST_VERSION_MINOR,
- "facedetect",
- "Performs face detection on videos and images, providing detected positions via bus messages",
- facedetect_init,
- VERSION,
- "LGPL",
- "GStreamer OpenCV Plugins",
- "http://www.mikeasoft.com/"
-)
diff --git a/src/facedetect/gstfacedetect.h b/src/facedetect/gstfacedetect.h
index 97e9e02..6ca56a7 100644
--- a/src/facedetect/gstfacedetect.h
+++ b/src/facedetect/gstfacedetect.h
@@ -1,93 +1,95 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2008 Michael Sheldon <mike@mikeasoft.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#ifndef __GST_FACEDETECT_H__
#define __GST_FACEDETECT_H__
#include <gst/gst.h>
#include <cv.h>
G_BEGIN_DECLS
/* #defines don't like whitespacey bits */
#define GST_TYPE_FACEDETECT \
(gst_facedetect_get_type())
#define GST_FACEDETECT(obj) \
(G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_FACEDETECT,Gstfacedetect))
#define GST_FACEDETECT_CLASS(klass) \
(G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_FACEDETECT,GstfacedetectClass))
#define GST_IS_FACEDETECT(obj) \
(G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_FACEDETECT))
#define GST_IS_FACEDETECT_CLASS(klass) \
(G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_FACEDETECT))
typedef struct _Gstfacedetect Gstfacedetect;
typedef struct _GstfacedetectClass GstfacedetectClass;
struct _Gstfacedetect
{
GstElement element;
GstPad *sinkpad, *srcpad;
gboolean display;
gchar *profile;
IplImage *cvImage, *cvGray;
CvHaarClassifierCascade *cvCascade;
CvMemStorage *cvStorage;
};
struct _GstfacedetectClass
{
GstElementClass parent_class;
};
GType gst_facedetect_get_type (void);
+gboolean gst_facedetect_plugin_init (GstPlugin * plugin);
+
G_END_DECLS
#endif /* __GST_FACEDETECT_H__ */
diff --git a/src/gstopencv.c b/src/gstopencv.c
new file mode 100644
index 0000000..8c03647
--- /dev/null
+++ b/src/gstopencv.c
@@ -0,0 +1,50 @@
+/* GStreamer
+ * Copyright (C) <2009> Kapil Agrawal <kapil@mediamagictechnologies.com>
+ *
+ * gstopencv.c: plugin registering
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library; if not, write to the
+ * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+ * Boston, MA 02111-1307, USA.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "gstedgedetect.h"
+#include "gstfacedetect.h"
+#include "gstpyramidsegment.h"
+
+static gboolean
+plugin_init (GstPlugin * plugin)
+{
+
+ if (!gst_edgedetect_plugin_init (plugin))
+ return FALSE;
+
+ if (!gst_facedetect_plugin_init (plugin))
+ return FALSE;
+
+ if (!gst_pyramidsegment_plugin_init (plugin))
+ return FALSE;
+
+ return TRUE;
+}
+
+GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
+ GST_VERSION_MINOR,
+ "opencv",
+ "GStreamer OpenCV Plugins",
+ plugin_init, VERSION, "LGPL", "OpenCv", "http://opencv.willowgarage.com")
diff --git a/src/pyramidsegment/Makefile.am b/src/pyramidsegment/Makefile.am
index e55de2d..7c4a691 100644
--- a/src/pyramidsegment/Makefile.am
+++ b/src/pyramidsegment/Makefile.am
@@ -1,15 +1,13 @@
-# plugindir is set in configure
-
-plugin_LTLIBRARIES = libgstpyramidsegment.la
+noinst_LTLIBRARIES = libgstpyramidsegment.la
# sources used to compile this plug-in
libgstpyramidsegment_la_SOURCES = gstpyramidsegment.c
# flags used to compile this pyramidsegment
# add other _CFLAGS and _LIBS as needed
libgstpyramidsegment_la_CFLAGS = $(GST_CFLAGS) $(OPENCV_CFLAGS)
libgstpyramidsegment_la_LIBADD = $(GST_LIBS) $(OPENCV_LIBS)
libgstpyramidsegment_la_LDFLAGS = $(GST_PLUGIN_LDFLAGS)
# headers we need but don't want installed
noinst_HEADERS = gstpyramidsegment.h
diff --git a/src/pyramidsegment/gstpyramidsegment.c b/src/pyramidsegment/gstpyramidsegment.c
index 811baea..77afa0f 100644
--- a/src/pyramidsegment/gstpyramidsegment.c
+++ b/src/pyramidsegment/gstpyramidsegment.c
@@ -1,333 +1,320 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2008 Michael Sheldon <mike@mikeasoft.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/**
* SECTION:element-pyramidsegment
*
* FIXME:Describe pyramidsegment here.
*
* <refsect2>
* <title>Example launch line</title>
* |[
* gst-launch -v -m fakesrc ! pyramidsegment ! fakesink silent=TRUE
* ]|
* </refsect2>
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <gst/gst.h>
#include "gstpyramidsegment.h"
#define BLOCK_SIZE 1000
GST_DEBUG_CATEGORY_STATIC (gst_pyramidsegment_debug);
#define GST_CAT_DEFAULT gst_pyramidsegment_debug
/* Filter signals and args */
enum
{
/* FILL ME */
LAST_SIGNAL
};
enum
{
PROP_0,
PROP_SILENT,
PROP_THRESHOLD1,
PROP_THRESHOLD2,
PROP_LEVEL
};
/* the capabilities of the inputs and outputs.
*
* describe the real formats here.
*/
static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
GST_PAD_SINK,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("video/x-raw-rgb")
);
static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
GST_PAD_SRC,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("video/x-raw-rgb")
);
GST_BOILERPLATE (Gstpyramidsegment, gst_pyramidsegment, GstElement,
GST_TYPE_ELEMENT);
static void gst_pyramidsegment_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec);
static void gst_pyramidsegment_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec);
static gboolean gst_pyramidsegment_set_caps (GstPad * pad, GstCaps * caps);
static GstFlowReturn gst_pyramidsegment_chain (GstPad * pad, GstBuffer * buf);
/* Clean up */
static void
gst_pyramidsegment_finalize (GObject * obj)
{
Gstpyramidsegment *filter = GST_PYRAMIDSEGMENT(obj);
if (filter->cvImage != NULL)
{
cvReleaseImage (&filter->cvImage);
cvReleaseImage (&filter->cvSegmentedImage);
}
G_OBJECT_CLASS (parent_class)->finalize (obj);
}
/* GObject vmethod implementations */
static void
gst_pyramidsegment_base_init (gpointer gclass)
{
GstElementClass *element_class = GST_ELEMENT_CLASS (gclass);
gst_element_class_set_details_simple(element_class,
"pyramidsegment",
"Filter/Effect/Video",
"Applies pyramid segmentation to a video or image.",
"Michael Sheldon <mike@mikeasoft.com>");
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&src_factory));
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&sink_factory));
}
/* initialize the pyramidsegment's class */
static void
gst_pyramidsegment_class_init (GstpyramidsegmentClass * klass)
{
GObjectClass *gobject_class;
GstElementClass *gstelement_class;
gobject_class = (GObjectClass *) klass;
gstelement_class = (GstElementClass *) klass;
parent_class = g_type_class_peek_parent (klass);
gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_pyramidsegment_finalize);
gobject_class->set_property = gst_pyramidsegment_set_property;
gobject_class->get_property = gst_pyramidsegment_get_property;
g_object_class_install_property (gobject_class, PROP_SILENT,
g_param_spec_boolean ("silent", "Silent", "Produce verbose output ?",
FALSE, G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_THRESHOLD1,
g_param_spec_double ("threshold1", "Threshold1", "Error threshold for establishing links",
0, 1000, 50, G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_THRESHOLD2,
g_param_spec_double ("threshold2", "Threshold2", "Error threshold for segment clustering",
0, 1000, 60, G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_LEVEL,
g_param_spec_int ("level", "Level", "Maximum level of the pyramid segmentation",
0, 4, 4, G_PARAM_READWRITE));
}
/* initialize the new element
* instantiate pads and add them to element
* set pad calback functions
* initialize instance structure
*/
static void
gst_pyramidsegment_init (Gstpyramidsegment * filter,
GstpyramidsegmentClass * gclass)
{
filter->sinkpad = gst_pad_new_from_static_template (&sink_factory, "sink");
gst_pad_set_setcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR(gst_pyramidsegment_set_caps));
gst_pad_set_getcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR(gst_pad_proxy_getcaps));
gst_pad_set_chain_function (filter->sinkpad,
GST_DEBUG_FUNCPTR(gst_pyramidsegment_chain));
filter->srcpad = gst_pad_new_from_static_template (&src_factory, "src");
gst_pad_set_getcaps_function (filter->srcpad,
GST_DEBUG_FUNCPTR(gst_pad_proxy_getcaps));
gst_element_add_pad (GST_ELEMENT (filter), filter->sinkpad);
gst_element_add_pad (GST_ELEMENT (filter), filter->srcpad);
filter->storage = cvCreateMemStorage ( BLOCK_SIZE );
filter->comp = cvCreateSeq(0, sizeof(CvSeq), sizeof(CvPoint), filter->storage);
filter->silent = FALSE;
filter->threshold1 = 50.0;
filter->threshold2 = 60.0;
filter->level = 4;
}
static void
gst_pyramidsegment_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec)
{
Gstpyramidsegment *filter = GST_PYRAMIDSEGMENT (object);
switch (prop_id) {
case PROP_SILENT:
filter->silent = g_value_get_boolean (value);
break;
case PROP_THRESHOLD1:
filter->threshold1 = g_value_get_double (value);
break;
case PROP_THRESHOLD2:
filter->threshold2 = g_value_get_double (value);
break;
case PROP_LEVEL:
filter->level = g_value_get_int (value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gst_pyramidsegment_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec)
{
Gstpyramidsegment *filter = GST_PYRAMIDSEGMENT (object);
switch (prop_id) {
case PROP_SILENT:
g_value_set_boolean (value, filter->silent);
break;
case PROP_THRESHOLD1:
g_value_set_double (value, filter->threshold1);
break;
case PROP_THRESHOLD2:
g_value_set_double (value, filter->threshold2);
break;
case PROP_LEVEL:
g_value_set_int (value, filter->level);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
/* GstElement vmethod implementations */
/* this function handles the link with other elements */
static gboolean
gst_pyramidsegment_set_caps (GstPad * pad, GstCaps * caps)
{
Gstpyramidsegment *filter;
GstPad *otherpad;
GstStructure *structure;
gint width, height;
filter = GST_PYRAMIDSEGMENT (gst_pad_get_parent (pad));
structure = gst_caps_get_structure (caps, 0);
gst_structure_get_int (structure, "width", &width);
gst_structure_get_int (structure, "height", &height);
filter->cvImage = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 3);
otherpad = (pad == filter->srcpad) ? filter->sinkpad : filter->srcpad;
gst_object_unref (filter);
return gst_pad_set_caps (otherpad, caps);
}
/* chain function
* this function does the actual processing
*/
static GstFlowReturn
gst_pyramidsegment_chain (GstPad * pad, GstBuffer * buf)
{
Gstpyramidsegment *filter;
filter = GST_PYRAMIDSEGMENT (GST_OBJECT_PARENT (pad));
filter->cvImage->imageData = (char *) GST_BUFFER_DATA (buf);
filter->cvSegmentedImage = cvCloneImage(filter->cvImage);
cvPyrSegmentation(filter->cvImage, filter->cvSegmentedImage, filter->storage, &(filter->comp), filter->level, filter->threshold1, filter->threshold2);
gst_buffer_set_data(buf, filter->cvSegmentedImage->imageData, filter->cvSegmentedImage->imageSize);
return gst_pad_push (filter->srcpad, buf);
}
/* entry point to initialize the plug-in
* initialize the plug-in itself
* register the element factories and other features
*/
-static gboolean
-pyramidsegment_init (GstPlugin * pyramidsegment)
+gboolean
+gst_pyramidsegment_plugin_init (GstPlugin * plugin)
{
/* debug category for fltering log messages */
GST_DEBUG_CATEGORY_INIT (gst_pyramidsegment_debug, "pyramidsegment",
0, "Applies pyramid segmentation to a video or image");
- return gst_element_register (pyramidsegment, "pyramidsegment", GST_RANK_NONE,
+ return gst_element_register (plugin, "pyramidsegment", GST_RANK_NONE,
GST_TYPE_PYRAMIDSEGMENT);
}
-
-/* gstreamer looks for this structure to register pyramidsegment */
-GST_PLUGIN_DEFINE (
- GST_VERSION_MAJOR,
- GST_VERSION_MINOR,
- "pyramidsegment",
- "Applies pyramid segmentation to a video or image",
- pyramidsegment_init,
- VERSION,
- "LGPL",
- "GStreamer OpenCV Plugins",
- "http://www.mikeasoft.com"
-)
diff --git a/src/pyramidsegment/gstpyramidsegment.h b/src/pyramidsegment/gstpyramidsegment.h
index d083a62..5a04d81 100644
--- a/src/pyramidsegment/gstpyramidsegment.h
+++ b/src/pyramidsegment/gstpyramidsegment.h
@@ -1,97 +1,99 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2008 Michael Sheldon <mike@mikeasoft.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#ifndef __GST_PYRAMIDSEGMENT_H__
#define __GST_PYRAMIDSEGMENT_H__
#include <gst/gst.h>
#include <cv.h>
G_BEGIN_DECLS
/* #defines don't like whitespacey bits */
#define GST_TYPE_PYRAMIDSEGMENT \
(gst_pyramidsegment_get_type())
#define GST_PYRAMIDSEGMENT(obj) \
(G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_PYRAMIDSEGMENT,Gstpyramidsegment))
#define GST_PYRAMIDSEGMENT_CLASS(klass) \
(G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_PYRAMIDSEGMENT,GstpyramidsegmentClass))
#define GST_IS_PYRAMIDSEGMENT(obj) \
(G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_PYRAMIDSEGMENT))
#define GST_IS_PYRAMIDSEGMENT_CLASS(klass) \
(G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_PYRAMIDSEGMENT))
typedef struct _Gstpyramidsegment Gstpyramidsegment;
typedef struct _GstpyramidsegmentClass GstpyramidsegmentClass;
struct _Gstpyramidsegment
{
GstElement element;
GstPad *sinkpad, *srcpad;
gboolean silent;
IplImage *cvImage, *cvSegmentedImage;
CvMemStorage *storage;
CvSeq *comp;
double threshold1, threshold2;
int level;
};
struct _GstpyramidsegmentClass
{
GstElementClass parent_class;
};
GType gst_pyramidsegment_get_type (void);
+gboolean gst_pyramidsegment_plugin_init (GstPlugin * plugin);
+
G_END_DECLS
#endif /* __GST_PYRAMIDSEGMENT_H__ */
|
Elleo/gst-opencv
|
d2b778b6c2d2ee050f64ecbb55d3a590b94a1793
|
Fix the profile parameter in the facedetect element to accept a string correctly
|
diff --git a/ChangeLog b/ChangeLog
index 1ac8d11..9214308 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,15 +1,18 @@
2009-05-06 Mike Sheldon <mike@mikeasoft.com>
+ * src/facedetect/gstfacedetect.c:
+ Fix "profile" parameter in face detect element to accept a string correctly
+ (was using char param instead of string param)
+
* src/edgedetect/gstedgedetect.c:
- * src/pyramidsegment/gstpyramidsegemnt.c:
+ * src/pyramidsegment/gstpyramidsegment.c:
* src/facedetect/gstfacedetect.c:
-
Release OpenCV images when finalizing
2009-05-06 Kapil Agrawal <kapil@mediamagictechnologies.com>
* configure.ac: Added an error check for opencv.
* src/edgedetect/gstedgedetect.h:
* src/facedetect/gstfacedetect.h:
* src/pyramidsegment/gstpyramidsegment.h: Fixed the included path.
Fixed some compilation errors.
diff --git a/src/facedetect/gstfacedetect.c b/src/facedetect/gstfacedetect.c
index e1e6d70..1e1af4c 100644
--- a/src/facedetect/gstfacedetect.c
+++ b/src/facedetect/gstfacedetect.c
@@ -1,355 +1,353 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2008 Michael Sheldon <mike@mikeasoft.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/**
* SECTION:element-facedetect
*
* FIXME:Describe facedetect here.
*
* <refsect2>
* <title>Example launch line</title>
* |[
* gst-launch-0.10 videotestsrc ! decodebin ! ffmpegcolorspace ! facedetect ! ffmpegcolorspace ! xvimagesink
* ]|
* </refsect2>
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <gst/gst.h>
#include "gstfacedetect.h"
GST_DEBUG_CATEGORY_STATIC (gst_facedetect_debug);
#define GST_CAT_DEFAULT gst_facedetect_debug
#define DEFAULT_PROFILE "/usr/share/opencv/haarcascades/haarcascade_frontalface_default.xml"
/* Filter signals and args */
enum
{
/* FILL ME */
LAST_SIGNAL
};
enum
{
PROP_0,
PROP_DISPLAY,
PROP_PROFILE
};
/* the capabilities of the inputs and outputs.
*/
static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
GST_PAD_SINK,
GST_PAD_ALWAYS,
GST_STATIC_CAPS (
"video/x-raw-rgb"
)
);
static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
GST_PAD_SRC,
GST_PAD_ALWAYS,
GST_STATIC_CAPS (
"video/x-raw-rgb"
)
);
GST_BOILERPLATE (Gstfacedetect, gst_facedetect, GstElement,
GST_TYPE_ELEMENT);
static void gst_facedetect_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec);
static void gst_facedetect_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec);
static gboolean gst_facedetect_set_caps (GstPad * pad, GstCaps * caps);
static GstFlowReturn gst_facedetect_chain (GstPad * pad, GstBuffer * buf);
-static void gst_facedetect_load_profile (GObject * object);
+static void gst_facedetect_load_profile (Gstfacedetect * filter);
/* Clean up */
static void
gst_facedetect_finalize (GObject * obj)
{
Gstfacedetect *filter = GST_FACEDETECT(obj);
if (filter->cvImage)
{
cvReleaseImage (&filter->cvImage);
cvReleaseImage (&filter->cvGray);
}
G_OBJECT_CLASS (parent_class)->finalize (obj);
}
/* GObject vmethod implementations */
static void
gst_facedetect_base_init (gpointer gclass)
{
GstElementClass *element_class = GST_ELEMENT_CLASS (gclass);
gst_element_class_set_details_simple(element_class,
"facedetect",
"Filter/Effect/Video",
"Performs face detection on videos and images, providing detected positions via bus messages",
"Michael Sheldon <mike@mikeasoft.com>");
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&src_factory));
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&sink_factory));
}
/* initialize the facedetect's class */
static void
gst_facedetect_class_init (GstfacedetectClass * klass)
{
GObjectClass *gobject_class;
GstElementClass *gstelement_class;
gobject_class = (GObjectClass *) klass;
gstelement_class = (GstElementClass *) klass;
parent_class = g_type_class_peek_parent (klass);
gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_facedetect_finalize);
gobject_class->set_property = gst_facedetect_set_property;
gobject_class->get_property = gst_facedetect_get_property;
g_object_class_install_property (gobject_class, PROP_DISPLAY,
g_param_spec_boolean ("display", "Display", "Sets whether the detected faces should be highlighted in the output",
TRUE, G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_PROFILE,
- g_param_spec_char ("profile", "Profile", "Location of Haar cascade file to use for face detection",
- G_MININT8, G_MAXINT8, DEFAULT_PROFILE, G_PARAM_READWRITE));
+ g_param_spec_string ("profile", "Profile", "Location of Haar cascade file to use for face detection",
+ DEFAULT_PROFILE, G_PARAM_READWRITE));
}
/* initialize the new element
* instantiate pads and add them to element
* set pad calback functions
* initialize instance structure
*/
static void
gst_facedetect_init (Gstfacedetect * filter,
GstfacedetectClass * gclass)
{
filter->sinkpad = gst_pad_new_from_static_template (&sink_factory, "sink");
gst_pad_set_setcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR(gst_facedetect_set_caps));
gst_pad_set_getcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR(gst_pad_proxy_getcaps));
gst_pad_set_chain_function (filter->sinkpad,
GST_DEBUG_FUNCPTR(gst_facedetect_chain));
filter->srcpad = gst_pad_new_from_static_template (&src_factory, "src");
gst_pad_set_getcaps_function (filter->srcpad,
GST_DEBUG_FUNCPTR(gst_pad_proxy_getcaps));
gst_element_add_pad (GST_ELEMENT (filter), filter->sinkpad);
gst_element_add_pad (GST_ELEMENT (filter), filter->srcpad);
filter->profile = DEFAULT_PROFILE;
filter->display = TRUE;
gst_facedetect_load_profile(filter);
}
static void
gst_facedetect_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec)
{
Gstfacedetect *filter = GST_FACEDETECT (object);
switch (prop_id) {
case PROP_PROFILE:
- filter->profile = g_value_get_char (value);
+ filter->profile = g_value_dup_string (value);
gst_facedetect_load_profile(filter);
break;
case PROP_DISPLAY:
filter->display = g_value_get_boolean (value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gst_facedetect_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec)
{
Gstfacedetect *filter = GST_FACEDETECT (object);
switch (prop_id) {
case PROP_PROFILE:
- g_value_set_char (value, filter->profile);
+ g_value_take_string (value, filter->profile);
break;
case PROP_DISPLAY:
g_value_set_boolean (value, filter->display);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
/* GstElement vmethod implementations */
/* this function handles the link with other elements */
static gboolean
gst_facedetect_set_caps (GstPad * pad, GstCaps * caps)
{
Gstfacedetect *filter;
GstPad *otherpad;
gint width, height;
GstStructure *structure;
filter = GST_FACEDETECT (gst_pad_get_parent (pad));
structure = gst_caps_get_structure (caps, 0);
gst_structure_get_int (structure, "width", &width);
gst_structure_get_int (structure, "height", &height);
filter->cvImage = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 3);
filter->cvGray = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 1);
filter->cvStorage = cvCreateMemStorage(0);
otherpad = (pad == filter->srcpad) ? filter->sinkpad : filter->srcpad;
gst_object_unref (filter);
return gst_pad_set_caps (otherpad, caps);
}
/* chain function
* this function does the actual processing
*/
static GstFlowReturn
gst_facedetect_chain (GstPad * pad, GstBuffer * buf)
{
Gstfacedetect *filter;
CvSeq *faces;
int i;
filter = GST_FACEDETECT (GST_OBJECT_PARENT (pad));
filter->cvImage->imageData = (char *) GST_BUFFER_DATA (buf);
cvCvtColor(filter->cvImage, filter->cvGray, CV_RGB2GRAY);
cvClearMemStorage(filter->cvStorage);
if (filter->cvCascade) {
faces = cvHaarDetectObjects(filter->cvGray, filter->cvCascade, filter->cvStorage, 1.1, 2, 0, cvSize(30, 30));
for (i = 0; i < (faces ? faces->total : 0); i++) {
CvRect* r = (CvRect *) cvGetSeqElem(faces, i);
GstStructure *s = gst_structure_new ("face",
"x", G_TYPE_UINT, r->x,
"y", G_TYPE_UINT, r->y,
"width", G_TYPE_UINT, r->width,
"height", G_TYPE_UINT, r->height, NULL);
GstMessage *m = gst_message_new_element (GST_OBJECT (filter), s);
gst_element_post_message (GST_ELEMENT (filter), m);
if (filter->display) {
CvPoint center;
int radius;
center.x = cvRound((r->x + r->width*0.5));
center.y = cvRound((r->y + r->height*0.5));
radius = cvRound((r->width + r->height)*0.25);
cvCircle(filter->cvImage, center, radius, CV_RGB(255, 32, 32), 3, 8, 0);
}
}
}
gst_buffer_set_data(buf, filter->cvImage->imageData, filter->cvImage->imageSize);
return gst_pad_push (filter->srcpad, buf);
}
-static void gst_facedetect_load_profile(GObject * object) {
- Gstfacedetect *filter = GST_FACEDETECT (object);
-
+static void gst_facedetect_load_profile(Gstfacedetect * filter) {
filter->cvCascade = (CvHaarClassifierCascade*)cvLoad(filter->profile, 0, 0, 0 );
if (!filter->cvCascade) {
GST_WARNING ("Couldn't load Haar classifier cascade: %s.", filter->profile);
}
}
/* entry point to initialize the plug-in
* initialize the plug-in itself
* register the element factories and other features
*/
static gboolean
facedetect_init (GstPlugin * facedetect)
{
/* debug category for fltering log messages */
GST_DEBUG_CATEGORY_INIT (gst_facedetect_debug, "facedetect",
0, "Performs face detection on videos and images, providing detected positions via bus messages");
return gst_element_register (facedetect, "facedetect", GST_RANK_NONE,
GST_TYPE_FACEDETECT);
}
/* gstreamer looks for this structure to register facedetect */
GST_PLUGIN_DEFINE (
GST_VERSION_MAJOR,
GST_VERSION_MINOR,
"facedetect",
"Performs face detection on videos and images, providing detected positions via bus messages",
facedetect_init,
VERSION,
"LGPL",
"GStreamer OpenCV Plugins",
"http://www.mikeasoft.com/"
)
|
Elleo/gst-opencv
|
81a57797c6a901f320ceaeddf06cb50c4f60e07b
|
Release OpenCV images when finalizing elements
|
diff --git a/ChangeLog b/ChangeLog
index be865d5..1ac8d11 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,7 +1,15 @@
-2009-04-06 Kapil Agrawal <kapil@mediamagictechnologies.com>
+2009-05-06 Mike Sheldon <mike@mikeasoft.com>
+
+ * src/edgedetect/gstedgedetect.c:
+ * src/pyramidsegment/gstpyramidsegemnt.c:
+ * src/facedetect/gstfacedetect.c:
+
+ Release OpenCV images when finalizing
+
+2009-05-06 Kapil Agrawal <kapil@mediamagictechnologies.com>
* configure.ac: Added an error check for opencv.
* src/edgedetect/gstedgedetect.h:
* src/facedetect/gstfacedetect.h:
* src/pyramidsegment/gstpyramidsegment.h: Fixed the included path.
Fixed some compilation errors.
diff --git a/src/edgedetect/gstedgedetect.c b/src/edgedetect/gstedgedetect.c
index 19cae79..26b4f47 100644
--- a/src/edgedetect/gstedgedetect.c
+++ b/src/edgedetect/gstedgedetect.c
@@ -1,330 +1,347 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2008 Michael Sheldon <mike@mikeasoft.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/**
* SECTION:element-edgedetect
*
* FIXME:Describe edgedetect here.
*
* <refsect2>
* <title>Example launch line</title>
* |[
* gst-launch-0.10 videotestsrc ! decodebin ! ffmpegcolorspace ! edgedetect ! ffmpegcolorspace ! xvimagesink
* ]|
* </refsect2>
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <gst/gst.h>
#include "gstedgedetect.h"
GST_DEBUG_CATEGORY_STATIC (gst_edgedetect_debug);
#define GST_CAT_DEFAULT gst_edgedetect_debug
/* Filter signals and args */
enum
{
/* FILL ME */
LAST_SIGNAL
};
enum
{
PROP_0,
PROP_THRESHOLD1,
PROP_THRESHOLD2,
PROP_APERTURE,
PROP_MASK
};
/* the capabilities of the inputs and outputs.
*
* describe the real formats here.
*/
static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
GST_PAD_SINK,
GST_PAD_ALWAYS,
GST_STATIC_CAPS (
"video/x-raw-rgb"
)
);
static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
GST_PAD_SRC,
GST_PAD_ALWAYS,
GST_STATIC_CAPS (
"video/x-raw-rgb"
)
);
GST_BOILERPLATE (Gstedgedetect, gst_edgedetect, GstElement,
GST_TYPE_ELEMENT);
static void gst_edgedetect_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec);
static void gst_edgedetect_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec);
static gboolean gst_edgedetect_set_caps (GstPad * pad, GstCaps * caps);
static GstFlowReturn gst_edgedetect_chain (GstPad * pad, GstBuffer * buf);
-/* GObject vmethod implementations */
+/* Clean up */
+static void
+gst_edgedetect_finalize (GObject * obj)
+{
+ Gstedgedetect *filter = GST_EDGEDETECT (obj);
+
+ if (filter->cvImage != NULL)
+ {
+ cvReleaseImage (&filter->cvImage);
+ cvReleaseImage (&filter->cvCEdge);
+ cvReleaseImage (&filter->cvGray);
+ cvReleaseImage (&filter->cvEdge);
+ }
+ G_OBJECT_CLASS (parent_class)->finalize (obj);
+}
+
+/* GObject vmethod implementations */
static void
gst_edgedetect_base_init (gpointer gclass)
{
GstElementClass *element_class = GST_ELEMENT_CLASS (gclass);
gst_element_class_set_details_simple(element_class,
"edgedetect",
"Filter/Effect/Video",
"Performs canny edge detection on videos and images.",
"Michael Sheldon <mike@mikeasoft.com>");
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&src_factory));
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&sink_factory));
}
/* initialize the edgedetect's class */
static void
gst_edgedetect_class_init (GstedgedetectClass * klass)
{
GObjectClass *gobject_class;
GstElementClass *gstelement_class;
gobject_class = (GObjectClass *) klass;
gstelement_class = (GstElementClass *) klass;
+ parent_class = g_type_class_peek_parent (klass);
+ gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_edgedetect_finalize);
gobject_class->set_property = gst_edgedetect_set_property;
gobject_class->get_property = gst_edgedetect_get_property;
g_object_class_install_property (gobject_class, PROP_MASK,
g_param_spec_boolean ("mask", "Mask", "Sets whether the detected edges should be used as a mask on the original input or not",
TRUE, G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_THRESHOLD1,
g_param_spec_int ("threshold1", "Threshold1", "Threshold value for canny edge detection",
0, 1000, 50, G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_THRESHOLD2,
g_param_spec_int ("threshold2", "Threshold2", "Second threshold value for canny edge detection",
0, 1000, 150, G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_APERTURE,
g_param_spec_int ("aperture", "Aperture", "Aperture size for Sobel operator (Must be either 3, 5 or 7",
3, 7, 3, G_PARAM_READWRITE));
}
/* initialize the new element
* instantiate pads and add them to element
* set pad calback functions
* initialize instance structure
*/
static void
gst_edgedetect_init (Gstedgedetect * filter,
GstedgedetectClass * gclass)
{
filter->sinkpad = gst_pad_new_from_static_template (&sink_factory, "sink");
gst_pad_set_setcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR(gst_edgedetect_set_caps));
gst_pad_set_getcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR(gst_pad_proxy_getcaps));
gst_pad_set_chain_function (filter->sinkpad,
GST_DEBUG_FUNCPTR(gst_edgedetect_chain));
filter->srcpad = gst_pad_new_from_static_template (&src_factory, "src");
gst_pad_set_getcaps_function (filter->srcpad,
GST_DEBUG_FUNCPTR(gst_pad_proxy_getcaps));
gst_element_add_pad (GST_ELEMENT (filter), filter->sinkpad);
gst_element_add_pad (GST_ELEMENT (filter), filter->srcpad);
filter->mask = TRUE;
filter->threshold1 = 50;
filter->threshold2 = 150;
filter->aperture = 3;
}
static void
gst_edgedetect_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec)
{
Gstedgedetect *filter = GST_EDGEDETECT (object);
switch (prop_id) {
case PROP_MASK:
filter->mask = g_value_get_boolean (value);
break;
case PROP_THRESHOLD1:
filter->threshold1 = g_value_get_int (value);
break;
case PROP_THRESHOLD2:
filter->threshold2 = g_value_get_int (value);
break;
case PROP_APERTURE:
filter->aperture = g_value_get_int (value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gst_edgedetect_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec)
{
Gstedgedetect *filter = GST_EDGEDETECT (object);
switch (prop_id) {
case PROP_MASK:
g_value_set_boolean (value, filter->mask);
break;
case PROP_THRESHOLD1:
g_value_set_int (value, filter->threshold1);
break;
case PROP_THRESHOLD2:
g_value_set_int (value, filter->threshold2);
break;
case PROP_APERTURE:
g_value_set_int (value, filter->aperture);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
/* GstElement vmethod implementations */
/* this function handles the link with other elements */
static gboolean
gst_edgedetect_set_caps (GstPad * pad, GstCaps * caps)
{
Gstedgedetect *filter;
GstPad *otherpad;
gint width, height;
GstStructure *structure;
filter = GST_EDGEDETECT (gst_pad_get_parent (pad));
structure = gst_caps_get_structure (caps, 0);
gst_structure_get_int (structure, "width", &width);
gst_structure_get_int (structure, "height", &height);
filter->cvImage = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 3);
filter->cvCEdge = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 3);
filter->cvGray = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 1);
filter->cvEdge = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 1);
otherpad = (pad == filter->srcpad) ? filter->sinkpad : filter->srcpad;
gst_object_unref (filter);
return gst_pad_set_caps (otherpad, caps);
}
/* chain function
* this function does the actual processing
*/
static GstFlowReturn
gst_edgedetect_chain (GstPad * pad, GstBuffer * buf)
{
Gstedgedetect *filter;
filter = GST_EDGEDETECT (GST_OBJECT_PARENT (pad));
filter->cvImage->imageData = (char *) GST_BUFFER_DATA (buf);
cvCvtColor(filter->cvImage, filter->cvGray, CV_RGB2GRAY);
cvSmooth(filter->cvGray, filter->cvEdge, CV_BLUR, 3, 3, 0, 0 );
cvNot(filter->cvGray, filter->cvEdge);
cvCanny(filter->cvGray, filter->cvEdge, filter->threshold1, filter->threshold2, filter->aperture);
cvZero(filter->cvCEdge);
if(filter-> mask) {
cvCopy(filter->cvImage, filter->cvCEdge, filter->cvEdge);
} else {
cvCvtColor(filter->cvEdge, filter->cvCEdge, CV_GRAY2RGB);
}
gst_buffer_set_data(buf, filter->cvCEdge->imageData, filter->cvCEdge->imageSize);
return gst_pad_push (filter->srcpad, buf);
}
-
/* entry point to initialize the plug-in
* initialize the plug-in itself
* register the element factories and other features
*/
static gboolean
edgedetect_init (GstPlugin * edgedetect)
{
/* debug category for fltering log messages
*
* exchange the string 'Template edgedetect' with your description
*/
GST_DEBUG_CATEGORY_INIT (gst_edgedetect_debug, "edgedetect",
0, "Performs canny edge detection on videos and images");
return gst_element_register (edgedetect, "edgedetect", GST_RANK_NONE,
GST_TYPE_EDGEDETECT);
}
/* gstreamer looks for this structure to register edgedetects
*
* exchange the string 'Template edgedetect' with your edgedetect description
*/
GST_PLUGIN_DEFINE (
GST_VERSION_MAJOR,
GST_VERSION_MINOR,
"edgedetect",
"Performs canny edge detection on videos and images",
edgedetect_init,
VERSION,
"LGPL",
"GStreamer OpenCV Plugins",
"http://www.mikeasoft.com/"
)
diff --git a/src/facedetect/gstfacedetect.c b/src/facedetect/gstfacedetect.c
index 0125c28..e1e6d70 100644
--- a/src/facedetect/gstfacedetect.c
+++ b/src/facedetect/gstfacedetect.c
@@ -1,338 +1,355 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2008 Michael Sheldon <mike@mikeasoft.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/**
* SECTION:element-facedetect
*
* FIXME:Describe facedetect here.
*
* <refsect2>
* <title>Example launch line</title>
* |[
* gst-launch-0.10 videotestsrc ! decodebin ! ffmpegcolorspace ! facedetect ! ffmpegcolorspace ! xvimagesink
* ]|
* </refsect2>
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <gst/gst.h>
#include "gstfacedetect.h"
GST_DEBUG_CATEGORY_STATIC (gst_facedetect_debug);
#define GST_CAT_DEFAULT gst_facedetect_debug
#define DEFAULT_PROFILE "/usr/share/opencv/haarcascades/haarcascade_frontalface_default.xml"
/* Filter signals and args */
enum
{
/* FILL ME */
LAST_SIGNAL
};
enum
{
PROP_0,
PROP_DISPLAY,
PROP_PROFILE
};
/* the capabilities of the inputs and outputs.
*/
static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
GST_PAD_SINK,
GST_PAD_ALWAYS,
GST_STATIC_CAPS (
"video/x-raw-rgb"
)
);
static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
GST_PAD_SRC,
GST_PAD_ALWAYS,
GST_STATIC_CAPS (
"video/x-raw-rgb"
)
);
GST_BOILERPLATE (Gstfacedetect, gst_facedetect, GstElement,
GST_TYPE_ELEMENT);
static void gst_facedetect_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec);
static void gst_facedetect_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec);
static gboolean gst_facedetect_set_caps (GstPad * pad, GstCaps * caps);
static GstFlowReturn gst_facedetect_chain (GstPad * pad, GstBuffer * buf);
static void gst_facedetect_load_profile (GObject * object);
-/* GObject vmethod implementations */
+/* Clean up */
+static void
+gst_facedetect_finalize (GObject * obj)
+{
+ Gstfacedetect *filter = GST_FACEDETECT(obj);
+
+ if (filter->cvImage)
+ {
+ cvReleaseImage (&filter->cvImage);
+ cvReleaseImage (&filter->cvGray);
+ }
+ G_OBJECT_CLASS (parent_class)->finalize (obj);
+}
+
+
+/* GObject vmethod implementations */
static void
gst_facedetect_base_init (gpointer gclass)
{
GstElementClass *element_class = GST_ELEMENT_CLASS (gclass);
gst_element_class_set_details_simple(element_class,
"facedetect",
"Filter/Effect/Video",
"Performs face detection on videos and images, providing detected positions via bus messages",
"Michael Sheldon <mike@mikeasoft.com>");
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&src_factory));
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&sink_factory));
}
/* initialize the facedetect's class */
static void
gst_facedetect_class_init (GstfacedetectClass * klass)
{
GObjectClass *gobject_class;
GstElementClass *gstelement_class;
gobject_class = (GObjectClass *) klass;
gstelement_class = (GstElementClass *) klass;
+ parent_class = g_type_class_peek_parent (klass);
+ gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_facedetect_finalize);
gobject_class->set_property = gst_facedetect_set_property;
gobject_class->get_property = gst_facedetect_get_property;
g_object_class_install_property (gobject_class, PROP_DISPLAY,
g_param_spec_boolean ("display", "Display", "Sets whether the detected faces should be highlighted in the output",
TRUE, G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_PROFILE,
g_param_spec_char ("profile", "Profile", "Location of Haar cascade file to use for face detection",
G_MININT8, G_MAXINT8, DEFAULT_PROFILE, G_PARAM_READWRITE));
}
/* initialize the new element
* instantiate pads and add them to element
* set pad calback functions
* initialize instance structure
*/
static void
gst_facedetect_init (Gstfacedetect * filter,
GstfacedetectClass * gclass)
{
filter->sinkpad = gst_pad_new_from_static_template (&sink_factory, "sink");
gst_pad_set_setcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR(gst_facedetect_set_caps));
gst_pad_set_getcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR(gst_pad_proxy_getcaps));
gst_pad_set_chain_function (filter->sinkpad,
GST_DEBUG_FUNCPTR(gst_facedetect_chain));
filter->srcpad = gst_pad_new_from_static_template (&src_factory, "src");
gst_pad_set_getcaps_function (filter->srcpad,
GST_DEBUG_FUNCPTR(gst_pad_proxy_getcaps));
gst_element_add_pad (GST_ELEMENT (filter), filter->sinkpad);
gst_element_add_pad (GST_ELEMENT (filter), filter->srcpad);
filter->profile = DEFAULT_PROFILE;
filter->display = TRUE;
gst_facedetect_load_profile(filter);
}
static void
gst_facedetect_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec)
{
Gstfacedetect *filter = GST_FACEDETECT (object);
switch (prop_id) {
case PROP_PROFILE:
filter->profile = g_value_get_char (value);
gst_facedetect_load_profile(filter);
break;
case PROP_DISPLAY:
filter->display = g_value_get_boolean (value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gst_facedetect_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec)
{
Gstfacedetect *filter = GST_FACEDETECT (object);
switch (prop_id) {
case PROP_PROFILE:
g_value_set_char (value, filter->profile);
break;
case PROP_DISPLAY:
g_value_set_boolean (value, filter->display);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
/* GstElement vmethod implementations */
/* this function handles the link with other elements */
static gboolean
gst_facedetect_set_caps (GstPad * pad, GstCaps * caps)
{
Gstfacedetect *filter;
GstPad *otherpad;
gint width, height;
GstStructure *structure;
filter = GST_FACEDETECT (gst_pad_get_parent (pad));
structure = gst_caps_get_structure (caps, 0);
gst_structure_get_int (structure, "width", &width);
gst_structure_get_int (structure, "height", &height);
filter->cvImage = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 3);
filter->cvGray = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 1);
filter->cvStorage = cvCreateMemStorage(0);
otherpad = (pad == filter->srcpad) ? filter->sinkpad : filter->srcpad;
gst_object_unref (filter);
return gst_pad_set_caps (otherpad, caps);
}
/* chain function
* this function does the actual processing
*/
static GstFlowReturn
gst_facedetect_chain (GstPad * pad, GstBuffer * buf)
{
Gstfacedetect *filter;
CvSeq *faces;
int i;
filter = GST_FACEDETECT (GST_OBJECT_PARENT (pad));
filter->cvImage->imageData = (char *) GST_BUFFER_DATA (buf);
cvCvtColor(filter->cvImage, filter->cvGray, CV_RGB2GRAY);
cvClearMemStorage(filter->cvStorage);
if (filter->cvCascade) {
faces = cvHaarDetectObjects(filter->cvGray, filter->cvCascade, filter->cvStorage, 1.1, 2, 0, cvSize(30, 30));
for (i = 0; i < (faces ? faces->total : 0); i++) {
CvRect* r = (CvRect *) cvGetSeqElem(faces, i);
GstStructure *s = gst_structure_new ("face",
"x", G_TYPE_UINT, r->x,
"y", G_TYPE_UINT, r->y,
"width", G_TYPE_UINT, r->width,
"height", G_TYPE_UINT, r->height, NULL);
GstMessage *m = gst_message_new_element (GST_OBJECT (filter), s);
gst_element_post_message (GST_ELEMENT (filter), m);
if (filter->display) {
CvPoint center;
int radius;
center.x = cvRound((r->x + r->width*0.5));
center.y = cvRound((r->y + r->height*0.5));
radius = cvRound((r->width + r->height)*0.25);
cvCircle(filter->cvImage, center, radius, CV_RGB(255, 32, 32), 3, 8, 0);
}
}
}
gst_buffer_set_data(buf, filter->cvImage->imageData, filter->cvImage->imageSize);
return gst_pad_push (filter->srcpad, buf);
}
static void gst_facedetect_load_profile(GObject * object) {
Gstfacedetect *filter = GST_FACEDETECT (object);
filter->cvCascade = (CvHaarClassifierCascade*)cvLoad(filter->profile, 0, 0, 0 );
if (!filter->cvCascade) {
GST_WARNING ("Couldn't load Haar classifier cascade: %s.", filter->profile);
}
}
/* entry point to initialize the plug-in
* initialize the plug-in itself
* register the element factories and other features
*/
static gboolean
facedetect_init (GstPlugin * facedetect)
{
/* debug category for fltering log messages */
GST_DEBUG_CATEGORY_INIT (gst_facedetect_debug, "facedetect",
0, "Performs face detection on videos and images, providing detected positions via bus messages");
return gst_element_register (facedetect, "facedetect", GST_RANK_NONE,
GST_TYPE_FACEDETECT);
}
/* gstreamer looks for this structure to register facedetect */
GST_PLUGIN_DEFINE (
GST_VERSION_MAJOR,
GST_VERSION_MINOR,
"facedetect",
"Performs face detection on videos and images, providing detected positions via bus messages",
facedetect_init,
VERSION,
"LGPL",
"GStreamer OpenCV Plugins",
"http://www.mikeasoft.com/"
)
diff --git a/src/pyramidsegment/gstpyramidsegment.c b/src/pyramidsegment/gstpyramidsegment.c
index 43dd502..811baea 100644
--- a/src/pyramidsegment/gstpyramidsegment.c
+++ b/src/pyramidsegment/gstpyramidsegment.c
@@ -1,317 +1,333 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2008 Michael Sheldon <mike@mikeasoft.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/**
* SECTION:element-pyramidsegment
*
* FIXME:Describe pyramidsegment here.
*
* <refsect2>
* <title>Example launch line</title>
* |[
* gst-launch -v -m fakesrc ! pyramidsegment ! fakesink silent=TRUE
* ]|
* </refsect2>
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <gst/gst.h>
#include "gstpyramidsegment.h"
#define BLOCK_SIZE 1000
GST_DEBUG_CATEGORY_STATIC (gst_pyramidsegment_debug);
#define GST_CAT_DEFAULT gst_pyramidsegment_debug
/* Filter signals and args */
enum
{
/* FILL ME */
LAST_SIGNAL
};
enum
{
PROP_0,
PROP_SILENT,
PROP_THRESHOLD1,
PROP_THRESHOLD2,
PROP_LEVEL
};
/* the capabilities of the inputs and outputs.
*
* describe the real formats here.
*/
static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
GST_PAD_SINK,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("video/x-raw-rgb")
);
static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
GST_PAD_SRC,
GST_PAD_ALWAYS,
GST_STATIC_CAPS ("video/x-raw-rgb")
);
GST_BOILERPLATE (Gstpyramidsegment, gst_pyramidsegment, GstElement,
GST_TYPE_ELEMENT);
static void gst_pyramidsegment_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec);
static void gst_pyramidsegment_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec);
static gboolean gst_pyramidsegment_set_caps (GstPad * pad, GstCaps * caps);
static GstFlowReturn gst_pyramidsegment_chain (GstPad * pad, GstBuffer * buf);
-/* GObject vmethod implementations */
+/* Clean up */
+static void
+gst_pyramidsegment_finalize (GObject * obj)
+{
+ Gstpyramidsegment *filter = GST_PYRAMIDSEGMENT(obj);
+
+ if (filter->cvImage != NULL)
+ {
+ cvReleaseImage (&filter->cvImage);
+ cvReleaseImage (&filter->cvSegmentedImage);
+ }
+
+ G_OBJECT_CLASS (parent_class)->finalize (obj);
+}
+/* GObject vmethod implementations */
static void
gst_pyramidsegment_base_init (gpointer gclass)
{
GstElementClass *element_class = GST_ELEMENT_CLASS (gclass);
gst_element_class_set_details_simple(element_class,
"pyramidsegment",
"Filter/Effect/Video",
"Applies pyramid segmentation to a video or image.",
"Michael Sheldon <mike@mikeasoft.com>");
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&src_factory));
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&sink_factory));
}
/* initialize the pyramidsegment's class */
static void
gst_pyramidsegment_class_init (GstpyramidsegmentClass * klass)
{
GObjectClass *gobject_class;
GstElementClass *gstelement_class;
gobject_class = (GObjectClass *) klass;
gstelement_class = (GstElementClass *) klass;
+ parent_class = g_type_class_peek_parent (klass);
+ gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_pyramidsegment_finalize);
gobject_class->set_property = gst_pyramidsegment_set_property;
gobject_class->get_property = gst_pyramidsegment_get_property;
g_object_class_install_property (gobject_class, PROP_SILENT,
g_param_spec_boolean ("silent", "Silent", "Produce verbose output ?",
FALSE, G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_THRESHOLD1,
g_param_spec_double ("threshold1", "Threshold1", "Error threshold for establishing links",
0, 1000, 50, G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_THRESHOLD2,
g_param_spec_double ("threshold2", "Threshold2", "Error threshold for segment clustering",
0, 1000, 60, G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_LEVEL,
g_param_spec_int ("level", "Level", "Maximum level of the pyramid segmentation",
0, 4, 4, G_PARAM_READWRITE));
}
/* initialize the new element
* instantiate pads and add them to element
* set pad calback functions
* initialize instance structure
*/
static void
gst_pyramidsegment_init (Gstpyramidsegment * filter,
GstpyramidsegmentClass * gclass)
{
filter->sinkpad = gst_pad_new_from_static_template (&sink_factory, "sink");
gst_pad_set_setcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR(gst_pyramidsegment_set_caps));
gst_pad_set_getcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR(gst_pad_proxy_getcaps));
gst_pad_set_chain_function (filter->sinkpad,
GST_DEBUG_FUNCPTR(gst_pyramidsegment_chain));
filter->srcpad = gst_pad_new_from_static_template (&src_factory, "src");
gst_pad_set_getcaps_function (filter->srcpad,
GST_DEBUG_FUNCPTR(gst_pad_proxy_getcaps));
gst_element_add_pad (GST_ELEMENT (filter), filter->sinkpad);
gst_element_add_pad (GST_ELEMENT (filter), filter->srcpad);
filter->storage = cvCreateMemStorage ( BLOCK_SIZE );
filter->comp = cvCreateSeq(0, sizeof(CvSeq), sizeof(CvPoint), filter->storage);
filter->silent = FALSE;
filter->threshold1 = 50.0;
filter->threshold2 = 60.0;
filter->level = 4;
}
static void
gst_pyramidsegment_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec)
{
Gstpyramidsegment *filter = GST_PYRAMIDSEGMENT (object);
switch (prop_id) {
case PROP_SILENT:
filter->silent = g_value_get_boolean (value);
break;
case PROP_THRESHOLD1:
filter->threshold1 = g_value_get_double (value);
break;
case PROP_THRESHOLD2:
filter->threshold2 = g_value_get_double (value);
break;
case PROP_LEVEL:
filter->level = g_value_get_int (value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gst_pyramidsegment_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec)
{
Gstpyramidsegment *filter = GST_PYRAMIDSEGMENT (object);
switch (prop_id) {
case PROP_SILENT:
g_value_set_boolean (value, filter->silent);
break;
case PROP_THRESHOLD1:
g_value_set_double (value, filter->threshold1);
break;
case PROP_THRESHOLD2:
g_value_set_double (value, filter->threshold2);
break;
case PROP_LEVEL:
g_value_set_int (value, filter->level);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
/* GstElement vmethod implementations */
/* this function handles the link with other elements */
static gboolean
gst_pyramidsegment_set_caps (GstPad * pad, GstCaps * caps)
{
Gstpyramidsegment *filter;
GstPad *otherpad;
GstStructure *structure;
gint width, height;
filter = GST_PYRAMIDSEGMENT (gst_pad_get_parent (pad));
structure = gst_caps_get_structure (caps, 0);
gst_structure_get_int (structure, "width", &width);
gst_structure_get_int (structure, "height", &height);
filter->cvImage = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 3);
otherpad = (pad == filter->srcpad) ? filter->sinkpad : filter->srcpad;
gst_object_unref (filter);
return gst_pad_set_caps (otherpad, caps);
}
/* chain function
* this function does the actual processing
*/
static GstFlowReturn
gst_pyramidsegment_chain (GstPad * pad, GstBuffer * buf)
{
Gstpyramidsegment *filter;
filter = GST_PYRAMIDSEGMENT (GST_OBJECT_PARENT (pad));
filter->cvImage->imageData = (char *) GST_BUFFER_DATA (buf);
filter->cvSegmentedImage = cvCloneImage(filter->cvImage);
cvPyrSegmentation(filter->cvImage, filter->cvSegmentedImage, filter->storage, &(filter->comp), filter->level, filter->threshold1, filter->threshold2);
gst_buffer_set_data(buf, filter->cvSegmentedImage->imageData, filter->cvSegmentedImage->imageSize);
return gst_pad_push (filter->srcpad, buf);
}
/* entry point to initialize the plug-in
* initialize the plug-in itself
* register the element factories and other features
*/
static gboolean
pyramidsegment_init (GstPlugin * pyramidsegment)
{
/* debug category for fltering log messages */
GST_DEBUG_CATEGORY_INIT (gst_pyramidsegment_debug, "pyramidsegment",
0, "Applies pyramid segmentation to a video or image");
return gst_element_register (pyramidsegment, "pyramidsegment", GST_RANK_NONE,
GST_TYPE_PYRAMIDSEGMENT);
}
/* gstreamer looks for this structure to register pyramidsegment */
GST_PLUGIN_DEFINE (
GST_VERSION_MAJOR,
GST_VERSION_MINOR,
"pyramidsegment",
"Applies pyramid segmentation to a video or image",
pyramidsegment_init,
VERSION,
"LGPL",
"GStreamer OpenCV Plugins",
"http://www.mikeasoft.com"
)
|
Elleo/gst-opencv
|
0b2ec7a5b38225278b3941151d4e66888c92a0e3
|
Fixed compile errors
|
diff --git a/ChangeLog b/ChangeLog
index fd587e4..be865d5 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,207 +1,7 @@
-2008-08-11 Stefan Kost <ensonic@users.sf.net>
+2009-04-06 Kapil Agrawal <kapil@mediamagictechnologies.com>
- * README:
- * src/gstaudiofilter.c:
- * src/gstplugin.c:
- * src/gsttransform.c:
- * tools/make_element:
- Integrate new template and improve search'n'replace ops. Update
- templates to use current API.
-
-2008-07-26 Stefan Kost <ensonic@users.sf.net>
-
- * tools/make_element:
- Fix username detection. tries getent first and falls back to grep
- passwd. Spotted by Karoly Segesdi.
-
-2008-06-09 Jan Schmidt <jan.schmidt@sun.com>
-
- * src/gstplugin.c:
- Fix some memory leaks, and make the setcaps function actually
- sets the caps on the other pad.
-
-2008-05-08 Stefan Kost <ensonic@users.sf.net>
-
- * README:
- Add simple usage explanation and make it look like the other READMEs.
-
- * src/gstplugin.c:
- * src/gstplugin.h:
- * src/gsttransform.c:
- * src/gsttransform.h:
- * tools/make_element:
- Add year, username and email fields. Update the templates here and
- there a bit. Add more comments.
-
-2007-08-01 Tim-Philipp Müller <tim at centricular dot net>
-
- * src/gsttransform.c:
- Include right header to avoid structure size mismatches etc.
-
-2007-07-25 Tim-Philipp Müller <tim at centricular dot net>
-
- Patch by: Steve Fink <sphink gmail com>
-
- * src/gstplugin.c:
- Use GST_DEBUG_FUNCPTR() macros where it makes sense.
-
-2007-07-19 Stefan Kost <ensonic@users.sf.net>
-
- * configure.ac:
- Fix CVS-build detection.
-
-2007-01-23 Tim-Philipp Müller <tim at centricular dot net>
-
- * src/Makefile.am:
- Make clearer which Makefile variables need renaming if the plugin
- name is changes (#399746) (pretty it is not, but it's the content
- that counts, right?)
-
-2007-01-22 Tim-Philipp Müller <tim at centricular dot net>
-
- Patch by: Philip Jägenstedt <philipj at opera com>
-
- * tools/make_element:
- Translate FOO_IS_MY_PLUGIN macro as well according to the template
- (#399323).
-
-2006-07-04 Tim-Philipp Müller <tim at centricular dot net>
-
- * autogen.sh:
- Run autoheader to create config.h.in and fix the build.`
-
-2006-07-03 Tim-Philipp Müller <tim at centricular dot net>
-
- * Makefile.am:
- * autogen.sh:
- * gst-autogen.sh:
- Throw an error if autotools versions are too old. We require
- automake 1.7 or newer (#346054). Add gst-autogen.sh to check
- for this.
-
- * COPYING:
- Add placeholder COPYING file so it doesn't get overwritten
- by a GPL one by automake.
-
-2006-06-22 Tim-Philipp Müller <tim at centricular dot net>
-
- Patch by: Philip Jägenstedt <philip at lysator liu se>
-
- * src/gstplugin.c: (gst_plugin_template_base_init),
- (gst_plugin_template_class_init), (gst_plugin_template_init),
- (plugin_init):
- Use GST_BOILERPLATE, add debug category (#345601).
-
-2006-04-20 Stefan Kost <ensonic@users.sf.net>
-
- Patch by: Johan Rydberg <jrydberg@gnu.org>
-
- * src/gstplugin.c: (gst_plugin_template_get_type),
- (gst_plugin_template_base_init), (gst_plugin_template_class_init),
- (gst_plugin_template_set_property),
- (gst_plugin_template_get_property):
- * src/gstplugin.h:
- * src/gsttransform.c: (gst_plugin_template_base_init),
- (gst_plugin_template_set_property),
- (gst_plugin_template_get_property):
- * tools/make_element:
- remove double gst_get_, fix '_' in names
-
-
-2006-02-26 Tim-Philipp Müller <tim at centricular dot net>
-
- * src/gstplugin.c: (gst_plugin_template_init),
- (gst_plugin_template_chain):
- Fix function declaration of _init() function.
- Remove unnecessary assertion clutter in chain function
- (that also failed to return a flow value, causing
- compiler warnings).
-
-2006-02-07 Stefan Kost <ensonic@users.sf.net>
-
- * src/gstplugin.c: (gst_plugin_template_set_caps),
- (gst_plugin_template_chain):
- * src/gsttransform.c: (gst_plugin_template_transform_ip):
- more code cleanups, more comments
-
-2006-02-07 Stefan Kost <ensonic@users.sf.net>
-
- * configure.ac:
- allow installing to $HOME
- * src/gstplugin.c: (gst_plugin_template_base_init),
- (gst_plugin_template_init):
- * src/gstplugin.h:
- * src/gsttransform.c: (gst_plugin_template_base_init),
- (gst_plugin_template_class_init), (gst_plugin_template_init),
- (gst_plugin_template_transform_ip),
- (gst_plugin_template_set_property),
- (gst_plugin_template_get_property), (plugin_init):
- * src/gsttransform.h:
- add another template
- * tools/make_element:
- fix generator, when template (arg2) is given
-
-2006-01-23 Tim-Philipp Müller <tim at centricular dot net>
-
- * src/gstplugin.h:
- FOO_BAR_CLASS(klass) should cast to FooBarClass*,
- not FooBar*.
-
-2006-01-13 Thomas Vander Stichele <thomas at apestaart dot org>
-
- * autogen.sh:
- * configure.ac:
- * src/Makefile.am:
- * src/gstplugin.c:
- bring into the 0.10 world
- Fix #315582
-
-2005-12-16 Jan Schmidt <thaytan@mad.scientist.com>
-
- * src/gstplugin.c: (gst_plugin_template_class_init):
- Need to have the set_property and get_property methods
- before installing properties
-
-2005-12-14 Tim-Philipp Müller <tim at centricular dot net>
-
- * src/gstplugin.h:
- Fix GST_IS_FOO_BAR_CLASS macro.
-
-2005-06-30 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
-
- * configure.ac:
- * src/gstplugin.c: (gst_plugin_template_set_caps),
- (gst_plugin_template_init), (gst_plugin_template_chain):
- Fix for GStreamer 0.9.
-
-2004-04-22 Thomas Vander Stichele <thomas at apestaart dot org>
-
- * Makefile.am:
- * autogen.sh:
- * configure.ac:
- * src/Makefile.am:
- use proper LDFLAGS for plugins
- run in maintainer mode by default
-
-2004-04-22 Thomas Vander Stichele <thomas at apestaart dot org>
-
- * configure.ac: ... and fix comments too
-
-2004-04-03 Benjamin Otte <otte@gnome.org>
-
- * configure.ac:
- update for GStreamer 0.8
-
-2004-01-25 Ronald Bultje <rbultje@ronald.bitfreak.net>
-
- * src/gstplugin.c: (gst_plugin_template_link),
- (gst_plugin_template_base_init), (gst_plugin_template_init):
- Fix for GStreamer 0.7.x.
-
-2003-02-06 Thomas Vander Stichele <thomas at apestaart dot org>
-
- * updated for GStreamer 0.6.0
-
-2002-07-17 Thomas Vander Stichele <thomas at apestaart dot org>
-
- * initial creation on a flight to New York
+ * configure.ac: Added an error check for opencv.
+ * src/edgedetect/gstedgedetect.h:
+ * src/facedetect/gstfacedetect.h:
+ * src/pyramidsegment/gstpyramidsegment.h: Fixed the included path.
+ Fixed some compilation errors.
diff --git a/configure.ac b/configure.ac
index 5adbe37..afe64cb 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1,142 +1,142 @@
AC_INIT
dnl versions of gstreamer and plugins-base
GST_MAJORMINOR=0.10
GST_REQUIRED=0.10.0
GSTPB_REQUIRED=0.10.0
dnl fill in your package name and version here
dnl the fourth (nano) number should be 0 for a release, 1 for CVS,
dnl and 2... for a prerelease
dnl when going to/from release please set the nano correctly !
dnl releases only do Wall, cvs and prerelease does Werror too
AS_VERSION(gst-edgedetect, GST_PLUGIN_VERSION, 0, 10, 0, 1,
GST_PLUGIN_CVS="no", GST_PLUGIN_CVS="yes")
dnl AM_MAINTAINER_MODE provides the option to enable maintainer mode
AM_MAINTAINER_MODE
AM_INIT_AUTOMAKE($PACKAGE, $VERSION)
dnl make aclocal work in maintainer mode
AC_SUBST(ACLOCAL_AMFLAGS, "-I m4")
AM_CONFIG_HEADER(config.h)
dnl check for tools
AC_PROG_CC
AC_PROG_LIBTOOL
dnl decide on error flags
AS_COMPILER_FLAG(-Wall, GST_WALL="yes", GST_WALL="no")
if test "x$GST_WALL" = "xyes"; then
GST_ERROR="$GST_ERROR -Wall"
# if test "x$GST_PLUGIN_CVS" = "xyes"; then
# AS_COMPILER_FLAG(-Werror,GST_ERROR="$GST_ERROR -Werror",GST_ERROR="$GST_ERROR")
# fi
fi
dnl Check for pkgconfig first
AC_CHECK_PROG(HAVE_PKGCONFIG, pkg-config, yes, no)
dnl Give error and exit if we don't have pkgconfig
if test "x$HAVE_PKGCONFIG" = "xno"; then
AC_MSG_ERROR(you need to have pkgconfig installed !)
fi
dnl Now we're ready to ask for gstreamer libs and cflags
dnl And we can also ask for the right version of gstreamer
PKG_CHECK_MODULES(GST, \
gstreamer-$GST_MAJORMINOR >= $GST_REQUIRED,
HAVE_GST=yes,HAVE_GST=no)
dnl Give error and exit if we don't have gstreamer
if test "x$HAVE_GST" = "xno"; then
AC_MSG_ERROR(you need gstreamer development packages installed !)
fi
dnl append GST_ERROR cflags to GST_CFLAGS
GST_CFLAGS="$GST_CFLAGS $GST_ERROR"
dnl make GST_CFLAGS and GST_LIBS available
AC_SUBST(GST_CFLAGS)
AC_SUBST(GST_LIBS)
dnl make GST_MAJORMINOR available in Makefile.am
AC_SUBST(GST_MAJORMINOR)
dnl If we need them, we can also use the base class libraries
PKG_CHECK_MODULES(GST_BASE, gstreamer-base-$GST_MAJORMINOR >= $GST_REQUIRED,
HAVE_GST_BASE=yes, HAVE_GST_BASE=no)
dnl Give a warning if we don't have gstreamer libs
dnl you can turn this into an error if you need them
if test "x$HAVE_GST_BASE" = "xno"; then
AC_MSG_NOTICE(no GStreamer base class libraries found (gstreamer-base-$GST_MAJORMINOR))
fi
dnl make _CFLAGS and _LIBS available
AC_SUBST(GST_BASE_CFLAGS)
AC_SUBST(GST_BASE_LIBS)
PKG_CHECK_MODULES(OPENCV,
opencv,
HAVE_OPENCV=yes, HAVE_OPENCV=no)
AC_SUBST(OPENCV_CFLAGS)
AC_SUBST(OPENCV_LIBS)
if test "x$HAVE_OPENCV" = "xno"; then
- AC_MSG_NOTICE(OpenCV libraries could not be found)
+ AC_MSG_ERROR(OpenCV libraries could not be found)
fi
dnl If we need them, we can also use the gstreamer-plugins-base libraries
PKG_CHECK_MODULES(GSTPB_BASE,
gstreamer-plugins-base-$GST_MAJORMINOR >= $GSTPB_REQUIRED,
HAVE_GSTPB_BASE=yes, HAVE_GSTPB_BASE=no)
dnl Give a warning if we don't have gstreamer libs
dnl you can turn this into an error if you need them
if test "x$HAVE_GSTPB_BASE" = "xno"; then
AC_MSG_NOTICE(no GStreamer Plugins Base libraries found (gstreamer-plugins-base-$GST_MAJORMINOR))
fi
dnl make _CFLAGS and _LIBS available
AC_SUBST(GSTPB_BASE_CFLAGS)
AC_SUBST(GSTPB_BASE_LIBS)
dnl If we need them, we can also use the gstreamer-controller libraries
PKG_CHECK_MODULES(GSTCTRL,
gstreamer-controller-$GST_MAJORMINOR >= $GSTPB_REQUIRED,
HAVE_GSTCTRL=yes, HAVE_GSTCTRL=no)
dnl Give a warning if we don't have gstreamer-controller
dnl you can turn this into an error if you need them
if test "x$HAVE_GSTCTRL" = "xno"; then
AC_MSG_NOTICE(no GStreamer Controller libraries found (gstreamer-controller-$GST_MAJORMINOR))
fi
dnl make _CFLAGS and _LIBS available
AC_SUBST(GSTCTRL_CFLAGS)
AC_SUBST(GSTCTRL_LIBS)
dnl set the plugindir where plugins should be installed
if test "x${prefix}" = "x$HOME"; then
plugindir="$HOME/.gstreamer-$GST_MAJORMINOR/plugins"
else
plugindir="\$(libdir)/gstreamer-$GST_MAJORMINOR"
fi
AC_SUBST(plugindir)
dnl set proper LDFLAGS for plugins
GST_PLUGIN_LDFLAGS='-module -avoid-version -export-symbols-regex [_]*\(gst_\|Gst\|GST_\).*'
AC_SUBST(GST_PLUGIN_LDFLAGS)
AC_OUTPUT(Makefile m4/Makefile src/Makefile src/edgedetect/Makefile src/pyramidsegment/Makefile src/facedetect/Makefile)
diff --git a/src/edgedetect/gstedgedetect.h b/src/edgedetect/gstedgedetect.h
index ceefe51..5931bf1 100644
--- a/src/edgedetect/gstedgedetect.h
+++ b/src/edgedetect/gstedgedetect.h
@@ -1,91 +1,91 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2008 Michael Sheldon <mike@mikeasoft.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#ifndef __GST_EDGEDETECT_H__
#define __GST_EDGEDETECT_H__
#include <gst/gst.h>
-#include <opencv/cv.h>
+#include <cv.h>
G_BEGIN_DECLS
/* #defines don't like whitespacey bits */
#define GST_TYPE_EDGEDETECT \
(gst_edgedetect_get_type())
#define GST_EDGEDETECT(obj) \
(G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_EDGEDETECT,Gstedgedetect))
#define GST_EDGEDETECT_CLASS(klass) \
(G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_EDGEDETECT,GstedgedetectClass))
#define GST_IS_EDGEDETECT(obj) \
(G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_EDGEDETECT))
#define GST_IS_EDGEDETECT_CLASS(klass) \
(G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_EDGEDETECT))
typedef struct _Gstedgedetect Gstedgedetect;
typedef struct _GstedgedetectClass GstedgedetectClass;
struct _Gstedgedetect
{
GstElement element;
GstPad *sinkpad, *srcpad;
gboolean mask;
int threshold1, threshold2, aperture;
IplImage *cvEdge, *cvGray, *cvImage, *cvCEdge;
};
struct _GstedgedetectClass
{
GstElementClass parent_class;
};
GType gst_edgedetect_get_type (void);
G_END_DECLS
#endif /* __GST_EDGEDETECT_H__ */
diff --git a/src/facedetect/gstfacedetect.h b/src/facedetect/gstfacedetect.h
index 7c15cca..97e9e02 100644
--- a/src/facedetect/gstfacedetect.h
+++ b/src/facedetect/gstfacedetect.h
@@ -1,93 +1,93 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2008 Michael Sheldon <mike@mikeasoft.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#ifndef __GST_FACEDETECT_H__
#define __GST_FACEDETECT_H__
#include <gst/gst.h>
-#include <opencv/cv.h>
+#include <cv.h>
G_BEGIN_DECLS
/* #defines don't like whitespacey bits */
#define GST_TYPE_FACEDETECT \
(gst_facedetect_get_type())
#define GST_FACEDETECT(obj) \
(G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_FACEDETECT,Gstfacedetect))
#define GST_FACEDETECT_CLASS(klass) \
(G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_FACEDETECT,GstfacedetectClass))
#define GST_IS_FACEDETECT(obj) \
(G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_FACEDETECT))
#define GST_IS_FACEDETECT_CLASS(klass) \
(G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_FACEDETECT))
typedef struct _Gstfacedetect Gstfacedetect;
typedef struct _GstfacedetectClass GstfacedetectClass;
struct _Gstfacedetect
{
GstElement element;
GstPad *sinkpad, *srcpad;
gboolean display;
gchar *profile;
IplImage *cvImage, *cvGray;
CvHaarClassifierCascade *cvCascade;
CvMemStorage *cvStorage;
};
struct _GstfacedetectClass
{
GstElementClass parent_class;
};
GType gst_facedetect_get_type (void);
G_END_DECLS
#endif /* __GST_FACEDETECT_H__ */
diff --git a/src/pyramidsegment/gstpyramidsegment.h b/src/pyramidsegment/gstpyramidsegment.h
index 7ab1f22..d083a62 100644
--- a/src/pyramidsegment/gstpyramidsegment.h
+++ b/src/pyramidsegment/gstpyramidsegment.h
@@ -1,97 +1,97 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2008 Michael Sheldon <mike@mikeasoft.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#ifndef __GST_PYRAMIDSEGMENT_H__
#define __GST_PYRAMIDSEGMENT_H__
#include <gst/gst.h>
-#include <opencv/cv.h>
+#include <cv.h>
G_BEGIN_DECLS
/* #defines don't like whitespacey bits */
#define GST_TYPE_PYRAMIDSEGMENT \
(gst_pyramidsegment_get_type())
#define GST_PYRAMIDSEGMENT(obj) \
(G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_PYRAMIDSEGMENT,Gstpyramidsegment))
#define GST_PYRAMIDSEGMENT_CLASS(klass) \
(G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_PYRAMIDSEGMENT,GstpyramidsegmentClass))
#define GST_IS_PYRAMIDSEGMENT(obj) \
(G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_PYRAMIDSEGMENT))
#define GST_IS_PYRAMIDSEGMENT_CLASS(klass) \
(G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_PYRAMIDSEGMENT))
typedef struct _Gstpyramidsegment Gstpyramidsegment;
typedef struct _GstpyramidsegmentClass GstpyramidsegmentClass;
struct _Gstpyramidsegment
{
GstElement element;
GstPad *sinkpad, *srcpad;
gboolean silent;
IplImage *cvImage, *cvSegmentedImage;
CvMemStorage *storage;
CvSeq *comp;
double threshold1, threshold2;
int level;
};
struct _GstpyramidsegmentClass
{
GstElementClass parent_class;
};
GType gst_pyramidsegment_get_type (void);
G_END_DECLS
#endif /* __GST_PYRAMIDSEGMENT_H__ */
|
Elleo/gst-opencv
|
c01ab385196b7aaf0d2bb2f91f22ac106a7df5d8
|
Make face detect send a bus message when a face is detected Write a simple python example for face detection
|
diff --git a/examples/python/facedetect.py b/examples/python/facedetect.py
new file mode 100755
index 0000000..7ffc03a
--- /dev/null
+++ b/examples/python/facedetect.py
@@ -0,0 +1,26 @@
+#!/usr/bin/env python
+import pygst
+pygst.require("0.10")
+import gst
+import gtk
+
+class FaceDetect:
+
+ def __init__(self):
+ pipe = """filesrc location=mike-boat.jpg ! decodebin ! ffmpegcolorspace ! facedetect ! ffmpegcolorspace ! ximagesink"""
+ self.pipeline = gst.parse_launch(pipe)
+
+ self.bus = self.pipeline.get_bus()
+ self.bus.add_signal_watch()
+ self.bus.connect("message::element", self.bus_message)
+
+ self.pipeline.set_state(gst.STATE_PLAYING)
+
+ def bus_message(self, bus, message):
+ st = message.structure
+ if st.get_name() == "face":
+ print "Face found at %d,%d with dimensions %dx%d" % (st["x"], st["y"], st["width"], st["height"])
+
+if __name__ == "__main__":
+ f = FaceDetect()
+ gtk.main()
diff --git a/examples/python/mike-boat.jpg b/examples/python/mike-boat.jpg
new file mode 100644
index 0000000..1c9202b
Binary files /dev/null and b/examples/python/mike-boat.jpg differ
diff --git a/src/facedetect/gstfacedetect.c b/src/facedetect/gstfacedetect.c
index fd04442..0125c28 100644
--- a/src/facedetect/gstfacedetect.c
+++ b/src/facedetect/gstfacedetect.c
@@ -1,329 +1,338 @@
/*
* GStreamer
* Copyright (C) 2005 Thomas Vander Stichele <thomas@apestaart.org>
* Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Copyright (C) 2008 Michael Sheldon <mike@mikeasoft.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Alternatively, the contents of this file may be used under the
* GNU Lesser General Public License Version 2.1 (the "LGPL"), in
* which case the following provisions apply instead of the ones
* mentioned above:
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/**
* SECTION:element-facedetect
*
* FIXME:Describe facedetect here.
*
* <refsect2>
* <title>Example launch line</title>
* |[
* gst-launch-0.10 videotestsrc ! decodebin ! ffmpegcolorspace ! facedetect ! ffmpegcolorspace ! xvimagesink
* ]|
* </refsect2>
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <gst/gst.h>
#include "gstfacedetect.h"
GST_DEBUG_CATEGORY_STATIC (gst_facedetect_debug);
#define GST_CAT_DEFAULT gst_facedetect_debug
#define DEFAULT_PROFILE "/usr/share/opencv/haarcascades/haarcascade_frontalface_default.xml"
/* Filter signals and args */
enum
{
/* FILL ME */
LAST_SIGNAL
};
enum
{
PROP_0,
PROP_DISPLAY,
PROP_PROFILE
};
/* the capabilities of the inputs and outputs.
*/
static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
GST_PAD_SINK,
GST_PAD_ALWAYS,
GST_STATIC_CAPS (
"video/x-raw-rgb"
)
);
static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
GST_PAD_SRC,
GST_PAD_ALWAYS,
GST_STATIC_CAPS (
"video/x-raw-rgb"
)
);
GST_BOILERPLATE (Gstfacedetect, gst_facedetect, GstElement,
GST_TYPE_ELEMENT);
static void gst_facedetect_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec);
static void gst_facedetect_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec);
static gboolean gst_facedetect_set_caps (GstPad * pad, GstCaps * caps);
static GstFlowReturn gst_facedetect_chain (GstPad * pad, GstBuffer * buf);
static void gst_facedetect_load_profile (GObject * object);
/* GObject vmethod implementations */
static void
gst_facedetect_base_init (gpointer gclass)
{
GstElementClass *element_class = GST_ELEMENT_CLASS (gclass);
gst_element_class_set_details_simple(element_class,
"facedetect",
"Filter/Effect/Video",
"Performs face detection on videos and images, providing detected positions via bus messages",
"Michael Sheldon <mike@mikeasoft.com>");
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&src_factory));
gst_element_class_add_pad_template (element_class,
gst_static_pad_template_get (&sink_factory));
}
/* initialize the facedetect's class */
static void
gst_facedetect_class_init (GstfacedetectClass * klass)
{
GObjectClass *gobject_class;
GstElementClass *gstelement_class;
gobject_class = (GObjectClass *) klass;
gstelement_class = (GstElementClass *) klass;
gobject_class->set_property = gst_facedetect_set_property;
gobject_class->get_property = gst_facedetect_get_property;
g_object_class_install_property (gobject_class, PROP_DISPLAY,
g_param_spec_boolean ("display", "Display", "Sets whether the detected faces should be highlighted in the output",
TRUE, G_PARAM_READWRITE));
g_object_class_install_property (gobject_class, PROP_PROFILE,
g_param_spec_char ("profile", "Profile", "Location of Haar cascade file to use for face detection",
G_MININT8, G_MAXINT8, DEFAULT_PROFILE, G_PARAM_READWRITE));
}
/* initialize the new element
* instantiate pads and add them to element
* set pad calback functions
* initialize instance structure
*/
static void
gst_facedetect_init (Gstfacedetect * filter,
GstfacedetectClass * gclass)
{
filter->sinkpad = gst_pad_new_from_static_template (&sink_factory, "sink");
gst_pad_set_setcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR(gst_facedetect_set_caps));
gst_pad_set_getcaps_function (filter->sinkpad,
GST_DEBUG_FUNCPTR(gst_pad_proxy_getcaps));
gst_pad_set_chain_function (filter->sinkpad,
GST_DEBUG_FUNCPTR(gst_facedetect_chain));
filter->srcpad = gst_pad_new_from_static_template (&src_factory, "src");
gst_pad_set_getcaps_function (filter->srcpad,
GST_DEBUG_FUNCPTR(gst_pad_proxy_getcaps));
gst_element_add_pad (GST_ELEMENT (filter), filter->sinkpad);
gst_element_add_pad (GST_ELEMENT (filter), filter->srcpad);
filter->profile = DEFAULT_PROFILE;
filter->display = TRUE;
gst_facedetect_load_profile(filter);
}
static void
gst_facedetect_set_property (GObject * object, guint prop_id,
const GValue * value, GParamSpec * pspec)
{
Gstfacedetect *filter = GST_FACEDETECT (object);
switch (prop_id) {
case PROP_PROFILE:
filter->profile = g_value_get_char (value);
gst_facedetect_load_profile(filter);
break;
case PROP_DISPLAY:
filter->display = g_value_get_boolean (value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gst_facedetect_get_property (GObject * object, guint prop_id,
GValue * value, GParamSpec * pspec)
{
Gstfacedetect *filter = GST_FACEDETECT (object);
switch (prop_id) {
case PROP_PROFILE:
g_value_set_char (value, filter->profile);
break;
case PROP_DISPLAY:
g_value_set_boolean (value, filter->display);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
/* GstElement vmethod implementations */
/* this function handles the link with other elements */
static gboolean
gst_facedetect_set_caps (GstPad * pad, GstCaps * caps)
{
Gstfacedetect *filter;
GstPad *otherpad;
gint width, height;
GstStructure *structure;
filter = GST_FACEDETECT (gst_pad_get_parent (pad));
structure = gst_caps_get_structure (caps, 0);
gst_structure_get_int (structure, "width", &width);
gst_structure_get_int (structure, "height", &height);
filter->cvImage = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 3);
filter->cvGray = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 1);
filter->cvStorage = cvCreateMemStorage(0);
otherpad = (pad == filter->srcpad) ? filter->sinkpad : filter->srcpad;
gst_object_unref (filter);
return gst_pad_set_caps (otherpad, caps);
}
/* chain function
* this function does the actual processing
*/
static GstFlowReturn
gst_facedetect_chain (GstPad * pad, GstBuffer * buf)
{
Gstfacedetect *filter;
CvSeq *faces;
int i;
filter = GST_FACEDETECT (GST_OBJECT_PARENT (pad));
filter->cvImage->imageData = (char *) GST_BUFFER_DATA (buf);
cvCvtColor(filter->cvImage, filter->cvGray, CV_RGB2GRAY);
cvClearMemStorage(filter->cvStorage);
if (filter->cvCascade) {
faces = cvHaarDetectObjects(filter->cvGray, filter->cvCascade, filter->cvStorage, 1.1, 2, 0, cvSize(30, 30));
for (i = 0; i < (faces ? faces->total : 0); i++) {
CvRect* r = (CvRect *) cvGetSeqElem(faces, i);
-
+
+ GstStructure *s = gst_structure_new ("face",
+ "x", G_TYPE_UINT, r->x,
+ "y", G_TYPE_UINT, r->y,
+ "width", G_TYPE_UINT, r->width,
+ "height", G_TYPE_UINT, r->height, NULL);
+
+ GstMessage *m = gst_message_new_element (GST_OBJECT (filter), s);
+ gst_element_post_message (GST_ELEMENT (filter), m);
+
if (filter->display) {
CvPoint center;
int radius;
center.x = cvRound((r->x + r->width*0.5));
center.y = cvRound((r->y + r->height*0.5));
radius = cvRound((r->width + r->height)*0.25);
cvCircle(filter->cvImage, center, radius, CV_RGB(255, 32, 32), 3, 8, 0);
}
}
}
gst_buffer_set_data(buf, filter->cvImage->imageData, filter->cvImage->imageSize);
return gst_pad_push (filter->srcpad, buf);
}
static void gst_facedetect_load_profile(GObject * object) {
Gstfacedetect *filter = GST_FACEDETECT (object);
filter->cvCascade = (CvHaarClassifierCascade*)cvLoad(filter->profile, 0, 0, 0 );
if (!filter->cvCascade) {
GST_WARNING ("Couldn't load Haar classifier cascade: %s.", filter->profile);
}
}
/* entry point to initialize the plug-in
* initialize the plug-in itself
* register the element factories and other features
*/
static gboolean
facedetect_init (GstPlugin * facedetect)
{
/* debug category for fltering log messages */
GST_DEBUG_CATEGORY_INIT (gst_facedetect_debug, "facedetect",
0, "Performs face detection on videos and images, providing detected positions via bus messages");
return gst_element_register (facedetect, "facedetect", GST_RANK_NONE,
GST_TYPE_FACEDETECT);
}
/* gstreamer looks for this structure to register facedetect */
GST_PLUGIN_DEFINE (
GST_VERSION_MAJOR,
GST_VERSION_MINOR,
"facedetect",
"Performs face detection on videos and images, providing detected positions via bus messages",
facedetect_init,
VERSION,
"LGPL",
"GStreamer OpenCV Plugins",
"http://www.mikeasoft.com/"
)
|
Elleo/gst-opencv
|
3e645658929ea14c3d9a56dd3bb14c2c48c4d534
|
* Fix package name in autogen * Remove template README
|
diff --git a/README b/README
index 1905684..2d1d2e8 100644
--- a/README
+++ b/README
@@ -1,34 +1 @@
-WHAT IT IS
-----------
-
-gst-plugin is a template for writing your own GStreamer plug-in.
-
-The code is deliberately kept simple so that you quickly understand the basics
-of how to set up autotools and your source tree.
-
-This template demonstrates :
-- what to do in autogen.sh
-- how to setup configure.ac (your package name and version, GStreamer flags)
-- how to setup your source dir
-- what to put in Makefile.am
-
-More features and templates might get added later on.
-
-HOW TO USE IT
--------------
-
-To use it, either make a copy for yourself and rename the parts or use the
-make_element script in tools. To create sources for "myfilter" based on the
-"gsttransform" template run:
-
-cd src;
-../tools/make_element myfilter gsttransform
-
-This will create gstmyfilter.c and gstmyfilter.h. Open them in an editor and
-start editing. There are several occurances of the string "template", update
-those with real values. The plugin will be called 'myfilter' and it will have
-one element called 'myfilter' too. Also look for "FIXME:" markers that point you
-to places where you need to edit the code.
-
-You still need to adjust the Makefile.am.
-
+TODO: Write this
diff --git a/autogen.sh b/autogen.sh
index 9d84a03..bb7d7d3 100755
--- a/autogen.sh
+++ b/autogen.sh
@@ -1,91 +1,91 @@
#!/bin/sh
# you can either set the environment variables AUTOCONF and AUTOMAKE
# to the right versions, or leave them unset and get the RedHat 7.3 defaults
DIE=0
-package=gst-plugin
+package=gst-opencv
srcfile=src/main.c
# autogen.sh helper functions (copied from GStreamer's common/ CVS module)
if test ! -f ./gst-autogen.sh;
then
echo There is something wrong with your source tree.
echo You are either missing ./gst-autogen.sh or not
echo running autogen.sh from the top-level source
echo directory.
exit 1
fi
. ./gst-autogen.sh
CONFIGURE_DEF_OPT='--enable-maintainer-mode --enable-debug'
autogen_options $@
echo -n "+ check for build tools"
if test ! -z "$NOCHECK"; then echo " skipped"; else echo; fi
version_check "autoconf" "$AUTOCONF autoconf autoconf259 autoconf257 autoconf-2.54 autoconf-2.53 autoconf-2.52" \
"ftp://ftp.gnu.org/pub/gnu/autoconf/" 2 52 || DIE=1
version_check "automake" "$AUTOMAKE automake automake-1.9 automake19 automake-1.7 automake-1.6 automake-1.5" \
"ftp://ftp.gnu.org/pub/gnu/automake/" 1 7 || DIE=1
###version_check "autopoint" "autopoint" \
### "ftp://ftp.gnu.org/pub/gnu/gettext/" 0 11 5 || DIE=1
version_check "libtoolize" "$LIBTOOLIZE libtoolize glibtoolize" \
"ftp://ftp.gnu.org/pub/gnu/libtool/" 1 5 0 || DIE=1
version_check "pkg-config" "" \
"http://www.freedesktop.org/software/pkgconfig" 0 8 0 || DIE=1
die_check $DIE
autoconf_2_52d_check || DIE=1
aclocal_check || DIE=1
autoheader_check || DIE=1
die_check $DIE
# if no arguments specified then this will be printed
if test -z "$*"; then
echo "+ checking for autogen.sh options"
echo " This autogen script will automatically run ./configure as:"
echo " ./configure $CONFIGURE_DEF_OPT"
echo " To pass any additional options, please specify them on the $0"
echo " command line."
fi
tool_run "$aclocal" "-I m4/ $ACLOCAL_FLAGS"
tool_run "$libtoolize" "--copy --force"
tool_run "$autoheader"
tool_run "$autoconf"
tool_run "$automake" "-a -c"
# if enable exists, add an -enable option for each of the lines in that file
if test -f enable; then
for a in `cat enable`; do
CONFIGURE_FILE_OPT="--enable-$a"
done
fi
# if disable exists, add an -disable option for each of the lines in that file
if test -f disable; then
for a in `cat disable`; do
CONFIGURE_FILE_OPT="$CONFIGURE_FILE_OPT --disable-$a"
done
fi
test -n "$NOCONFIGURE" && {
echo "+ skipping configure stage for package $package, as requested."
echo "+ autogen.sh done."
exit 0
}
echo "+ running configure ... "
test ! -z "$CONFIGURE_DEF_OPT" && echo " ./configure default flags: $CONFIGURE_DEF_OPT"
test ! -z "$CONFIGURE_EXT_OPT" && echo " ./configure external flags: $CONFIGURE_EXT_OPT"
test ! -z "$CONFIGURE_FILE_OPT" && echo " ./configure enable/disable flags: $CONFIGURE_FILE_OPT"
echo
./configure $CONFIGURE_DEF_OPT $CONFIGURE_EXT_OPT $CONFIGURE_FILE_OPT || {
echo " configure failed"
exit 1
}
echo "Now type 'make' to compile $package."
|
parabuzzle/cistern
|
037189b88dc83a6f513b15c56f867c74b00010a0
|
Added ack codes to collector for verifing on the agent side
|
diff --git a/src/server/lib/modules/collection_server.rb b/src/server/lib/modules/collection_server.rb
index b5c610a..a2c105e 100644
--- a/src/server/lib/modules/collection_server.rb
+++ b/src/server/lib/modules/collection_server.rb
@@ -1,99 +1,104 @@
module CollectionServer
#TODO: Checksum check should be wrapped in to an exception and then and handled that way in receive_data
#Set buffer delimiters
@@break = '__1_BB'
@@value = '__1_VV'
@@finish = '__1_EE'
def check_key(agent, key)
if agent.authkey != key
return false
else
return true
end
end
#Write a log entry
def log_entry(line)
raw = line.split(@@break)
map = Hash.new
raw.each do |keys|
parts = keys.split(@@value)
map.store(parts[0],parts[1])
end
#unless USEMEMCACHE != true
# if Staticentry.get_cache(Digest::MD5.hexdigest(map['data'] + map['logtype_id'].to_s)).nil?
# static = Logtype.find(map['logtype_id']).staticentries.new
# static.data = map['data']
# static.save
# end
#else
static = Logtype.find(map['logtype_id']).staticentries.new
static.data = map['data']
static.save
#end
unless USEMEMCACHE != true
static = Staticentry.get_cache(Digest::MD5.hexdigest(map['data'] + map['logtype_id'].to_s))
else
static = Staticentry.find(Digest::MD5.hexdigest(map['data'] + map['logtype_id'].to_s))
end
event = static.events.new
event.etime = map['etime'].to_i
event.loglevel_id = map['loglevel_id'].to_i
event.payload = map['payload']
event.logtype_id = map['logtype_id'].to_i
event.agent_id = map['agent_id'].to_i
begin
a = Agent.find(map['agent_id'])
l = Logtype.find(map['logtype_id'])
if a.logtypes.member?(l)
if check_key(a, map['authkey'])
event.save
else
ActiveRecord::Base.logger.error "Event dropped -- invalid agent authkey sent for #{a.name}"
+ send_data "ackerr1"
end
else
ActiveRecord::Base.logger.error "Event dropped -- Agent #{a.name} is not a member of logtype #{l.name}"
+ send_data "ackerr2"
end
rescue ActiveRecord::RecordNotFound
ActiveRecord::Base.logger.error "Event dropped -- invalid agent_id or logtype_id specified"
+ send_data "ackerr3"
end
port, ip = Socket.unpack_sockaddr_in(get_peername)
host = Socket.getaddrinfo(ip, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME)[0][2]
ActiveRecord::Base.logger.debug "New event logged from #{host} \n -- Log data: #{line}"
end
#Do this when a connection is initialized
def post_init
port, ip = Socket.unpack_sockaddr_in(get_peername)
host = Socket.getaddrinfo(ip, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME)[0][2]
ActiveRecord::Base.logger.info "-- Collector connection established from #{host}"
end
#Do this when data is received
def receive_data(data)
(@buffer ||= BufferedTokenizer.new(delimiter = "__1_EE")).extract(data).each do |line|
#strip newline at beginning of line
if line.match(/^\W{1}./)
line = line[1..line.length-1]
end
if line.valid?
log_entry(line)
+ send_data "ackok"
else
port, ip = Socket.unpack_sockaddr_in(get_peername)
host = Socket.getaddrinfo(ip, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME)[0][2]
ActiveRecord::Base.logger.error "Dropped log entry from #{host} - checksum invalid"
+ send_data "ackerr0"
end
end
end
#Do this when a connection is closed by a peer
def unbind
ActiveRecord::Base.logger.info "-- Collector connection closed by a peer"
end
end
\ No newline at end of file
|
parabuzzle/cistern
|
906eb055dcd3d04320ec9fe00df1858e94bc1eb5
|
Added reconnect logic to agent code.
|
diff --git a/src/agent/agent.rb b/src/agent/agent.rb
index 6849603..17acf5d 100644
--- a/src/agent/agent.rb
+++ b/src/agent/agent.rb
@@ -1,55 +1,54 @@
require 'rubygems'
require 'eventmachine'
require 'lib/modules.rb'
require 'socket'
require 'file/tail'
require 'yaml'
require 'digest/md5'
require 'commands.rb'
require 'lib/sender_base.rb'
+require 'timeout'
include LogHelper
include AgentCommands
include File::Tail
include Socket::Constants
CONFIG = YAML::load(File.open("config.yml"))
port = CONFIG['agent']['listenport']
bindip = CONFIG['agent']['bindip']
authkey = CONFIG['agent']['key']
agent_id = CONFIG['agent']['agent_id']
-serverhost = CONFIG['server']['hostname']
-serverport = CONFIG['server']['port']
+@serverhost = CONFIG['server']['hostname']
+@serverport = CONFIG['server']['port']
-@socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
-sockaddr = Socket.pack_sockaddr_in( serverport, serverhost )
-@socket.connect( sockaddr )
+@socket = initialize_socket(@serverport, @serverhost)
CONFIG['logtypes'].each do |l,logtype|
x = Thread.new {
require 'logmodels/' + logtype['modelfile']
include eval(logtype['modelname'])
File.open(logtype['logfile']) do |log|
log.extend(File::Tail)
log.interval = 1
log.backward(0)
puts "tailing #{logtype['logfile']} with logmodel #{logtype['modelname']}"
log.tail { |line| send_event(line, @socket, authkey, logtype['logtype_id'], agent_id) }
end
}
end
Signal.trap("TERM") do
EventMachine::stop_event_loop
end
EventMachine::run {
EventMachine::start_server bindip, port, CommandServer
}
diff --git a/src/agent/lib/sender_base.rb b/src/agent/lib/sender_base.rb
index be6b535..066e302 100644
--- a/src/agent/lib/sender_base.rb
+++ b/src/agent/lib/sender_base.rb
@@ -1,20 +1,47 @@
module LogHelper
def send_event(entry, socket, authkey, logtype_id, agent_id)
event = Hash.new
e = String.new
entry = entry.chomp
puts entry
event.store("authkey", authkey)
event.store("logtype_id", logtype_id)
event.store("agent_id", agent_id)
event.store("loglevel_id", get_loglevel_id(entry))
event.store("etime", get_time(entry))
event.store("data", get_static(entry))
event.store("payload", get_payload(entry))
event.each do |key, val|
e = e + key.to_s + '__1_VV' + val.to_s + '__1_BB'
end
e = e + '__1_CC' + Digest::MD5.hexdigest(e) + '__1_EE'
- socket.write(e)
+ begin
+ if @socket == false
+ raise Errno::EPIPE
+ end
+ socket.write(e)
+ rescue Errno::EPIPE
+ puts "server is not responding, dropping event"
+ @socket = initialize_socket(@serverport, @serverhost)
+ end
+ end
+
+ def initialize_socket(port, host, timeout=1)
+ begin
+ Timeout::timeout(timeout) do
+ begin
+ socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
+ sockaddr = Socket.pack_sockaddr_in( port, host )
+ socket.connect( sockaddr )
+ return socket
+ rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH
+ puts "Server connection refused or unreachable"
+ return false
+ end
+ end
+ rescue Timeout::Error
+ puts "server connection timeout"
+ end
end
+
end
|
parabuzzle/cistern
|
f51b477af8b91bb06f539ecc670c4fc0734f16c6
|
Started hardening the agent code
|
diff --git a/src/agent/agent.rb b/src/agent/agent.rb
index 6849603..fbcf8ca 100644
--- a/src/agent/agent.rb
+++ b/src/agent/agent.rb
@@ -1,55 +1,69 @@
require 'rubygems'
require 'eventmachine'
require 'lib/modules.rb'
require 'socket'
require 'file/tail'
require 'yaml'
require 'digest/md5'
require 'commands.rb'
require 'lib/sender_base.rb'
include LogHelper
include AgentCommands
include File::Tail
include Socket::Constants
CONFIG = YAML::load(File.open("config.yml"))
port = CONFIG['agent']['listenport']
bindip = CONFIG['agent']['bindip']
authkey = CONFIG['agent']['key']
agent_id = CONFIG['agent']['agent_id']
+unless CONFIG['server']['retry'].nil?
+ retrytime = CONFIG['server']['retry']
+else
+ retrytime = 3
+end
+
+unless CONFIG['server']['timeout'].nil?
+ timeout = CONFIG['server']['timeout']
+else
+ timeout = 3
+end
+
serverhost = CONFIG['server']['hostname']
serverport = CONFIG['server']['port']
-@socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
-sockaddr = Socket.pack_sockaddr_in( serverport, serverhost )
-@socket.connect( sockaddr )
-
-
-
-CONFIG['logtypes'].each do |l,logtype|
- x = Thread.new {
- require 'logmodels/' + logtype['modelfile']
- include eval(logtype['modelname'])
-
- File.open(logtype['logfile']) do |log|
- log.extend(File::Tail)
- log.interval = 1
- log.backward(0)
- puts "tailing #{logtype['logfile']} with logmodel #{logtype['modelname']}"
- log.tail { |line| send_event(line, @socket, authkey, logtype['logtype_id'], agent_id) }
- end
- }
+unless CONFIG['logtypes'].nil?
+ @socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
+ sockaddr = Socket.pack_sockaddr_in( serverport, serverhost )
+ @socket.connect( sockaddr )
+
+ #TODO: Need to add a reconnect if the socket goes stale.
+
+ CONFIG['logtypes'].each do |l,logtype|
+ x = Thread.new {
+ require 'logmodels/' + logtype['modelfile']
+ include eval(logtype['modelname'])
+
+ File.open(logtype['logfile']) do |log|
+ log.extend(File::Tail)
+ log.interval = 1
+ log.backward(0)
+ puts "tailing #{logtype['logfile']} with logmodel #{logtype['modelname']}"
+ log.tail { |line| send_event(line, @socket, authkey, logtype['logtype_id'], agent_id) }
+ end
+ }
+ end
end
Signal.trap("TERM") do
EventMachine::stop_event_loop
end
EventMachine::run {
EventMachine::start_server bindip, port, CommandServer
}
diff --git a/src/agent/config.yml b/src/agent/config.yml
index bd821d6..3f6a666 100644
--- a/src/agent/config.yml
+++ b/src/agent/config.yml
@@ -1,22 +1,24 @@
server:
hostname: 127.0.0.1
connection: tcp
port: 9845
+ retry: 3
+ timeout: 3
agent:
listenport: 9846
bindip: 0.0.0.0
agent_id: 1
key: 7952d3072b86a949e45232fe42ad03bc
logtypes:
syslog:
modelfile: syslog.rb
modelname: SysLogModel
logtype_id: 1
logfile: /var/log/system.log
- authlog:
- modelfile: syslog.rb
- modelname: SysLogModel
- logtype_id: 2
- logfile: /var/log/secure.log
+# authlog:
+# modelfile: syslog.rb
+# modelname: SysLogModel
+# logtype_id: 2
+# logfile: /var/log/secure.log
diff --git a/src/agent/lib/sender_base.rb b/src/agent/lib/sender_base.rb
index be6b535..d1d44a4 100644
--- a/src/agent/lib/sender_base.rb
+++ b/src/agent/lib/sender_base.rb
@@ -1,20 +1,27 @@
module LogHelper
def send_event(entry, socket, authkey, logtype_id, agent_id)
event = Hash.new
e = String.new
entry = entry.chomp
puts entry
event.store("authkey", authkey)
event.store("logtype_id", logtype_id)
event.store("agent_id", agent_id)
event.store("loglevel_id", get_loglevel_id(entry))
event.store("etime", get_time(entry))
event.store("data", get_static(entry))
event.store("payload", get_payload(entry))
event.each do |key, val|
e = e + key.to_s + '__1_VV' + val.to_s + '__1_BB'
end
e = e + '__1_CC' + Digest::MD5.hexdigest(e) + '__1_EE'
socket.write(e)
end
+
+ def connect
+ @socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
+ sockaddr = Socket.pack_sockaddr_in( serverport, serverhost )
+ @socket.connect( sockaddr )
+ end
+
end
|
parabuzzle/cistern
|
d797d16a9850770bf77ccc70dbf85557ff6444ee
|
added stats pages
|
diff --git a/src/server/app/controllers/stats_controller.rb b/src/server/app/controllers/stats_controller.rb
new file mode 100644
index 0000000..827d5ad
--- /dev/null
+++ b/src/server/app/controllers/stats_controller.rb
@@ -0,0 +1,13 @@
+class StatsController < ApplicationController
+
+ def index
+ @title = "Statistics"
+ @agents = Agent.all
+ @logtypes = Logtype.all
+ @agentscount = Agent.count
+ @eventscount = Event.count
+ @logtypescount = Logtype.count
+ @staticscount = Staticentry.count
+ end
+
+end
diff --git a/src/server/app/helpers/stats_helper.rb b/src/server/app/helpers/stats_helper.rb
new file mode 100644
index 0000000..65e2f8b
--- /dev/null
+++ b/src/server/app/helpers/stats_helper.rb
@@ -0,0 +1,2 @@
+module StatsHelper
+end
diff --git a/src/server/app/views/layouts/application.rhtml b/src/server/app/views/layouts/application.rhtml
index 6708736..7c208b5 100644
--- a/src/server/app/views/layouts/application.rhtml
+++ b/src/server/app/views/layouts/application.rhtml
@@ -1,82 +1,82 @@
<%starttime = Time.now.to_f %>
<!DOCTYPE HTML PUBLIC "!//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Cistern :: <%= @title %></title>
<%= stylesheet_link_tag "main" %>
<%= javascript_include_tag "jquery.min"%>
<%= javascript_include_tag "application"%>
</head>
<body>
<div id="header">
<div id="logo">Cistern</div>
<div id="search">
Search all Events
<% form_for :search, :url => { :action => "index", :controller => "search" } do |form| %>
<div><%= form.text_field :data, :size => 20, :class => "searchbox", :value => params[:query] %></div>
<!--<div class="adendem">advanced</div> -->
<%end%>
</div>
</div> <!-- header -->
<div id="container">
<div id="topnav">
<%= link_to("Events", :controller => "events", :action => "index")%>
<%= link_to("Agents", :controller => "agents", :action => "index")%>
<%= link_to("Logtypes", :controller => "logtypes", :action => "index")%>
<%= link_to("Search", :controller => "search", :action => "index")%>
- <!-- <%= link_to("Stats", :controller => "stats", :action => "index")%> -->
+ <%= link_to("Stats", :controller => "stats", :action => "index")%>
</div>
<div id="main">
<% if flash[:notice]%>
<div id="notice"><%=h flash[:notice]%></div>
<%end%>
<%if flash[:error]%>
<div id="error"><%=h flash[:error]%></div>
<%end%>
<%= @content_for_layout %>
</div> <!-- main -->
<div id="footer">
Copyright © 2009 Mike Heijmans
<div class="adendum">powered by <a href="http://parabuzzle.github.com/cistern">Cistern</a></div>
</div> <!-- footer -->
<% if ENV["RAILS_ENV"] == "development" #call this block if in dev mode %>
<!-- Dev stuff -->
<div id="debug">
<a href='#' onclick="$('#params_debug_info').toggle();return false;">params</a> |
<a href='#' onclick="$('#session_debug_info').toggle();return false;">session</a> |
<a href='#' onclick="$('#env_debug_info').toggle();return false;">env</a> |
<a href='#' onclick="$('#request_debug_info').toggle();return false;">request</a>
<fieldset id="params_debug_info" class="debug_info" style="display:none">
<legend>params</legend>
<%= debug(params) %>
</fieldset>
<fieldset id="session_debug_info" class="debug_info" style="display:none">
<legend>session</legend>
<%= debug(session) %>
</fieldset>
<fieldset id="env_debug_info" class="debug_info" style="display:none">
<legend>env</legend>
<%= debug(request.env) %>
</fieldset>
<fieldset id="request_debug_info" class="debug_info" style="display:none">
<legend>request</legend>
<%= debug(request) %>
</fieldset>
</div>
<!-- end Dev mode only stuff -->
<% end %>
</div> <!-- container -->
</body>
</html>
<% rtime = Time.now.to_f - starttime%>
<% if ENV["RAILS_ENV"] == "development"%>
<%= [rtime*1000].to_s.to_i %> ms
<%else%>
<!-- <%= rtime*1000 %> -->
<%end%>
\ No newline at end of file
diff --git a/src/server/app/views/stats/index.rhtml b/src/server/app/views/stats/index.rhtml
new file mode 100644
index 0000000..b0843ad
--- /dev/null
+++ b/src/server/app/views/stats/index.rhtml
@@ -0,0 +1,30 @@
+<h1>Statistics</h1>
+<div class="loglevelstats">
+ <h2>Events by loglevel</h2>
+ <div class="info">FATAL: <%=Event.count(:conditions => "loglevel_id = 1")%></div>
+ <div class="info">ERROR: <%=Event.count(:conditions => "loglevel_id = 2")%></div>
+ <div class="info">WARN: <%=Event.count(:conditions => "loglevel_id = 3")%></div>
+ <div class="info">INFO: <%=Event.count(:conditions => "loglevel_id = 4")%></div>
+ <div class="info">DEBUG: <%=Event.count(:conditions => "loglevel_id = 5")%></div>
+ <div class="info">UNKNOWN: <%=Event.count(:conditions => "loglevel_id = 6")%></div>
+</div>
+
+<div id="events">
+ <div class="info">There are currently <%=@eventscount%> total events</div>
+ <div class="info">Spread across <%=@logtypescount%> logtype(s) and <%=@agentscount%> agent(s)</div>
+ <div class="info"><There are <%=@staticscount%> unique static entries</div>
+</div>
+<h2>Agent Breakdown</h2>
+<ul>
+<% for agent in @agents do %>
+ <li><%= agent.name%>: <%=agent.events.count%> total events</li>
+<%end%>
+</ul>
+<h2>Logtype Breakdown</h2>
+<ul>
+<% for type in @logtypes do %>
+ <li><%=type.name%>: <%=type.events.count%> total events</li>
+<%end%>
+</ul>
+
+<div class="clear"></div>
diff --git a/src/server/public/stylesheets/main.css b/src/server/public/stylesheets/main.css
index 89aa4ea..6aa20d2 100644
--- a/src/server/public/stylesheets/main.css
+++ b/src/server/public/stylesheets/main.css
@@ -1,246 +1,254 @@
body {
background: #fff;
color: #000;
margin: 0px;
padding: 0px;
color: #333;
font-weight:bold;
font-family: serif;
}
a {
text-decoration: none;
color: #660033;
}
a:hover {
background: #000033;
color: #fff;
padding: 2px;
}
#container {
padding: 0px;
margin: auto;
width: 90%;
}
#header {
width: 100%;
margin: 0px;
height: 95px;
background: #333;
border-bottom: solid 6px #000;
color:#fff;
}
#logo {
position: absolute;
padding-top: 20px;
padding-left: 45px;
font-weight:bold;
font-size: 55px;
color: #fff;
}
#search {
text-align: right;
padding-top: 20px;
padding-right: 50px;
}
.searchbox {
background: #663366;
border: 1px solid #000;
color: #fff;
font-size: 20px;
padding: 2px;
font-weight: none;
}
#eventlist {
min-height: 350px;
_height: 350px;
}
#topnav a {
background: #000;
padding: 4px;
padding-bottom: 4px;
padding-left: 6px;
padding-right: 6px;
color: #fff;
border-left: solid 2px #000033;
border-right: solid 2px #000033;
border-bottom: solid 2px #000033;
}
#topnav a:hover {
background: #666;
padding: 4px;
padding-bottom: 4px;
padding-left: 6px;
padding-right: 6px;
color: #fff;
border-left: solid 2px #000033;
border-right: solid 2px #000033;
border-bottom: solid 2px #000033;
}
.topnav {
background: #666;
padding: 2px;
padding-bottom: 4px;
padding-left: 6px;
padding-right: 6px;
color: #fff;
border-left: solid 2px #000033;
border-right: solid 2px #000033;
border-bottom: solid 2px #000033;
}
#topnav {
font-size: 20px;
padding: 2px;
padding-bottom: 4px;
padding-left: 6px;
padding-right: 6px;
color: #fff;
}
#main {
min-height: 400px;
_height: 400px; /* IE min-height hack */
}
#footer {
margin:auto;
text-align: center;
width: 100%;
border-top: 2px solid #000;
padding-top: 15px;
}
#notice {
margin-top: 10px;
width: 100%;
background: #09F;
color: #000;
padding: 10px;
border: 1px solid #333;
}
#error {
margin-top: 10px;
width: 100%;
background: #F00;
color: #000;
padding: 10px;
border: 1px solid #333;
}
#form {
width: 350px;
margin: auto;
}
.submitbutton {
background: #660033;
color: #fff;
border: 3px solid #000;
padding: 6px;
}
.fbox {
background: #ffff55;
border: 1px solid #333;
padding: 2px;
}
.clear {
clear:both;
}
.adendem {
font-size: 14px;
font-weight: normal;
}
.in20 {
padding-left: 20px;
padding-right: 20px;
}
.errorExplanation {
width: 800px;
margin: auto;
padding: 3px;
padding-left: 10px;
padding-right: 10px;
background: #ffff55;
border: 1px solid #333;
margin-bottom: 10px;
}
.subnav {
float:right;
}
.agent {
margin-top: 10px;
padding: 2px;
}
.result {
padding: 5px;
}
.advancedsearch {
display: none;
background:#FF9;
padding: 3px;
border: 1px solid #000
}
#events {
}
.event{
background: #fff;
margin-bottom: 10px;
}
.event a {
color:#333;
}
.event a:hover {
color:#333;
background: #aaa;
}
#commandout {
overflow: auto;
white-space: nowrap;
background: #eee;
padding: 4px;
border: 1px solid #AAA;
margin: 5px;
}
#totalhits {
margin-bottom: 10px;
font-size: 14px;
}
.mainsearchbox {
background: #FF9;
border: solid 1px #000;
font-size: 20px;
padding: 2px;
font-weight: none;
}
.searchsubmitbutton {
background: #660033;
color: #fff;
border: 1px solid #000;
padding: 6px;
height: 28px;
}
.rightsearch {
float:right;
text-align: right;
}
.minisearchbox {
background: #FF9;
border: 1px solid #000;
+}
+
+.loglevelstats {
+ float: right;
+ background: #CCC;
+ color: #333;
+ padding: 8px;
+ border: 1px solid #000;
}
\ No newline at end of file
diff --git a/src/server/test/functional/stats_controller_test.rb b/src/server/test/functional/stats_controller_test.rb
new file mode 100644
index 0000000..bce12eb
--- /dev/null
+++ b/src/server/test/functional/stats_controller_test.rb
@@ -0,0 +1,9 @@
+require 'test_helper'
+
+class StatsControllerTest < ActionController::TestCase
+ # Replace this with your real tests.
+ test "the truth" do
+ assert true
+ end
+
+end
diff --git a/src/server/test/unit/helpers/stats_helper_test.rb b/src/server/test/unit/helpers/stats_helper_test.rb
new file mode 100644
index 0000000..3f0b9aa
--- /dev/null
+++ b/src/server/test/unit/helpers/stats_helper_test.rb
@@ -0,0 +1,4 @@
+require 'test_helper'
+
+class StatsHelperTest < ActionView::TestCase
+end
|
parabuzzle/cistern
|
8523b8c85a1b048ddcaf9dd5802628f2e521dbd6
|
ignore tmp directory
|
diff --git a/.gitignore b/.gitignore
index c2238c9..bb72fb9 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,11 +1,12 @@
*.log
*.pid
*.sqlite3
src/server/config/database.yml
src/server/config/daemons.yml
src/server/config/collectors.yml
src/server/config/cistern.yml
src/server/config/memcached.yml
src/server/index
src/server/db/schema.rb
src/server/.idea
+src/server/tmp
|
parabuzzle/cistern
|
e41e3ae8c8487e3a04544ce231d0c526e8e8eba4
|
Added agent to logtype check for log collector and exception handling on invalid agent_id and/or logtype_id
|
diff --git a/src/server/lib/modules/collection_server.rb b/src/server/lib/modules/collection_server.rb
index 7dfbdc1..b5c610a 100644
--- a/src/server/lib/modules/collection_server.rb
+++ b/src/server/lib/modules/collection_server.rb
@@ -1,89 +1,99 @@
module CollectionServer
#TODO: Checksum check should be wrapped in to an exception and then and handled that way in receive_data
#Set buffer delimiters
@@break = '__1_BB'
@@value = '__1_VV'
@@finish = '__1_EE'
def check_key(agent, key)
if agent.authkey != key
return false
else
return true
end
end
#Write a log entry
def log_entry(line)
raw = line.split(@@break)
map = Hash.new
raw.each do |keys|
parts = keys.split(@@value)
map.store(parts[0],parts[1])
end
#unless USEMEMCACHE != true
# if Staticentry.get_cache(Digest::MD5.hexdigest(map['data'] + map['logtype_id'].to_s)).nil?
# static = Logtype.find(map['logtype_id']).staticentries.new
# static.data = map['data']
# static.save
# end
#else
static = Logtype.find(map['logtype_id']).staticentries.new
static.data = map['data']
static.save
#end
unless USEMEMCACHE != true
static = Staticentry.get_cache(Digest::MD5.hexdigest(map['data'] + map['logtype_id'].to_s))
else
static = Staticentry.find(Digest::MD5.hexdigest(map['data'] + map['logtype_id'].to_s))
end
event = static.events.new
event.etime = map['etime'].to_i
event.loglevel_id = map['loglevel_id'].to_i
event.payload = map['payload']
event.logtype_id = map['logtype_id'].to_i
event.agent_id = map['agent_id'].to_i
- if check_key(Agent.find(map['agent_id']), map['authkey'])
- event.save
- else
- ActiveRecord::Base.logger.debug "Event dropped -- invalid agent authkey sent"
+ begin
+ a = Agent.find(map['agent_id'])
+ l = Logtype.find(map['logtype_id'])
+ if a.logtypes.member?(l)
+ if check_key(a, map['authkey'])
+ event.save
+ else
+ ActiveRecord::Base.logger.error "Event dropped -- invalid agent authkey sent for #{a.name}"
+ end
+ else
+ ActiveRecord::Base.logger.error "Event dropped -- Agent #{a.name} is not a member of logtype #{l.name}"
+ end
+ rescue ActiveRecord::RecordNotFound
+ ActiveRecord::Base.logger.error "Event dropped -- invalid agent_id or logtype_id specified"
end
port, ip = Socket.unpack_sockaddr_in(get_peername)
host = Socket.getaddrinfo(ip, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME)[0][2]
ActiveRecord::Base.logger.debug "New event logged from #{host} \n -- Log data: #{line}"
end
#Do this when a connection is initialized
def post_init
port, ip = Socket.unpack_sockaddr_in(get_peername)
host = Socket.getaddrinfo(ip, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME)[0][2]
ActiveRecord::Base.logger.info "-- Collector connection established from #{host}"
end
#Do this when data is received
def receive_data(data)
(@buffer ||= BufferedTokenizer.new(delimiter = "__1_EE")).extract(data).each do |line|
#strip newline at beginning of line
if line.match(/^\W{1}./)
line = line[1..line.length-1]
end
if line.valid?
log_entry(line)
else
port, ip = Socket.unpack_sockaddr_in(get_peername)
host = Socket.getaddrinfo(ip, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME)[0][2]
ActiveRecord::Base.logger.error "Dropped log entry from #{host} - checksum invalid"
end
end
end
#Do this when a connection is closed by a peer
def unbind
ActiveRecord::Base.logger.info "-- Collector connection closed by a peer"
end
end
\ No newline at end of file
|
parabuzzle/cistern
|
43d15cc086503ccb62ec366a3338ae05dc94e645
|
added cascading del methods to the models... may not need them
|
diff --git a/src/server/app/models/agent.rb b/src/server/app/models/agent.rb
index 8c08f7d..691608d 100644
--- a/src/server/app/models/agent.rb
+++ b/src/server/app/models/agent.rb
@@ -1,37 +1,45 @@
class Agent < ActiveRecord::Base
acts_as_ferret :fields => [:hostname, :name, :port]
has_and_belongs_to_many :logtypes, :join_table => :agents_logtypes
has_many :events
#Validations
validates_presence_of :hostname, :port, :name
#validates_format_of :hostname, :with => /([A-Z0-9-]+\.)+[A-Z]{2,4}$/i
validates_uniqueness_of :name
def add_logtype(logtype)
if self.logtypes.find_by_logtype_id('logtype.id') == nil
ActiveRecord::Base.connection.execute("insert into agents_logtypes (logtype_id,agent_id)values('#{logtype.id}','#{self.id}')")
end
return logtype
end
def remove_logtype(logtype)
if self.logtypes.find_by_logtype_id('logtype.id') != nil
ActiveRecord::Base.connection.execute("delete from agents_logtypes where logtype_id = '#{logtype.id}' and agent_id = '#{self.id}'")
end
return logtype
end
def logtype_member?(logtype)
flag = 0
self.logtypes.each do |log|
if log.id == logtype.id
flag = 1
end
end
return flag
end
+
+ def del
+ events = self.events
+ events.each do |e|
+ e.destroy
+ end
+ self.destory
+ end
end
diff --git a/src/server/app/models/logtype.rb b/src/server/app/models/logtype.rb
index 4ae4493..11c628d 100644
--- a/src/server/app/models/logtype.rb
+++ b/src/server/app/models/logtype.rb
@@ -1,14 +1,23 @@
class Logtype < ActiveRecord::Base
has_and_belongs_to_many :agents
has_many :staticentries
has_many :events, :through => :staticentries
#Validations
validates_presence_of :name
def add(agent)
ActiveRecord::Base.connection.execute("insert into agents_logtypes (logtype_id,agent_id)values('#{self.id}','#{agent.id}')")
return agent
end
+
+ def del
+ static = self.staticentries
+ static.each do |s|
+ s.del
+ end
+ self.destory
+ end
+
end
diff --git a/src/server/app/models/staticentry.rb b/src/server/app/models/staticentry.rb
index da80d07..927552f 100644
--- a/src/server/app/models/staticentry.rb
+++ b/src/server/app/models/staticentry.rb
@@ -1,15 +1,23 @@
class Staticentry < ActiveRecord::Base
acts_as_ferret
acts_as_cached :ttl => 4.hours
has_many :events
belongs_to :logtype
has_many :loglevels, :through => :entries
def before_create
if Staticentry.find_by_id(Digest::MD5.hexdigest(self.data + self.logtype_id.to_s)) != nil
return false
end
self.id = Digest::MD5.hexdigest(self.data + self.logtype_id.to_s)
end
+ def del
+ events = self.events
+ event.each do |e|
+ e.destory
+ end
+ self.destroy
+ end
+
end
|
parabuzzle/cistern
|
5572853e6a91c4ff1ac63cbf5390b3eb425749c8
|
Fixed line breaks in search results and made the onclick javascript more standards compliant
|
diff --git a/src/server/app/views/agents/index.rhtml b/src/server/app/views/agents/index.rhtml
index d0763b0..20b5088 100644
--- a/src/server/app/views/agents/index.rhtml
+++ b/src/server/app/views/agents/index.rhtml
@@ -1,33 +1,33 @@
<h1>Agents</h1>
<div class="subnav"><%=link_to("Create new Agent #{image_tag("addserver.png", :alt => "add server", :border => "0px")}", :action => "new")%></div>
<div class="clear"></div>
<% for agent in @agents do%>
<%online = is_agent_online?(agent.hostname, agent.port)%>
<div class="agent">
- <%=if online then image_tag("serverup.png", :alt => "agent is up") else image_tag("serverdown.png", :alt => "agent listener down")end%><a href='#' onclick="$('.agentinfo<%=agent.id%>').toggle();return false"><%= h agent.name%></a> : <%=link_to("View Events", :action=>"show", :id=>agent.id)%>
+ <%=if online then image_tag("serverup.png", :alt => "agent is up") else image_tag("serverdown.png", :alt => "agent listener down")end%><a href='#' onclick="$('.agentinfo<%=agent.id%>').toggle();return false;"><%= h agent.name%></a> : <%=link_to("View Events", :action=>"show", :id=>agent.id)%>
<%= if !online then "(agent listener is offline)" end%>
<div class="agentinfo<%=agent.id%>" style="display:none; margin-left:30px; background:#FF9; padding: 3px; border: 1px solid #000">
<div class="subnav" style="width:200px;">
Logtypes
<% for logtype in agent.logtypes do%>
<div class="adendem"><%=h logtype.name%></div>
<%end%>
</div>
<div clear></div>
<div class="info">Total Events: <%= agent.events.count %></div>
<div class="info">Hostname: <%=h agent.hostname%></div>
<div class="info">Listenport: <%=h agent.port%></div>
<div class="info">Key: <%=h agent.authkey%></div>
<div class="info">Agent_id: <%=agent.id%></div>
<div class="info"><%=if online then link_to("View Commands for Host", :action => "commands", :id => agent.id) else "Agent listener is offline" end%></div>
<div class="info"><%=link_to("edit", :action => "edit", :id => agent.id)%></div>
</div>
</div>
<%end%>
<div class="pagination">
<%= will_paginate @event %>
</div>
\ No newline at end of file
diff --git a/src/server/app/views/agents/search.rhtml b/src/server/app/views/agents/search.rhtml
index 867e364..7be57c9 100644
--- a/src/server/app/views/agents/search.rhtml
+++ b/src/server/app/views/agents/search.rhtml
@@ -1,25 +1,25 @@
<div class="rightsearch">
<div>
<% form_for :search, :url => { :id => params[:id]} do |form| %>
<div>Search within Agent</div>
<div><%= form.text_field :data, :size => 20, :class => "minisearchbox",:value => params[:aquery] %> </div>
<%end%>
</div>
</div>
<div class="clear"></div>
<h1>Search Results</h1>
<div id="totalhits">Found <%=@total%> matching results</div>
<div id="events">
<% for event in @results do %>
<div class="event">
- <a href="#" onclick="$('.eventinfo<%=event.id%>').toggle();return false"><%= if params[:withepoch] then event.etime else Time.at(event.etime.to_f) end %></a> : <%= h event.loglevel.name %> ::
- <%=h event.full_event%>
+ <a href="#" onclick="$('.eventinfo<%=event.id%>').toggle();return false;"><%= if params[:withepoch] then event.etime else Time.at(event.etime.to_f) end %></a> : <%= h event.loglevel.name %> ::
+ <%=sanitize event.full_event, :tags => %w(br)%>
<div class="eventinfo<%=event.id%>" style="display:none; background:#FF9; border:1px solid #000; padding:5px; width:50%">
<div class="info">Agent: <%=link_to(h(event.agent.name), :controller => "agents", :action => "show", :id => event.agent.id)%></div>
<div class="info">Logtype: <%=link_to(h(event.staticentry.logtype.name), :controller => "logtypes", :action => "show", :id => event.staticentry.logtype.id)%></div>
<div class="info">Static Entry Id: <%= h event.staticentry_id%></div>
</div>
</div>
<%end%>
</div>
<%=will_paginate @results%>
\ No newline at end of file
diff --git a/src/server/app/views/agents/show.rhtml b/src/server/app/views/agents/show.rhtml
index 55a3ca8..984b9c5 100644
--- a/src/server/app/views/agents/show.rhtml
+++ b/src/server/app/views/agents/show.rhtml
@@ -1,52 +1,52 @@
<div class="rightsearch">
<div>
<% form_for :search, :url => { :id => params[:id]} do |form| %>
<div>Search within Agent</div>
<div><%= form.text_field :data, :size => 20, :class => "minisearchbox" %> </div>
<%end%>
</div>
</div>
<div class="clear"></div>
<h1>All Events for <%=h @agent.name%></h1>
<div id="filter">
<% if params[:logtype]%>
Current filter: <%= h Logtype.find(params[:logtype]).name%>
<%else%>
Filter by logtype:
<% for type in @agent.logtypes.all do %>
<%= link_to( h(type.name), :logtype => type.id, :withepoch => params[:withepoch] )%>
<%end%>
<%end%>
<div class="adendem">
<%= link_to("Clear filter", :logtype => nil, :withepoch => params[:withepoch])%>
</div>
</div>
<div id="events">
<% for event in @events do %>
<div class="event">
- <a href="#" onclick="$('.eventinfo<%=event.id%>').toggle();return false"><%= if params[:withepoch] then event.etime else Time.at(event.etime.to_f) end %></a> : <%= link_to(h(event.loglevel.name), :action => "show", :loglevel => event.loglevel.id, :withepoch => params[:withepoch])%> ::
+ <a href="#" onclick="$('.eventinfo<%=event.id%>').toggle();return false;"><%= if params[:withepoch] then event.etime else Time.at(event.etime.to_f) end %></a> : <%= link_to(h(event.loglevel.name), :action => "show", :loglevel => event.loglevel.id, :withepoch => params[:withepoch])%> ::
<%=sanitize event.payload, :tags => %w(br)%>
<div class="eventinfo<%=event.id%>" style="display:none; background:#FF9; border:1px solid #000; padding:5px;">
<div class="info">Logtype: <%=link_to(h(event.staticentry.logtype.name), :controller => "logtypes", :action => "show", :id => event.staticentry.logtype.id)%></div>
<div class="info">Static Entry Id: <%=h event.staticentry_id%></div>
</div>
</div>
<%end%>
</div>
<div class="pagination">
<%= will_paginate @event %>
</div>
<div class="adendem">
Records per page:
<%=link_to "20", :withepoch => params[:withepoch], :page => 1, :perpage => "20" %> |
<%=link_to "50", :withepoch => params[:withepoch], :page => 1, :perpage => "50" %> |
<%=link_to "100", :withepoch => params[:withepoch], :page => 1, :perpage => "100" %> |
<%=link_to "200", :withepoch => params[:withepoch], :page => 1, :perpage => "200" %>
</div>
<%if params[:withepoch]%>
<div class="adendem"><%=link_to "show regular time", :withepoch => nil, :page => params[:page], :perpage => params[:perpage], :logtype => params[:logtype] %></div>
<%else%>
<div class="adendem"><%=link_to "show epoch time", :withepoch => 1, :page => params[:page], :perpage => params[:perpage], :logtype => params[:logtype] %></div>
<%end%>
\ No newline at end of file
diff --git a/src/server/app/views/events/show.rhtml b/src/server/app/views/events/show.rhtml
index 4aff993..dc2f716 100644
--- a/src/server/app/views/events/show.rhtml
+++ b/src/server/app/views/events/show.rhtml
@@ -1,38 +1,38 @@
<h1>All Events</h1>
<%unless params[:loglevel].nil?%>
<div class="adendem"><%=link_to("clear filters", :action => "show", :loglevel => nil)%></div>
<%end%>
<div id="events">
<% for event in @events do %>
<div class="event">
- <a href="#" onclick="$('.eventinfo<%=event.id%>').toggle();return false"><%= if params[:withepoch] then event.etime else Time.at(event.etime.to_f) end %></a> : <%= link_to(h(event.loglevel.name), :action => "show", :loglevel => event.loglevel.id, :withepoch => params[:withepoch])%> ::
+ <a href="#" onclick="$('.eventinfo<%=event.id%>').toggle();return false;"><%= if params[:withepoch] then event.etime else Time.at(event.etime.to_f) end %></a> : <%= link_to(h(event.loglevel.name), :action => "show", :loglevel => event.loglevel.id, :withepoch => params[:withepoch])%> ::
<%= sanitize event.payload, :tags => %w(br) %>
<div class="eventinfo<%=event.id%>" style="display:none; background:#FF9; border:1px solid #000; padding:5px;">
<div class="info">Agent: <%=link_to(h(event.agent.name), :controller => "agents", :action => "show", :id => event.agent.id)%></div>
<div class="info">Logtype: <%=link_to(h(event.staticentry.logtype.name), :controller => "logtypes", :action => "show", :id => event.staticentry.logtype.id)%></div>
<div class="info">Static Entry Id: <%=h event.staticentry_id%></div>
</div>
</div>
<%end%>
</div>
<div class="pagination">
<%= will_paginate @event %>
</div>
<div class="adendem">
Records per page:
<%=link_to "20", :loglevel => params[:loglevel], :withepoch => params[:withepoch], :page => 1, :perpage => "20" %> |
<%=link_to "50", :loglevel => params[:loglevel], :withepoch => params[:withepoch], :page => 1, :perpage => "50" %> |
<%=link_to "100", :loglevel => params[:loglevel], :withepoch => params[:withepoch], :page => 1, :perpage => "100" %> |
<%=link_to "200", :loglevel => params[:loglevel], :withepoch => params[:withepoch], :page => 1, :perpage => "200" %>
</div>
<%if params[:withepoch]%>
<div class="adendem"><%=link_to "show regular time", :withepoch => nil, :loglevel => params[:loglevel], :page => params[:page], :perpage => params[:perpage] %></div>
<%else%>
<div class="adendem"><%=link_to "show epoch time", :withepoch => 1, :loglevel => params[:loglevel], :page => params[:page], :perpage => params[:perpage] %></div>
<%end%>
<div class="adendem"><%=link_to "view by agent", :controller => 'agents', :action => "index" %> | <%=link_to "view by logtype", :controller => 'logtypes', :action => 'index' %></div>
diff --git a/src/server/app/views/layouts/application.rhtml b/src/server/app/views/layouts/application.rhtml
index 5b77add..6708736 100644
--- a/src/server/app/views/layouts/application.rhtml
+++ b/src/server/app/views/layouts/application.rhtml
@@ -1,82 +1,82 @@
<%starttime = Time.now.to_f %>
<!DOCTYPE HTML PUBLIC "!//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Cistern :: <%= @title %></title>
<%= stylesheet_link_tag "main" %>
<%= javascript_include_tag "jquery.min"%>
<%= javascript_include_tag "application"%>
</head>
<body>
<div id="header">
<div id="logo">Cistern</div>
<div id="search">
Search all Events
<% form_for :search, :url => { :action => "index", :controller => "search" } do |form| %>
<div><%= form.text_field :data, :size => 20, :class => "searchbox", :value => params[:query] %></div>
<!--<div class="adendem">advanced</div> -->
<%end%>
</div>
</div> <!-- header -->
<div id="container">
<div id="topnav">
<%= link_to("Events", :controller => "events", :action => "index")%>
<%= link_to("Agents", :controller => "agents", :action => "index")%>
<%= link_to("Logtypes", :controller => "logtypes", :action => "index")%>
<%= link_to("Search", :controller => "search", :action => "index")%>
<!-- <%= link_to("Stats", :controller => "stats", :action => "index")%> -->
</div>
<div id="main">
<% if flash[:notice]%>
<div id="notice"><%=h flash[:notice]%></div>
<%end%>
<%if flash[:error]%>
<div id="error"><%=h flash[:error]%></div>
<%end%>
<%= @content_for_layout %>
</div> <!-- main -->
<div id="footer">
Copyright © 2009 Mike Heijmans
<div class="adendum">powered by <a href="http://parabuzzle.github.com/cistern">Cistern</a></div>
</div> <!-- footer -->
<% if ENV["RAILS_ENV"] == "development" #call this block if in dev mode %>
<!-- Dev stuff -->
<div id="debug">
- <a href='#' onclick="$('#params_debug_info').toggle();return false">params</a> |
- <a href='#' onclick="$('#session_debug_info').toggle();return false">session</a> |
- <a href='#' onclick="$('#env_debug_info').toggle();return false">env</a> |
- <a href='#' onclick="$('#request_debug_info').toggle();return false">request</a>
+ <a href='#' onclick="$('#params_debug_info').toggle();return false;">params</a> |
+ <a href='#' onclick="$('#session_debug_info').toggle();return false;">session</a> |
+ <a href='#' onclick="$('#env_debug_info').toggle();return false;">env</a> |
+ <a href='#' onclick="$('#request_debug_info').toggle();return false;">request</a>
<fieldset id="params_debug_info" class="debug_info" style="display:none">
<legend>params</legend>
<%= debug(params) %>
</fieldset>
<fieldset id="session_debug_info" class="debug_info" style="display:none">
<legend>session</legend>
<%= debug(session) %>
</fieldset>
<fieldset id="env_debug_info" class="debug_info" style="display:none">
<legend>env</legend>
<%= debug(request.env) %>
</fieldset>
<fieldset id="request_debug_info" class="debug_info" style="display:none">
<legend>request</legend>
<%= debug(request) %>
</fieldset>
</div>
<!-- end Dev mode only stuff -->
<% end %>
</div> <!-- container -->
</body>
</html>
<% rtime = Time.now.to_f - starttime%>
<% if ENV["RAILS_ENV"] == "development"%>
<%= [rtime*1000].to_s.to_i %> ms
<%else%>
<!-- <%= rtime*1000 %> -->
<%end%>
\ No newline at end of file
diff --git a/src/server/app/views/logtypes/index.rhtml b/src/server/app/views/logtypes/index.rhtml
index c723306..8d7dcd2 100644
--- a/src/server/app/views/logtypes/index.rhtml
+++ b/src/server/app/views/logtypes/index.rhtml
@@ -1,22 +1,22 @@
<h1>Logtypes</h1>
<div class="subnav"><%=link_to("Create new Logtype", :action => "new")%></div>
<div class="clear"></div>
<% for type in @logtypes do%>
<div class="agent">
- <a href='#' onclick="$('.typeinfo<%=type.id%>').toggle();return false"><%=h type.name%></a> : <%=link_to("View Events", :action=>"show", :id=>type.id)%>
+ <a href='#' onclick="$('.typeinfo<%=type.id%>').toggle();return false;"><%=h type.name%></a> : <%=link_to("View Events", :action=>"show", :id=>type.id)%>
<div class="typeinfo<%=type.id%>" style="display:none; background:#FF9; padding: 3px; border: 1px solid #000">
<div class="info">Description: <%=h type.description%></div>
<div class="info">Total Events: <%= type.events.count %></div>
<div class="info">Total Agents: <%=type.agents.count%></div>
<div class="info">Logtype_id: <%=type.id%></div>
<div class="info"><%=link_to("edit", :action => "edit", :id => type.id)%></div>
</div>
</div>
<%end%>
<div class="pagination">
<%= will_paginate @logtypes %>
</div>
diff --git a/src/server/app/views/logtypes/search.rhtml b/src/server/app/views/logtypes/search.rhtml
index ed9db0f..63645e6 100644
--- a/src/server/app/views/logtypes/search.rhtml
+++ b/src/server/app/views/logtypes/search.rhtml
@@ -1,24 +1,24 @@
<div class="rightsearch">
<div>
<% form_for :search, :url => { :id => params[:id]} do |form| %>
<div>Search within Logtype</div>
<div><%= form.text_field :data, :size => 20, :class => "minisearchbox", :value => params[:aquery] %> </div>
<%end%>
</div>
</div>
<h1>Search Results</h1>
<div id="totalhits">Found <%=@total%> matching results</div>
<div id="events">
<% for event in @results do %>
<div class="event">
<a href="#" onclick="$('.eventinfo<%=event.id%>').toggle();return false;"><%= if params[:withepoch] then event.etime else Time.at(event.etime.to_f) end %></a> : <%= h event.loglevel.name %> ::
- <%=h event.full_event%>
+ <%=sanitize event.full_event, :tags => %w(br)%>
<div class="eventinfo<%=event.id%>" style="display:none; background:#FF9; border:1px solid #000; padding:5px; width:50%">
<div class="info">Agent: <%=link_to(h(event.agent.name), :controller => "agents", :action => "show", :id => event.agent.id)%></div>
<div class="info">Logtype: <%=link_to(h(event.staticentry.logtype.name), :controller => "logtypes", :action => "show", :id => event.staticentry.logtype.id)%></div>
<div class="info">Static Entry Id: <%=h event.staticentry_id%></div>
</div>
</div>
<%end%>
</div>
<%=will_paginate @results%>
\ No newline at end of file
diff --git a/src/server/app/views/search/index.rhtml b/src/server/app/views/search/index.rhtml
index 2b06606..3286e3b 100644
--- a/src/server/app/views/search/index.rhtml
+++ b/src/server/app/views/search/index.rhtml
@@ -1,31 +1,31 @@
<h1>Search for Events</h1>
<div>
<% form_for :search do |form| %>
<div><%= form.text_field :data, :size => 20, :class => "mainsearchbox" %> <%= submit_tag "Findit!", :class => "searchsubmitbutton", :action => 'show' %></div>
- <!--<div class="adendem"><a href='#' onclick="$('.advancedsearch').toggle();return false">advanced</a></div>
+ <!--<div class="adendem"><a href='#' onclick="$('.advancedsearch').toggle();return false;">advanced</a></div>
<div class="advancedsearch">
<div class="agent">Search within Logtype</div>
<div>
<%for log in Logtype.all do%>
<%= radio_button_tag "logtype_ids", log.id %> <%= log.name %>
<%end%>
<%= radio_button_tag "logtype_ids", "off"%> all
</div>
<div class="agent">Search within Agent</div>
<div>
<%for agent in Agent.all do%>
<%= radio_button_tag "agent_ids", agent.id %> <%= agent.name %>
<%end%>
<%= radio_button_tag "agent_ids", "off"%> all
</div>
<div class="agent">Show only loglevel (Will show all levels at or above your choice)</div>
<div>
<%for level in Loglevel.all do%>
<%= radio_button_tag "loglevel_ids", level.id %> <%= level.name %>
<%end%>
<%= radio_button_tag "loglevel_ids", "off"%> all
</div>
</div>-->
<%end%>
</div>
\ No newline at end of file
diff --git a/src/server/app/views/search/show.rhtml b/src/server/app/views/search/show.rhtml
index 85fd806..cb1436e 100644
--- a/src/server/app/views/search/show.rhtml
+++ b/src/server/app/views/search/show.rhtml
@@ -1,16 +1,16 @@
<h1>Search Results</h1>
<div id="totalhits">Found <%=@total%> matching results</div>
<div id="events">
<% for event in @results do %>
<div class="event">
- <a href="#" onclick="$('.eventinfo<%=event.id%>').toggle();return false"><%= if params[:withepoch] then event.etime else Time.at(event.etime.to_f) end %></a> : <%= h event.loglevel.name %> ::
+ <a href="#" onclick="$('.eventinfo<%=event.id%>').toggle();return false;"><%= if params[:withepoch] then event.etime else Time.at(event.etime.to_f) end %></a> : <%= h event.loglevel.name %> ::
<%=sanitize event.full_event, :tags => %w(br)%>
<div class="eventinfo<%=event.id%>" style="display:none; background:#FF9; border:1px solid #000; padding:5px;">
<div class="info">Agent: <%=link_to(h(event.agent.name), :controller => "agents", :action => "show", :id => event.agent.id)%></div>
<div class="info">Logtype: <%=link_to(h(event.staticentry.logtype.name), :controller => "logtypes", :action => "show", :id => event.staticentry.logtype.id)%></div>
<div class="info">Static Entry Id: <%=h event.staticentry_id%></div>
</div>
</div>
<%end%>
</div>
<%=will_paginate @results%>
\ No newline at end of file
|
parabuzzle/cistern
|
8969d52b1fa2665ff3557a09c097ae4d2b9fbe3e
|
Changed layout to wide for easier log reading
|
diff --git a/src/server/public/stylesheets/main.css b/src/server/public/stylesheets/main.css
index 02ca319..89aa4ea 100644
--- a/src/server/public/stylesheets/main.css
+++ b/src/server/public/stylesheets/main.css
@@ -1,245 +1,246 @@
body {
background: #fff;
color: #000;
margin: 0px;
padding: 0px;
color: #333;
font-weight:bold;
font-family: serif;
}
a {
text-decoration: none;
color: #660033;
}
a:hover {
background: #000033;
color: #fff;
padding: 2px;
}
#container {
padding: 0px;
margin: auto;
- width: 900px;
+ width: 90%;
}
#header {
width: 100%;
margin: 0px;
height: 95px;
background: #333;
border-bottom: solid 6px #000;
color:#fff;
}
#logo {
position: absolute;
padding-top: 20px;
padding-left: 45px;
font-weight:bold;
font-size: 55px;
color: #fff;
}
#search {
text-align: right;
padding-top: 20px;
padding-right: 50px;
}
.searchbox {
background: #663366;
border: 1px solid #000;
color: #fff;
font-size: 20px;
padding: 2px;
font-weight: none;
}
#eventlist {
min-height: 350px;
_height: 350px;
}
#topnav a {
background: #000;
padding: 4px;
padding-bottom: 4px;
padding-left: 6px;
padding-right: 6px;
color: #fff;
border-left: solid 2px #000033;
border-right: solid 2px #000033;
border-bottom: solid 2px #000033;
}
#topnav a:hover {
background: #666;
padding: 4px;
padding-bottom: 4px;
padding-left: 6px;
padding-right: 6px;
color: #fff;
border-left: solid 2px #000033;
border-right: solid 2px #000033;
border-bottom: solid 2px #000033;
}
.topnav {
background: #666;
padding: 2px;
padding-bottom: 4px;
padding-left: 6px;
padding-right: 6px;
color: #fff;
border-left: solid 2px #000033;
border-right: solid 2px #000033;
border-bottom: solid 2px #000033;
}
#topnav {
font-size: 20px;
padding: 2px;
padding-bottom: 4px;
padding-left: 6px;
padding-right: 6px;
color: #fff;
}
#main {
min-height: 400px;
_height: 400px; /* IE min-height hack */
}
#footer {
+ margin:auto;
text-align: center;
- width: 900px;
+ width: 100%;
border-top: 2px solid #000;
padding-top: 15px;
}
#notice {
margin-top: 10px;
width: 100%;
background: #09F;
color: #000;
padding: 10px;
border: 1px solid #333;
}
#error {
margin-top: 10px;
width: 100%;
background: #F00;
color: #000;
padding: 10px;
border: 1px solid #333;
}
#form {
width: 350px;
margin: auto;
}
.submitbutton {
background: #660033;
color: #fff;
border: 3px solid #000;
padding: 6px;
}
.fbox {
background: #ffff55;
border: 1px solid #333;
padding: 2px;
}
.clear {
clear:both;
}
.adendem {
font-size: 14px;
font-weight: normal;
}
.in20 {
padding-left: 20px;
padding-right: 20px;
}
.errorExplanation {
width: 800px;
margin: auto;
padding: 3px;
padding-left: 10px;
padding-right: 10px;
background: #ffff55;
border: 1px solid #333;
margin-bottom: 10px;
}
.subnav {
float:right;
}
.agent {
margin-top: 10px;
padding: 2px;
}
.result {
padding: 5px;
}
.advancedsearch {
display: none;
background:#FF9;
padding: 3px;
border: 1px solid #000
}
#events {
}
.event{
background: #fff;
margin-bottom: 10px;
}
.event a {
color:#333;
}
.event a:hover {
color:#333;
background: #aaa;
}
#commandout {
overflow: auto;
white-space: nowrap;
background: #eee;
padding: 4px;
border: 1px solid #AAA;
margin: 5px;
}
#totalhits {
margin-bottom: 10px;
font-size: 14px;
}
.mainsearchbox {
background: #FF9;
border: solid 1px #000;
font-size: 20px;
padding: 2px;
font-weight: none;
}
.searchsubmitbutton {
background: #660033;
color: #fff;
border: 1px solid #000;
padding: 6px;
height: 28px;
}
.rightsearch {
float:right;
text-align: right;
}
.minisearchbox {
background: #FF9;
border: 1px solid #000;
}
\ No newline at end of file
|
parabuzzle/cistern
|
0b3a2a26274964f43bb8c3ee5e2c45cb876be5b4
|
bad times being commited. changed etime to int
|
diff --git a/src/server/app/models/event.rb b/src/server/app/models/event.rb
index e25e713..8b096fb 100644
--- a/src/server/app/models/event.rb
+++ b/src/server/app/models/event.rb
@@ -1,25 +1,25 @@
class Event < ActiveRecord::Base
include ApplicationHelper
acts_as_ferret :fields => ['full_event', :etime]
belongs_to :staticentry
belongs_to :agent
belongs_to :loglevel
cattr_reader :per_page
- @@per_page = 20
+ @@per_page = 50
default_scope :order => 'etime DESC'
#Validations
validates_presence_of :agent_id, :loglevel_id, :etime, :logtype_id
def full_event
return rebuildevent(self)
end
end
diff --git a/src/server/app/views/events/show.rhtml b/src/server/app/views/events/show.rhtml
index 05ea883..4aff993 100644
--- a/src/server/app/views/events/show.rhtml
+++ b/src/server/app/views/events/show.rhtml
@@ -1,36 +1,38 @@
<h1>All Events</h1>
<%unless params[:loglevel].nil?%>
<div class="adendem"><%=link_to("clear filters", :action => "show", :loglevel => nil)%></div>
<%end%>
<div id="events">
+
<% for event in @events do %>
<div class="event">
<a href="#" onclick="$('.eventinfo<%=event.id%>').toggle();return false"><%= if params[:withepoch] then event.etime else Time.at(event.etime.to_f) end %></a> : <%= link_to(h(event.loglevel.name), :action => "show", :loglevel => event.loglevel.id, :withepoch => params[:withepoch])%> ::
<%= sanitize event.payload, :tags => %w(br) %>
<div class="eventinfo<%=event.id%>" style="display:none; background:#FF9; border:1px solid #000; padding:5px;">
<div class="info">Agent: <%=link_to(h(event.agent.name), :controller => "agents", :action => "show", :id => event.agent.id)%></div>
<div class="info">Logtype: <%=link_to(h(event.staticentry.logtype.name), :controller => "logtypes", :action => "show", :id => event.staticentry.logtype.id)%></div>
<div class="info">Static Entry Id: <%=h event.staticentry_id%></div>
</div>
</div>
<%end%>
+
</div>
<div class="pagination">
<%= will_paginate @event %>
</div>
<div class="adendem">
Records per page:
<%=link_to "20", :loglevel => params[:loglevel], :withepoch => params[:withepoch], :page => 1, :perpage => "20" %> |
<%=link_to "50", :loglevel => params[:loglevel], :withepoch => params[:withepoch], :page => 1, :perpage => "50" %> |
<%=link_to "100", :loglevel => params[:loglevel], :withepoch => params[:withepoch], :page => 1, :perpage => "100" %> |
<%=link_to "200", :loglevel => params[:loglevel], :withepoch => params[:withepoch], :page => 1, :perpage => "200" %>
</div>
<%if params[:withepoch]%>
<div class="adendem"><%=link_to "show regular time", :withepoch => nil, :loglevel => params[:loglevel], :page => params[:page], :perpage => params[:perpage] %></div>
<%else%>
<div class="adendem"><%=link_to "show epoch time", :withepoch => 1, :loglevel => params[:loglevel], :page => params[:page], :perpage => params[:perpage] %></div>
<%end%>
<div class="adendem"><%=link_to "view by agent", :controller => 'agents', :action => "index" %> | <%=link_to "view by logtype", :controller => 'logtypes', :action => 'index' %></div>
diff --git a/src/server/db/migrate/20090721233433_create_events.rb b/src/server/db/migrate/20090721233433_create_events.rb
index 4e39165..732c165 100644
--- a/src/server/db/migrate/20090721233433_create_events.rb
+++ b/src/server/db/migrate/20090721233433_create_events.rb
@@ -1,22 +1,22 @@
class CreateEvents < ActiveRecord::Migration
def self.up
create_table :events do |t|
t.column :payload, :string
t.column :staticentry_id, :string
t.column :agent_id, :int
t.column :loglevel_id, :int
t.column :logtype_id, :int
- t.column :etime, :float
+ t.column :etime, :int
t.timestamps
end
add_index :events, :logtype_id
add_index :events, :loglevel_id
add_index :events, :etime
add_index :events, :agent_id
add_index :events, :staticentry_id
end
def self.down
drop_table :events
end
end
diff --git a/src/server/lib/modules/collection_server.rb b/src/server/lib/modules/collection_server.rb
index 6c17f6d..7dfbdc1 100644
--- a/src/server/lib/modules/collection_server.rb
+++ b/src/server/lib/modules/collection_server.rb
@@ -1,89 +1,89 @@
module CollectionServer
#TODO: Checksum check should be wrapped in to an exception and then and handled that way in receive_data
#Set buffer delimiters
@@break = '__1_BB'
@@value = '__1_VV'
@@finish = '__1_EE'
def check_key(agent, key)
if agent.authkey != key
return false
else
return true
end
end
#Write a log entry
def log_entry(line)
raw = line.split(@@break)
map = Hash.new
raw.each do |keys|
parts = keys.split(@@value)
map.store(parts[0],parts[1])
end
#unless USEMEMCACHE != true
# if Staticentry.get_cache(Digest::MD5.hexdigest(map['data'] + map['logtype_id'].to_s)).nil?
# static = Logtype.find(map['logtype_id']).staticentries.new
# static.data = map['data']
# static.save
# end
#else
static = Logtype.find(map['logtype_id']).staticentries.new
static.data = map['data']
static.save
#end
unless USEMEMCACHE != true
static = Staticentry.get_cache(Digest::MD5.hexdigest(map['data'] + map['logtype_id'].to_s))
else
static = Staticentry.find(Digest::MD5.hexdigest(map['data'] + map['logtype_id'].to_s))
end
event = static.events.new
- event.etime = map['etime']
- event.loglevel_id = map['loglevel_id']
+ event.etime = map['etime'].to_i
+ event.loglevel_id = map['loglevel_id'].to_i
event.payload = map['payload']
- event.logtype_id = map['logtype_id']
- event.agent_id = map['agent_id']
+ event.logtype_id = map['logtype_id'].to_i
+ event.agent_id = map['agent_id'].to_i
if check_key(Agent.find(map['agent_id']), map['authkey'])
event.save
else
ActiveRecord::Base.logger.debug "Event dropped -- invalid agent authkey sent"
end
port, ip = Socket.unpack_sockaddr_in(get_peername)
host = Socket.getaddrinfo(ip, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME)[0][2]
ActiveRecord::Base.logger.debug "New event logged from #{host} \n -- Log data: #{line}"
end
#Do this when a connection is initialized
def post_init
port, ip = Socket.unpack_sockaddr_in(get_peername)
host = Socket.getaddrinfo(ip, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME)[0][2]
ActiveRecord::Base.logger.info "-- Collector connection established from #{host}"
end
#Do this when data is received
def receive_data(data)
(@buffer ||= BufferedTokenizer.new(delimiter = "__1_EE")).extract(data).each do |line|
#strip newline at beginning of line
if line.match(/^\W{1}./)
line = line[1..line.length-1]
end
if line.valid?
log_entry(line)
else
port, ip = Socket.unpack_sockaddr_in(get_peername)
host = Socket.getaddrinfo(ip, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME)[0][2]
ActiveRecord::Base.logger.error "Dropped log entry from #{host} - checksum invalid"
end
end
end
#Do this when a connection is closed by a peer
def unbind
ActiveRecord::Base.logger.info "-- Collector connection closed by a peer"
end
end
\ No newline at end of file
diff --git a/src/server/public/stylesheets/main.css b/src/server/public/stylesheets/main.css
index 3aa041c..02ca319 100644
--- a/src/server/public/stylesheets/main.css
+++ b/src/server/public/stylesheets/main.css
@@ -1,242 +1,245 @@
body {
background: #fff;
color: #000;
margin: 0px;
padding: 0px;
color: #333;
font-weight:bold;
font-family: serif;
}
a {
text-decoration: none;
color: #660033;
}
a:hover {
background: #000033;
color: #fff;
padding: 2px;
}
#container {
padding: 0px;
margin: auto;
width: 900px;
}
#header {
width: 100%;
margin: 0px;
height: 95px;
background: #333;
border-bottom: solid 6px #000;
color:#fff;
}
#logo {
position: absolute;
padding-top: 20px;
padding-left: 45px;
font-weight:bold;
font-size: 55px;
color: #fff;
}
#search {
text-align: right;
padding-top: 20px;
padding-right: 50px;
}
.searchbox {
background: #663366;
border: 1px solid #000;
color: #fff;
font-size: 20px;
padding: 2px;
font-weight: none;
}
#eventlist {
min-height: 350px;
_height: 350px;
}
#topnav a {
background: #000;
padding: 4px;
padding-bottom: 4px;
padding-left: 6px;
padding-right: 6px;
color: #fff;
border-left: solid 2px #000033;
border-right: solid 2px #000033;
border-bottom: solid 2px #000033;
}
#topnav a:hover {
background: #666;
padding: 4px;
padding-bottom: 4px;
padding-left: 6px;
padding-right: 6px;
color: #fff;
border-left: solid 2px #000033;
border-right: solid 2px #000033;
border-bottom: solid 2px #000033;
}
.topnav {
background: #666;
padding: 2px;
padding-bottom: 4px;
padding-left: 6px;
padding-right: 6px;
color: #fff;
border-left: solid 2px #000033;
border-right: solid 2px #000033;
border-bottom: solid 2px #000033;
}
#topnav {
font-size: 20px;
padding: 2px;
padding-bottom: 4px;
padding-left: 6px;
padding-right: 6px;
color: #fff;
}
#main {
min-height: 400px;
_height: 400px; /* IE min-height hack */
}
#footer {
text-align: center;
width: 900px;
border-top: 2px solid #000;
padding-top: 15px;
}
#notice {
margin-top: 10px;
width: 100%;
background: #09F;
color: #000;
padding: 10px;
border: 1px solid #333;
}
#error {
margin-top: 10px;
width: 100%;
background: #F00;
color: #000;
padding: 10px;
border: 1px solid #333;
}
#form {
width: 350px;
margin: auto;
}
.submitbutton {
background: #660033;
color: #fff;
border: 3px solid #000;
padding: 6px;
}
.fbox {
background: #ffff55;
border: 1px solid #333;
padding: 2px;
}
.clear {
clear:both;
}
.adendem {
font-size: 14px;
font-weight: normal;
}
.in20 {
padding-left: 20px;
padding-right: 20px;
}
.errorExplanation {
width: 800px;
margin: auto;
padding: 3px;
padding-left: 10px;
padding-right: 10px;
background: #ffff55;
border: 1px solid #333;
margin-bottom: 10px;
}
.subnav {
float:right;
}
.agent {
margin-top: 10px;
padding: 2px;
}
.result {
padding: 5px;
}
.advancedsearch {
display: none;
background:#FF9;
padding: 3px;
border: 1px solid #000
}
+#events {
+
+}
.event{
background: #fff;
margin-bottom: 10px;
}
.event a {
color:#333;
}
.event a:hover {
color:#333;
background: #aaa;
}
#commandout {
overflow: auto;
white-space: nowrap;
background: #eee;
padding: 4px;
border: 1px solid #AAA;
margin: 5px;
}
#totalhits {
margin-bottom: 10px;
font-size: 14px;
}
.mainsearchbox {
background: #FF9;
border: solid 1px #000;
font-size: 20px;
padding: 2px;
font-weight: none;
}
.searchsubmitbutton {
background: #660033;
color: #fff;
border: 1px solid #000;
padding: 6px;
height: 28px;
}
.rightsearch {
float:right;
text-align: right;
}
.minisearchbox {
background: #FF9;
border: 1px solid #000;
}
\ No newline at end of file
|
parabuzzle/cistern
|
138af2ce0eed3efa65a9f04c8772a8d6a1ba9aa3
|
ignoring rubymine files
|
diff --git a/.gitignore b/.gitignore
index f7f726b..c2238c9 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,10 +1,11 @@
*.log
*.pid
*.sqlite3
src/server/config/database.yml
src/server/config/daemons.yml
src/server/config/collectors.yml
src/server/config/cistern.yml
src/server/config/memcached.yml
src/server/index
src/server/db/schema.rb
+src/server/.idea
|
parabuzzle/cistern
|
5f0cf8251f99cd9c6237771c0e51950f07da3723
|
fixed issue 16
|
diff --git a/src/server/app/views/logtypes/search.rhtml b/src/server/app/views/logtypes/search.rhtml
index 9b97344..ed9db0f 100644
--- a/src/server/app/views/logtypes/search.rhtml
+++ b/src/server/app/views/logtypes/search.rhtml
@@ -1,24 +1,24 @@
<div class="rightsearch">
<div>
<% form_for :search, :url => { :id => params[:id]} do |form| %>
<div>Search within Logtype</div>
<div><%= form.text_field :data, :size => 20, :class => "minisearchbox", :value => params[:aquery] %> </div>
<%end%>
</div>
</div>
<h1>Search Results</h1>
<div id="totalhits">Found <%=@total%> matching results</div>
<div id="events">
<% for event in @results do %>
<div class="event">
- <a href="#" onclick="$('.eventinfo<%=event.id%>').toggle();return false"><%= if params[:withepoch] then event.etime else Time.at(event.etime.to_f) end %></a> : <%= h event.loglevel.name %> ::
+ <a href="#" onclick="$('.eventinfo<%=event.id%>').toggle();return false;"><%= if params[:withepoch] then event.etime else Time.at(event.etime.to_f) end %></a> : <%= h event.loglevel.name %> ::
<%=h event.full_event%>
<div class="eventinfo<%=event.id%>" style="display:none; background:#FF9; border:1px solid #000; padding:5px; width:50%">
<div class="info">Agent: <%=link_to(h(event.agent.name), :controller => "agents", :action => "show", :id => event.agent.id)%></div>
- <div class="info">Logtype: <%=link_to(h(event.staticentry).logtype.name, :controller => "logtypes", :action => "show", :id => event.staticentry.logtype.id)%></div>
+ <div class="info">Logtype: <%=link_to(h(event.staticentry.logtype.name), :controller => "logtypes", :action => "show", :id => event.staticentry.logtype.id)%></div>
<div class="info">Static Entry Id: <%=h event.staticentry_id%></div>
</div>
</div>
<%end%>
</div>
<%=will_paginate @results%>
\ No newline at end of file
diff --git a/src/server/app/views/logtypes/show.rhtml b/src/server/app/views/logtypes/show.rhtml
index 8efde2f..28288da 100644
--- a/src/server/app/views/logtypes/show.rhtml
+++ b/src/server/app/views/logtypes/show.rhtml
@@ -1,46 +1,46 @@
<div class="rightsearch">
<div>
<% form_for :search, :url => { :id => params[:id]} do |form| %>
<div>Search within Logtype</div>
<div><%= form.text_field :data, :size => 20, :class => "minisearchbox" %> </div>
<%end%>
</div>
</div>
-<div class="clear"></div>
+<div class="clear"/>
<h1>All Events for <%=h @logtype.name%></h1>
<div id="filter">
- <a href='#' onclick="$('.agentinfo').toggle();return false">View by Agent</a>
+ <a href='#' onclick="$('.agentinfo').toggle();return false;">View by Agent</a>
<div class="agentinfo" style="display:none; background:#FF9; padding: 3px; border: 1px solid #000">
<% for agent in @logtype.agents do %>
<div class="info"><%= link_to( h(agent.name), :controller => 'agents', :action => 'show', :logtype => @logtype.id, :withepoch => params[:withepoch], :id => agent.id )%></div>
<%end%>
</div>
</div>
<div id="events">
<% for event in @events do %>
<div class="event">
- <a href="#" onclick="$('.eventinfo<%=event.id%>').toggle();return false"><%= if params[:withepoch] then event.etime else Time.at(event.etime.to_f) end %></a> : <%= link_to(h(event.loglevel.name), :action => "show", :loglevel => event.loglevel.id, :withepoch => params[:withepoch])%> ::
+ <a href="#" onclick="$('.eventinfo<%=event.id%>').toggle();return false;"><%= if params[:withepoch] then event.etime else Time.at(event.etime.to_f) end %></a> : <%= link_to(h(event.loglevel.name), :action => "show", :loglevel => event.loglevel.id, :withepoch => params[:withepoch])%> ::
<%=sanitize event.payload, :tags => %w(br)%>
<div class="eventinfo<%=event.id%>" style="display:none; background:#FF9; border:1px solid #000; padding:5px;">
<div class="info">Agent: <%=link_to(h(event.agent.name), :controller => "agents", :action => "show", :id => event.agent.id)%></div>
<div class="info">Static Entry Id: <%=h event.staticentry_id%></div>
</div>
</div>
<%end%>
</div>
<div class="pagination">
<%= will_paginate @event %>
</div>
<div class="adendem">
Records per page:
<%=link_to "20", :withepoch => params[:withepoch], :page => 1, :perpage => "20" %> |
<%=link_to "50", :withepoch => params[:withepoch], :page => 1, :perpage => "50" %> |
<%=link_to "100", :withepoch => params[:withepoch], :page => 1, :perpage => "100" %> |
<%=link_to "200", :withepoch => params[:withepoch], :page => 1, :perpage => "200" %>
</div>
<%if params[:withepoch]%>
<div class="adendem"><%=link_to "show regular time", :withepoch => nil, :page => params[:page], :perpage => params[:perpage] %></div>
<%else%>
<div class="adendem"><%=link_to "show epoch time", :withepoch => 1, :page => params[:page], :perpage => params[:perpage] %></div>
<%end%>
\ No newline at end of file
|
parabuzzle/cistern
|
6a9317c09f7bc7368123b32f8c220c66a0bbf528
|
Dealing with newlines at the beginning of event lines
|
diff --git a/src/server/config/initializers/extended_modules.rb b/src/server/config/initializers/extended_modules.rb
index 2d44c4e..0df7603 100644
--- a/src/server/config/initializers/extended_modules.rb
+++ b/src/server/config/initializers/extended_modules.rb
@@ -1,18 +1,19 @@
#This initializer is used to pull in modules and extentions in other directories. (The include functions in envrionment.rb is crap)
require 'digest/md5'
require RAILS_ROOT + '/lib/modules/collection_server.rb'
require RAILS_ROOT + '/lib/modules/command_server.rb'
USEMEMCACHE = YAML::load(File.open(RAILS_ROOT + "/config/cistern.yml"))['usememcache']
#Mixin for the string class to add a validity check for log events based on the checksum appended to buffered received data
class String
def valid?
part = self.split('__1_CC')
+ puts part[0]
if Digest::MD5.hexdigest(part[0]) == part[1]
return true
else
return false
end
end
end
\ No newline at end of file
diff --git a/src/server/lib/modules/collection_server.rb b/src/server/lib/modules/collection_server.rb
index 50d2774..6c17f6d 100644
--- a/src/server/lib/modules/collection_server.rb
+++ b/src/server/lib/modules/collection_server.rb
@@ -1,86 +1,89 @@
module CollectionServer
#TODO: Checksum check should be wrapped in to an exception and then and handled that way in receive_data
#Set buffer delimiters
@@break = '__1_BB'
@@value = '__1_VV'
@@finish = '__1_EE'
def check_key(agent, key)
if agent.authkey != key
return false
else
return true
end
end
#Write a log entry
def log_entry(line)
raw = line.split(@@break)
map = Hash.new
raw.each do |keys|
parts = keys.split(@@value)
map.store(parts[0],parts[1])
end
#unless USEMEMCACHE != true
# if Staticentry.get_cache(Digest::MD5.hexdigest(map['data'] + map['logtype_id'].to_s)).nil?
# static = Logtype.find(map['logtype_id']).staticentries.new
# static.data = map['data']
# static.save
# end
#else
static = Logtype.find(map['logtype_id']).staticentries.new
static.data = map['data']
static.save
#end
unless USEMEMCACHE != true
static = Staticentry.get_cache(Digest::MD5.hexdigest(map['data'] + map['logtype_id'].to_s))
else
static = Staticentry.find(Digest::MD5.hexdigest(map['data'] + map['logtype_id'].to_s))
end
event = static.events.new
event.etime = map['etime']
event.loglevel_id = map['loglevel_id']
event.payload = map['payload']
event.logtype_id = map['logtype_id']
event.agent_id = map['agent_id']
if check_key(Agent.find(map['agent_id']), map['authkey'])
event.save
else
ActiveRecord::Base.logger.debug "Event dropped -- invalid agent authkey sent"
end
port, ip = Socket.unpack_sockaddr_in(get_peername)
host = Socket.getaddrinfo(ip, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME)[0][2]
ActiveRecord::Base.logger.debug "New event logged from #{host} \n -- Log data: #{line}"
end
#Do this when a connection is initialized
def post_init
port, ip = Socket.unpack_sockaddr_in(get_peername)
host = Socket.getaddrinfo(ip, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME)[0][2]
ActiveRecord::Base.logger.info "-- Collector connection established from #{host}"
end
#Do this when data is received
def receive_data(data)
(@buffer ||= BufferedTokenizer.new(delimiter = "__1_EE")).extract(data).each do |line|
+ #strip newline at beginning of line
+ if line.match(/^\W{1}./)
+ line = line[1..line.length-1]
+ end
if line.valid?
- puts line
log_entry(line)
else
port, ip = Socket.unpack_sockaddr_in(get_peername)
host = Socket.getaddrinfo(ip, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME)[0][2]
ActiveRecord::Base.logger.error "Dropped log entry from #{host} - checksum invalid"
end
end
end
#Do this when a connection is closed by a peer
def unbind
ActiveRecord::Base.logger.info "-- Collector connection closed by a peer"
end
end
\ No newline at end of file
|
parabuzzle/cistern
|
323b342074cc21ab6ebb728b5f0beafa2ae17d29
|
Working on log4j apo
|
diff --git a/src/plugins/log4j/.classpath b/src/plugins/log4j/.classpath
index e27f6e5..d8b3f86 100644
--- a/src/plugins/log4j/.classpath
+++ b/src/plugins/log4j/.classpath
@@ -1,8 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="target/classes" path="src/main/java"/>
+ <classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources"/>
<classpathentry kind="src" output="target/test-classes" path="src/test/java"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="con" path="org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER"/>
<classpathentry kind="output" path="target/classes"/>
</classpath>
diff --git a/src/plugins/log4j/pom.xml b/src/plugins/log4j/pom.xml
index aad8be2..02b474f 100644
--- a/src/plugins/log4j/pom.xml
+++ b/src/plugins/log4j/pom.xml
@@ -1,25 +1,25 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
- <groupId>com.yahoo.groups.log4j</groupId>
- <artifactId>cistern</artifactId>
+ <groupId>org.cistern.log4j</groupId>
+ <artifactId>cistern-appender</artifactId>
<packaging>jar</packaging>
- <version>0.0.1-SNAPSHOT1</version>
+ <version>0.0.1-SNAPSHOT</version>
<name>cistern</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.15</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
diff --git a/src/plugins/log4j/src/main/java/org/cistern/log4j/appender/TCPAppender.java b/src/plugins/log4j/src/main/java/org/cistern/log4j/appender/TCPAppender.java
index 8f27cc6..0195681 100644
--- a/src/plugins/log4j/src/main/java/org/cistern/log4j/appender/TCPAppender.java
+++ b/src/plugins/log4j/src/main/java/org/cistern/log4j/appender/TCPAppender.java
@@ -1,157 +1,157 @@
package org.cistern.log4j.appender;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.Level;
import org.apache.log4j.spi.LoggingEvent;
import org.apache.log4j.spi.ErrorCode;
import org.cistern.log4j.appender.LogObject;
import org.cistern.log4j.appender.Util;
import java.security.NoSuchAlgorithmException;
import java.io.*;
import java.net.*;
public class TCPAppender extends AppenderSkeleton {
//Setup variables
String serverhost;
int serverport;
String agent_id;
String logtype_id;
String authkey;
int timeout;
static String eq = "/000/";
static String newval = "/111/";
//Setup loglevels
String fatal = "1";
String error = "2";
String warn = "3";
String info = "4";
String debug = "5";
String level;
protected void append(LoggingEvent arg0) {
// Log4j calls this with a log event
String s;
LoggingEvent entry = arg0;
if (entry.getThrowableStrRep() == null){
s = "";
} else {
s = entry.getThrowableStrRep()[0]; //This needs fixing...
}
LogObject event = new LogObject("<<<MESSAGE>>> " + s, "MESSAGE" + eq + entry.getMessage(), this.authkey, this.logtype_id, this.agent_id);
if (entry.getLevel() == Level.DEBUG) {
level = debug;
}else if (entry.getLevel() == Level.INFO){
level = info;
}else if (entry.getLevel() == Level.WARN){
level = warn;
}else if (entry.getLevel() == Level.ERROR){
level = error;
}else if (entry.getLevel() == Level.FATAL){
level = fatal;
}else{
level = "6";
}
event.setLoglevel_id(level);
- event.setEtime(Long.toString(entry.getTimeStamp()/1000));
+ //event.setEtime(Long.toString(entry.getTimeStamp()/1000));
String data = null;
try {
data = Util.getSendableString(event);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
System.out.println(data);
try {
sendData(data);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendData(String data) throws UnknownHostException, IOException {
Socket sock = new Socket();
sock.bind(null);
try {
sock.connect(new InetSocketAddress(serverhost, serverport), timeout);
PrintWriter out = new PrintWriter(sock.getOutputStream(), true);
out.println(data);
sock.close();
} catch (SocketTimeoutException e) {
System.out.println("Socket Connection Timedout");
}
}
public void close() {
// TODO Auto-generated method stub
}
public boolean requiresLayout() {
return false;
}
public String getServerhost() {
return serverhost;
}
public void setServerhost(String serverhost) {
this.serverhost = serverhost;
}
public int getServerport() {
return serverport;
}
public void setServerport(int serverport) {
this.serverport = serverport;
}
public String getAgent_id() {
return agent_id;
}
public void setAgent_id(String agent_id) {
this.agent_id = agent_id;
}
public String getLogtype_id() {
return logtype_id;
}
public void setLogtype_id(String logtype_id) {
this.logtype_id = logtype_id;
}
public String getAuthkey() {
return authkey;
}
public void setAuthkey(String authkey) {
this.authkey = authkey;
}
public int getTimeout() {
return timeout;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
}
diff --git a/src/plugins/log4j/src/test/java/org/cistern/log4j/appender/AppTest.java b/src/plugins/log4j/src/test/java/org/cistern/log4j/appender/AppTest.java
index e63cdf0..b14d456 100644
--- a/src/plugins/log4j/src/test/java/org/cistern/log4j/appender/AppTest.java
+++ b/src/plugins/log4j/src/test/java/org/cistern/log4j/appender/AppTest.java
@@ -1,38 +1,38 @@
-package com.yahoo.groups.log4j.cistern;
+package org.cistern.log4j.appender;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
}
}
diff --git a/src/plugins/log4j/target/appender-0.0.1-SNAPSHOT1.jar b/src/plugins/log4j/target/appender-0.0.1-SNAPSHOT1.jar
new file mode 100644
index 0000000..83b2ec2
Binary files /dev/null and b/src/plugins/log4j/target/appender-0.0.1-SNAPSHOT1.jar differ
diff --git a/src/plugins/log4j/target/classes/log4j.properties b/src/plugins/log4j/target/classes/log4j.properties
new file mode 100644
index 0000000..a28e32f
--- /dev/null
+++ b/src/plugins/log4j/target/classes/log4j.properties
@@ -0,0 +1,17 @@
+log4j.rootLogger=DEBUG, FILE, CONSOLE, REMOTE
+log4j.appender.FILE=org.apache.log4j.FileAppender
+log4j.appender.FILE.file=/tmp/logs/log.txt
+log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
+log4j.appender.FILE.layout.ConversionPattern=[%d{MMM dd HH:mm:ss}] %-5p (%F:%L) - %m%n
+log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
+log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
+log4j.appender.CONSOLE.layout.ConversionPattern=[%d{MMM dd HH:mm:ss}] %-5p (%F:%L) - %m%n
+log4j.appender.REMOTE=org.cistern.log4j.appender.TCPAppender
+log4j.appender.REMOTE.serverhost=127.0.0.1
+log4j.appender.REMOTE.serverport=9845
+log4j.appender.REMOTE.agent_id=1
+log4j.appender.REMOTE.logtype_id=1
+log4j.appender.REMOTE.authkey=7952d3072b86a949e45232fe42ad03bc
+log4j.appender.REMOTE.timeout=100
+
+
diff --git a/src/plugins/log4j/target/classes/org/cistern/log4j/appender/App.class b/src/plugins/log4j/target/classes/org/cistern/log4j/appender/App.class
new file mode 100644
index 0000000..0cc53be
Binary files /dev/null and b/src/plugins/log4j/target/classes/org/cistern/log4j/appender/App.class differ
diff --git a/src/plugins/log4j/target/classes/org/cistern/log4j/appender/LogObject.class b/src/plugins/log4j/target/classes/org/cistern/log4j/appender/LogObject.class
new file mode 100644
index 0000000..ec07299
Binary files /dev/null and b/src/plugins/log4j/target/classes/org/cistern/log4j/appender/LogObject.class differ
diff --git a/src/plugins/log4j/target/classes/org/cistern/log4j/appender/TCPAppender.class b/src/plugins/log4j/target/classes/org/cistern/log4j/appender/TCPAppender.class
new file mode 100644
index 0000000..0c5e8f4
Binary files /dev/null and b/src/plugins/log4j/target/classes/org/cistern/log4j/appender/TCPAppender.class differ
diff --git a/src/plugins/log4j/target/classes/org/cistern/log4j/appender/Util.class b/src/plugins/log4j/target/classes/org/cistern/log4j/appender/Util.class
new file mode 100644
index 0000000..a49156b
Binary files /dev/null and b/src/plugins/log4j/target/classes/org/cistern/log4j/appender/Util.class differ
diff --git a/src/plugins/log4j/target/maven-archiver/pom.properties b/src/plugins/log4j/target/maven-archiver/pom.properties
new file mode 100644
index 0000000..9597c57
--- /dev/null
+++ b/src/plugins/log4j/target/maven-archiver/pom.properties
@@ -0,0 +1,5 @@
+#Generated by Maven
+#Thu Aug 13 12:38:39 PDT 2009
+version=0.0.1-SNAPSHOT1
+groupId=org.cistern.log4j
+artifactId=appender
diff --git a/src/plugins/log4j/target/surefire-reports/TEST-org.cistern.log4j.appender.AppTest.xml b/src/plugins/log4j/target/surefire-reports/TEST-org.cistern.log4j.appender.AppTest.xml
new file mode 100644
index 0000000..a738bf7
--- /dev/null
+++ b/src/plugins/log4j/target/surefire-reports/TEST-org.cistern.log4j.appender.AppTest.xml
@@ -0,0 +1,84 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<testsuite errors="0" skipped="0" tests="1" time="0.024" failures="0" name="org.cistern.log4j.appender.AppTest">
+ <properties>
+ <property value="Apple Inc." name="java.vendor"/>
+ <property value="/Users/heijmans/.m2/repository" name="localRepository"/>
+ <property value="SUN_STANDARD" name="sun.java.launcher"/>
+ <property value="HotSpot Client Compiler" name="sun.management.compiler"/>
+ <property value="813c90" name="env.SECURITYSESSIONID"/>
+ <property value="Mac OS X" name="os.name"/>
+ <property value="/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Classes/jsfd.jar:/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Classes/classes.jar:/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Classes/ui.jar:/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Classes/laf.jar:/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Classes/sunrsasign.jar:/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Classes/jsse.jar:/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Classes/jce.jar:/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Classes/charsets.jar" name="sun.boot.class.path"/>
+ <property value="/var/folders/K2/K2XkcjL5FoyjLv4ykudu3k++gAY/-Tmp-/" name="env.TMPDIR"/>
+ <property value="Sun Microsystems Inc." name="java.vm.specification.vendor"/>
+ <property value="1.5.0_19-b02-304" name="java.runtime.version"/>
+ <property value="/tmp/launch-z7dbML/Render" name="env.Apple_PubSub_Socket_Render"/>
+ <property value="/tmp/launch-doYP0q/:0" name="env.DISPLAY"/>
+ <property value="heijmans" name="user.name"/>
+ <property value="heijmans" name="env.USER"/>
+ <property value="/bin/bash" name="env.SHELL"/>
+ <property value="0xB0C9:0:0" name="env.__CF_USER_TEXT_ENCODING"/>
+ <property value="true" name="awt.nativeDoubleBuffering"/>
+ <property value="/usr/bin:/bin:/usr/sbin:/sbin" name="env.PATH"/>
+ <property value="en" name="user.language"/>
+ <property value="../Resources/Eclipse.icns" name="env.APP_ICON_24279"/>
+ <property value="/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Libraries" name="sun.boot.library.path"/>
+ <property value="1.5.0_19" name="java.version"/>
+ <property value="1" name="env.JAVA_STARTED_ON_FIRST_THREAD_24279"/>
+ <property value="" name="user.timezone"/>
+ <property value="32" name="sun.arch.data.model"/>
+ <property value="local|*.local|169.254/16|*.169.254/16" name="http.nonProxyHosts"/>
+ <property value="/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Home/lib/endorsed" name="java.endorsed.dirs"/>
+ <property value="" name="sun.cpu.isalist"/>
+ <property value="MacRoman" name="sun.jnu.encoding"/>
+ <property value="sun.io" name="file.encoding.pkg"/>
+ <property value="/" name="file.separator"/>
+ <property value="Java Platform API Specification" name="java.specification.name"/>
+ <property value="49.0" name="java.class.version"/>
+ <property value="US" name="user.country"/>
+ <property value="/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Home" name="java.home"/>
+ <property value="mixed mode, sharing" name="java.vm.info"/>
+ <property value="heijmans" name="env.LOGNAME"/>
+ <property value="10.5.7" name="os.version"/>
+ <property value=":" name="path.separator"/>
+ <property value="1.5.0_19-137" name="java.vm.version"/>
+ <property value="apple.awt.CPrinterJob" name="java.awt.printerjob"/>
+ <property value="UnicodeLittle" name="sun.io.unicode.encoding"/>
+ <property value="apple.awt.CToolkit" name="awt.toolkit"/>
+ <property value="local|*.local|169.254/16|*.169.254/16" name="socksNonProxyHosts"/>
+ <property value="local|*.local|169.254/16|*.169.254/16" name="ftp.nonProxyHosts"/>
+ <property value="/Users/heijmans" name="user.home"/>
+ <property value="org.apache.maven.cli.MavenCli" name="env.JAVA_MAIN_CLASS_25011"/>
+ <property value="Sun Microsystems Inc." name="java.specification.vendor"/>
+ <property value=".:/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java" name="java.library.path"/>
+ <property value="http://www.apple.com/" name="java.vendor.url"/>
+ <property value="Apple Inc." name="java.vm.vendor"/>
+ <property value="false" name="gopherProxySet"/>
+ <property value="Java(TM) 2 Runtime Environment, Standard Edition" name="java.runtime.name"/>
+ <property value="/Applications/eclipse/plugins/org.maven.ide.components.maven_embedder_2.1.0.20080530-2300/jars/aspectjrt-1.5.3.jar:/Applications/eclipse/plugins/org.maven.ide.components.maven_embedder_2.1.0.20080530-2300/jars/commons-cli-1.0.jar:/Applications/eclipse/plugins/org.maven.ide.components.maven_embedder_2.1.0.20080530-2300/jars/doxia-sink-api-1.0-alpha-9.jar:/Applications/eclipse/plugins/org.maven.ide.components.maven_embedder_2.1.0.20080530-2300/jars/jsch-0.1.27.jar:/Applications/eclipse/plugins/org.maven.ide.components.maven_embedder_2.1.0.20080530-2300/jars/jtidy-4aug2000r7-dev.jar:/Applications/eclipse/plugins/org.maven.ide.components.maven_embedder_2.1.0.20080530-2300/jars/maven-artifact-3.0-SNAPSHOT.jar:/Applications/eclipse/plugins/org.maven.ide.components.maven_embedder_2.1.0.20080530-2300/jars/maven-core-2.1-SNAPSHOT.jar:/Applications/eclipse/plugins/org.maven.ide.components.maven_embedder_2.1.0.20080530-2300/jars/maven-embedder-2.1-SNAPSHOT.jar:/Applications/eclipse/plugins/org.maven.ide.components.maven_embedder_2.1.0.20080530-2300/jars/maven-lifecycle-2.1-SNAPSHOT.jar:/Applications/eclipse/plugins/org.maven.ide.components.maven_embedder_2.1.0.20080530-2300/jars/maven-model-2.1-SNAPSHOT.jar:/Applications/eclipse/plugins/org.maven.ide.components.maven_embedder_2.1.0.20080530-2300/jars/maven-plugin-api-2.1-SNAPSHOT.jar:/Applications/eclipse/plugins/org.maven.ide.components.maven_embedder_2.1.0.20080530-2300/jars/maven-profile-2.1-SNAPSHOT.jar:/Applications/eclipse/plugins/org.maven.ide.components.maven_embedder_2.1.0.20080530-2300/jars/maven-project-2.1-SNAPSHOT.jar:/Applications/eclipse/plugins/org.maven.ide.components.maven_embedder_2.1.0.20080530-2300/jars/maven-reporting-api-2.1-SNAPSHOT.jar:/Applications/eclipse/plugins/org.maven.ide.components.maven_embedder_2.1.0.20080530-2300/jars/maven-toolchain-2.1-SNAPSHOT.jar:/Applications/eclipse/plugins/org.maven.ide.components.maven_embedder_2.1.0.20080530-2300/jars/maven-workspace-2.1-SNAPSHOT.jar:/Applications/eclipse/plugins/org.maven.ide.components.maven_embedder_2.1.0.20080530-2300/jars/plexus-classworlds-1.2-alpha-12.jar:/Applications/eclipse/plugins/org.maven.ide.components.maven_embedder_2.1.0.20080530-2300/jars/plexus-container-default-1.0-alpha-44.jar:/Applications/eclipse/plugins/org.maven.ide.components.maven_embedder_2.1.0.20080530-2300/jars/plexus-interactivity-api-1.0-alpha-6.jar:/Applications/eclipse/plugins/org.maven.ide.components.maven_embedder_2.1.0.20080530-2300/jars/plexus-interpolation-1.0-SNAPSHOT.jar:/Applications/eclipse/plugins/org.maven.ide.components.maven_embedder_2.1.0.20080530-2300/jars/plexus-utils-1.5.1.jar:/Applications/eclipse/plugins/org.maven.ide.components.maven_embedder_2.1.0.20080530-2300/jars/wagon-file-1.0-beta-2.jar:/Applications/eclipse/plugins/org.maven.ide.components.maven_embedder_2.1.0.20080530-2300/jars/wagon-http-lightweight-1.0-beta-2.jar:/Applications/eclipse/plugins/org.maven.ide.components.maven_embedder_2.1.0.20080530-2300/jars/wagon-http-shared-1.0-beta-2.jar:/Applications/eclipse/plugins/org.maven.ide.components.maven_embedder_2.1.0.20080530-2300/jars/wagon-provider-api-1.0-beta-2.jar:/Applications/eclipse/plugins/org.maven.ide.components.maven_embedder_2.1.0.20080530-2300/jars/wagon-ssh-1.0-beta-2.jar:/Applications/eclipse/plugins/org.maven.ide.components.maven_embedder_2.1.0.20080530-2300/jars/wagon-ssh-common-1.0-beta-2.jar:/Applications/eclipse/plugins/org.maven.ide.components.maven_embedder_2.1.0.20080530-2300/jars/wagon-ssh-external-1.0-beta-2.jar" name="java.class.path"/>
+ <property value="ssh" name="env.CVS_RSH"/>
+ <property value="Java Virtual Machine Specification" name="java.vm.specification.name"/>
+ <property value="1.0" name="java.vm.specification.version"/>
+ <property value="little" name="sun.cpu.endian"/>
+ <property value="unknown" name="sun.os.patch.level"/>
+ <property value="/Users/heijmans" name="env.HOME"/>
+ <property value="/Users/heijmans/Projects/cistern/src/plugins/log4j/target/test-classes:/Users/heijmans/Projects/cistern/src/plugins/log4j/target/classes:/Users/heijmans/.m2/repository/junit/junit/3.8.1/junit-3.8.1.jar:/Users/heijmans/.m2/repository/log4j/log4j/1.2.15/log4j-1.2.15.jar:/Users/heijmans/.m2/repository/javax/mail/mail/1.4/mail-1.4.jar:/Users/heijmans/.m2/repository/javax/activation/activation/1.1/activation-1.1.jar:/Users/heijmans/.m2/repository/javax/jms/jms/1.1/jms-1.1.jar:/Users/heijmans/.m2/repository/com/sun/jdmk/jmxtools/1.2.1/jmxtools-1.2.1.jar:/Users/heijmans/.m2/repository/com/sun/jmx/jmxri/1.2.1/jmxri-1.2.1.jar:" name="surefire.test.class.path"/>
+ <property value="/var/folders/K2/K2XkcjL5FoyjLv4ykudu3k++gAY/-Tmp-/" name="java.io.tmpdir"/>
+ <property value="http://bugreport.apple.com/" name="java.vendor.url.bug"/>
+ <property value="/tmp/launch-wNYHDp/Listeners" name="env.SSH_AUTH_SOCK"/>
+ <property value="legacy" name="env.COMMAND_MODE"/>
+ <property value="i386" name="os.arch"/>
+ <property value="apple.awt.CGraphicsEnvironment" name="java.awt.graphicsenv"/>
+ <property value="/Library/Java/Extensions:/System/Library/Java/Extensions:/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Home/lib/ext" name="java.ext.dirs"/>
+ <property value="1050.1.5.0_19-304" name="mrj.version"/>
+ <property value="/Users/heijmans/Projects/cistern/src/plugins/log4j" name="user.dir"/>
+ <property value="
+" name="line.separator"/>
+ <property value="Java HotSpot(TM) Client VM" name="java.vm.name"/>
+ <property value="ssh" name="env.RSYNC_RSH"/>
+ <property value="/Users/heijmans/Projects/cistern/src/plugins/log4j" name="basedir"/>
+ <property value="true" name="maven.mode.standalone"/>
+ <property value="MacRoman" name="file.encoding"/>
+ <property value="1.5" name="java.specification.version"/>
+ </properties>
+ <testcase classname="org.cistern.log4j.appender.AppTest" time="0.003" name="testApp"/>
+</testsuite>
\ No newline at end of file
diff --git a/src/plugins/log4j/target/surefire-reports/org.cistern.log4j.appender.AppTest.txt b/src/plugins/log4j/target/surefire-reports/org.cistern.log4j.appender.AppTest.txt
new file mode 100644
index 0000000..f93f830
--- /dev/null
+++ b/src/plugins/log4j/target/surefire-reports/org.cistern.log4j.appender.AppTest.txt
@@ -0,0 +1,4 @@
+-------------------------------------------------------------------------------
+Test set: org.cistern.log4j.appender.AppTest
+-------------------------------------------------------------------------------
+Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.036 sec
diff --git a/src/plugins/log4j/target/test-classes/org/cistern/log4j/appender/AppTest.class b/src/plugins/log4j/target/test-classes/org/cistern/log4j/appender/AppTest.class
new file mode 100644
index 0000000..b40c874
Binary files /dev/null and b/src/plugins/log4j/target/test-classes/org/cistern/log4j/appender/AppTest.class differ
|
parabuzzle/cistern
|
6f263deae13166c4b3680320e4bfb03d4d8b25fd
|
Added the log4j appender I am working on
|
diff --git a/src/plugins/log4j/.classpath b/src/plugins/log4j/.classpath
new file mode 100644
index 0000000..e27f6e5
--- /dev/null
+++ b/src/plugins/log4j/.classpath
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="src" output="target/classes" path="src/main/java"/>
+ <classpathentry kind="src" output="target/test-classes" path="src/test/java"/>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
+ <classpathentry kind="con" path="org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER"/>
+ <classpathentry kind="output" path="target/classes"/>
+</classpath>
diff --git a/src/plugins/log4j/.project b/src/plugins/log4j/.project
new file mode 100644
index 0000000..59e1737
--- /dev/null
+++ b/src/plugins/log4j/.project
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>cistern</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.maven.ide.eclipse.maven2Builder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ <nature>org.maven.ide.eclipse.maven2Nature</nature>
+ </natures>
+</projectDescription>
diff --git a/src/plugins/log4j/.settings/org.eclipse.jdt.core.prefs b/src/plugins/log4j/.settings/org.eclipse.jdt.core.prefs
new file mode 100644
index 0000000..d5ca86f
--- /dev/null
+++ b/src/plugins/log4j/.settings/org.eclipse.jdt.core.prefs
@@ -0,0 +1,5 @@
+#Wed Aug 12 13:34:20 PDT 2009
+eclipse.preferences.version=1
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.2
+org.eclipse.jdt.core.compiler.compliance=1.4
+org.eclipse.jdt.core.compiler.source=1.3
diff --git a/src/plugins/log4j/.settings/org.maven.ide.eclipse.prefs b/src/plugins/log4j/.settings/org.maven.ide.eclipse.prefs
new file mode 100644
index 0000000..8c31759
--- /dev/null
+++ b/src/plugins/log4j/.settings/org.maven.ide.eclipse.prefs
@@ -0,0 +1,8 @@
+#Wed Aug 12 13:34:19 PDT 2009
+activeProfiles=
+eclipse.preferences.version=1
+fullBuildGoals=process-test-resources
+includeModules=false
+resolveWorkspaceProjects=true
+resourceFilterGoals=process-resources resources\:testResources
+version=1
diff --git a/src/plugins/log4j/pom.xml b/src/plugins/log4j/pom.xml
new file mode 100644
index 0000000..aad8be2
--- /dev/null
+++ b/src/plugins/log4j/pom.xml
@@ -0,0 +1,25 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>com.yahoo.groups.log4j</groupId>
+ <artifactId>cistern</artifactId>
+ <packaging>jar</packaging>
+ <version>0.0.1-SNAPSHOT1</version>
+ <name>cistern</name>
+ <url>http://maven.apache.org</url>
+ <dependencies>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <version>3.8.1</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>log4j</groupId>
+ <artifactId>log4j</artifactId>
+ <version>1.2.15</version>
+ <type>jar</type>
+ <scope>compile</scope>
+ </dependency>
+ </dependencies>
+</project>
diff --git a/src/plugins/log4j/src/main/java/org/cistern/log4j/appender/App.java b/src/plugins/log4j/src/main/java/org/cistern/log4j/appender/App.java
new file mode 100644
index 0000000..b5629cd
--- /dev/null
+++ b/src/plugins/log4j/src/main/java/org/cistern/log4j/appender/App.java
@@ -0,0 +1,26 @@
+package org.cistern.log4j.appender;
+
+import org.apache.log4j.Logger;
+import org.apache.log4j.LogManager;
+import org.cistern.log4j.appender.LogObject;
+import org.cistern.log4j.appender.TCPAppender;
+
+
+public class App
+{
+ private static final Logger log = Logger.getLogger("com.yahoo.groups.log4j.cistern");
+
+
+ public static void main( String[] args )
+ {
+ //LogObject log = new LogObject("Data Section <<<NAME>>>", "NAME/000/Cistern", "1", "1");
+ //log.setLoglevel_id("3");
+ log.debug("Debug Message");
+ log.info("Info Message");
+ log.warn("warn Message");
+ log.error("error Message");
+ log.fatal("fatal Message");
+
+
+ }
+}
diff --git a/src/plugins/log4j/src/main/java/org/cistern/log4j/appender/LogObject.java b/src/plugins/log4j/src/main/java/org/cistern/log4j/appender/LogObject.java
new file mode 100644
index 0000000..08778c6
--- /dev/null
+++ b/src/plugins/log4j/src/main/java/org/cistern/log4j/appender/LogObject.java
@@ -0,0 +1,101 @@
+package org.cistern.log4j.appender;
+
+public class LogObject {
+
+ String data; //Static Log Data//
+ String payload; //Dynamic Log Data//
+ String authkey; //Agent Authkey//
+ String logtype_id; //logtype_id for cistern server//
+ String loglevel_id; //loglevel to send//
+ String etime; //Event time//
+ String agent_id;
+
+ /*Constuctors to set defaults*/
+ public LogObject(String data, String payload, String authkey,
+ String logtype_id, String loglevel_id, String etime, String agent_id) {
+ super();
+ this.data = data;
+ this.payload = payload;
+ this.authkey = authkey;
+ this.logtype_id = logtype_id;
+ this.loglevel_id = loglevel_id;
+ this.etime = etime;
+ this.agent_id = agent_id;
+ }
+
+ public LogObject(String data, String payload, String authkey,
+ String logtype_id, String agent_id) {
+ super();
+ this.data = data;
+ this.payload = payload;
+ this.authkey = authkey;
+ this.logtype_id = logtype_id;
+ this.loglevel_id = "6";
+ this.agent_id = agent_id;
+ this.etime = Long.toString(System.currentTimeMillis()/1000);
+ }
+
+
+
+ public LogObject(String data, String payload, String logtype_id, String agent_id) {
+ super();
+ this.data = data;
+ this.payload = payload;
+ this.logtype_id = logtype_id;
+ this.loglevel_id = "6";
+ this.agent_id = agent_id;
+ this.etime = Long.toString(System.currentTimeMillis()/1000);
+ this.authkey = "";
+ }
+
+ /*Methods*/
+
+ public String getData() {
+ return data;
+ }
+ public String getAgent_id() {
+ return agent_id;
+ }
+
+ public void setAgent_id(String agent_id) {
+ this.agent_id = agent_id;
+ }
+
+ public void setData(String data) {
+ this.data = data;
+ }
+ public String getPayload() {
+ return payload;
+ }
+ public void setPayload(String payload) {
+ this.payload = payload;
+ }
+ public String getAuthkey() {
+ return authkey;
+ }
+ public void setAuthkey(String authkey) {
+ this.authkey = authkey;
+ }
+ public String getLogtype_id() {
+ return logtype_id;
+ }
+ public void setLogtype_id(String logtype_id) {
+ this.logtype_id = logtype_id;
+ }
+ public String getLoglevel_id() {
+ return loglevel_id;
+ }
+ public void setLoglevel_id(String loglevel_id) {
+ this.loglevel_id = loglevel_id;
+ }
+ public String getEtime() {
+ return etime;
+ }
+ public void setEtime(String etime) {
+ this.etime = etime;
+ }
+
+
+
+
+}
diff --git a/src/plugins/log4j/src/main/java/org/cistern/log4j/appender/TCPAppender.java b/src/plugins/log4j/src/main/java/org/cistern/log4j/appender/TCPAppender.java
new file mode 100644
index 0000000..8f27cc6
--- /dev/null
+++ b/src/plugins/log4j/src/main/java/org/cistern/log4j/appender/TCPAppender.java
@@ -0,0 +1,157 @@
+package org.cistern.log4j.appender;
+
+import org.apache.log4j.AppenderSkeleton;
+import org.apache.log4j.Level;
+import org.apache.log4j.spi.LoggingEvent;
+import org.apache.log4j.spi.ErrorCode;
+import org.cistern.log4j.appender.LogObject;
+import org.cistern.log4j.appender.Util;
+
+import java.security.NoSuchAlgorithmException;
+
+import java.io.*;
+import java.net.*;
+
+
+
+
+public class TCPAppender extends AppenderSkeleton {
+
+ //Setup variables
+ String serverhost;
+ int serverport;
+ String agent_id;
+ String logtype_id;
+ String authkey;
+ int timeout;
+
+ static String eq = "/000/";
+ static String newval = "/111/";
+
+ //Setup loglevels
+ String fatal = "1";
+ String error = "2";
+ String warn = "3";
+ String info = "4";
+ String debug = "5";
+ String level;
+
+ protected void append(LoggingEvent arg0) {
+ // Log4j calls this with a log event
+ String s;
+ LoggingEvent entry = arg0;
+ if (entry.getThrowableStrRep() == null){
+ s = "";
+ } else {
+ s = entry.getThrowableStrRep()[0]; //This needs fixing...
+ }
+ LogObject event = new LogObject("<<<MESSAGE>>> " + s, "MESSAGE" + eq + entry.getMessage(), this.authkey, this.logtype_id, this.agent_id);
+
+ if (entry.getLevel() == Level.DEBUG) {
+ level = debug;
+ }else if (entry.getLevel() == Level.INFO){
+ level = info;
+ }else if (entry.getLevel() == Level.WARN){
+ level = warn;
+ }else if (entry.getLevel() == Level.ERROR){
+ level = error;
+ }else if (entry.getLevel() == Level.FATAL){
+ level = fatal;
+ }else{
+ level = "6";
+ }
+ event.setLoglevel_id(level);
+ event.setEtime(Long.toString(entry.getTimeStamp()/1000));
+
+ String data = null;
+ try {
+ data = Util.getSendableString(event);
+ } catch (UnsupportedEncodingException e) {
+ e.printStackTrace();
+ } catch (NoSuchAlgorithmException e) {
+ e.printStackTrace();
+ }
+ System.out.println(data);
+ try {
+ sendData(data);
+ } catch (UnknownHostException e) {
+ e.printStackTrace();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+
+ }
+
+ public void sendData(String data) throws UnknownHostException, IOException {
+ Socket sock = new Socket();
+ sock.bind(null);
+ try {
+ sock.connect(new InetSocketAddress(serverhost, serverport), timeout);
+ PrintWriter out = new PrintWriter(sock.getOutputStream(), true);
+ out.println(data);
+ sock.close();
+ } catch (SocketTimeoutException e) {
+ System.out.println("Socket Connection Timedout");
+ }
+ }
+
+ public void close() {
+ // TODO Auto-generated method stub
+
+ }
+
+
+ public boolean requiresLayout() {
+ return false;
+ }
+
+
+ public String getServerhost() {
+ return serverhost;
+ }
+
+ public void setServerhost(String serverhost) {
+ this.serverhost = serverhost;
+ }
+
+ public int getServerport() {
+ return serverport;
+ }
+
+ public void setServerport(int serverport) {
+ this.serverport = serverport;
+ }
+
+ public String getAgent_id() {
+ return agent_id;
+ }
+
+ public void setAgent_id(String agent_id) {
+ this.agent_id = agent_id;
+ }
+
+ public String getLogtype_id() {
+ return logtype_id;
+ }
+
+ public void setLogtype_id(String logtype_id) {
+ this.logtype_id = logtype_id;
+ }
+
+ public String getAuthkey() {
+ return authkey;
+ }
+
+ public void setAuthkey(String authkey) {
+ this.authkey = authkey;
+ }
+
+ public int getTimeout() {
+ return timeout;
+ }
+
+ public void setTimeout(int timeout) {
+ this.timeout = timeout;
+ }
+
+}
diff --git a/src/plugins/log4j/src/main/java/org/cistern/log4j/appender/Util.java b/src/plugins/log4j/src/main/java/org/cistern/log4j/appender/Util.java
new file mode 100644
index 0000000..c0c1cff
--- /dev/null
+++ b/src/plugins/log4j/src/main/java/org/cistern/log4j/appender/Util.java
@@ -0,0 +1,45 @@
+package org.cistern.log4j.appender;
+
+import java.io.UnsupportedEncodingException;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import org.cistern.log4j.appender.TCPAppender;
+
+public class Util {
+
+ //Setup delimiters
+ static String vb = "__1_VV";
+ static String bb = "__1_BB";
+ static String check = "__1_CC";
+ static String end = "__1_EE";
+ static String eq = "/000/";
+ static String newval = "/111/";
+
+ protected static String getSendableString(LogObject obj) throws UnsupportedEncodingException, NoSuchAlgorithmException {
+ String data = "authkey" + vb + obj.getAuthkey() + bb + "agent_id" + vb + obj.getAgent_id() + bb + "logtype_id" + vb + obj.getLogtype_id() + bb + "loglevel_id" + vb + obj.getLoglevel_id() + bb + "etime" + vb + obj.getEtime() + bb + "data" + vb + obj.getData() + bb + "payload" + vb + obj.payload + bb;
+ MessageDigest md;
+ md = MessageDigest.getInstance("MD5");
+ byte[] md5hash = new byte[32];
+ md.update(data.getBytes("UTF-8"), 0, data.length());
+ md5hash = md.digest();
+ String withchecksum = data + check + convertToHex(md5hash) + end;
+ return withchecksum;
+ }
+
+ private static String convertToHex(byte[] data) {
+ StringBuffer buf = new StringBuffer();
+ for (int i = 0; i < data.length; i++) {
+ int halfbyte = (data[i] >>> 4) & 0x0F;
+ int two_halfs = 0;
+ do {
+ if ((0 <= halfbyte) && (halfbyte <= 9))
+ buf.append((char) ('0' + halfbyte));
+ else
+ buf.append((char) ('a' + (halfbyte - 10)));
+ halfbyte = data[i] & 0x0F;
+ } while(two_halfs++ < 1);
+ }
+ return buf.toString();
+ }
+
+}
diff --git a/src/plugins/log4j/src/main/resources/log4j.properties b/src/plugins/log4j/src/main/resources/log4j.properties
new file mode 100644
index 0000000..a28e32f
--- /dev/null
+++ b/src/plugins/log4j/src/main/resources/log4j.properties
@@ -0,0 +1,17 @@
+log4j.rootLogger=DEBUG, FILE, CONSOLE, REMOTE
+log4j.appender.FILE=org.apache.log4j.FileAppender
+log4j.appender.FILE.file=/tmp/logs/log.txt
+log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
+log4j.appender.FILE.layout.ConversionPattern=[%d{MMM dd HH:mm:ss}] %-5p (%F:%L) - %m%n
+log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
+log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
+log4j.appender.CONSOLE.layout.ConversionPattern=[%d{MMM dd HH:mm:ss}] %-5p (%F:%L) - %m%n
+log4j.appender.REMOTE=org.cistern.log4j.appender.TCPAppender
+log4j.appender.REMOTE.serverhost=127.0.0.1
+log4j.appender.REMOTE.serverport=9845
+log4j.appender.REMOTE.agent_id=1
+log4j.appender.REMOTE.logtype_id=1
+log4j.appender.REMOTE.authkey=7952d3072b86a949e45232fe42ad03bc
+log4j.appender.REMOTE.timeout=100
+
+
diff --git a/src/plugins/log4j/src/test/java/com/yahoo/groups/log4j/cistern/AppTest.java b/src/plugins/log4j/src/test/java/com/yahoo/groups/log4j/cistern/AppTest.java
new file mode 100644
index 0000000..e63cdf0
--- /dev/null
+++ b/src/plugins/log4j/src/test/java/com/yahoo/groups/log4j/cistern/AppTest.java
@@ -0,0 +1,38 @@
+package com.yahoo.groups.log4j.cistern;
+
+import junit.framework.Test;
+import junit.framework.TestCase;
+import junit.framework.TestSuite;
+
+/**
+ * Unit test for simple App.
+ */
+public class AppTest
+ extends TestCase
+{
+ /**
+ * Create the test case
+ *
+ * @param testName name of the test case
+ */
+ public AppTest( String testName )
+ {
+ super( testName );
+ }
+
+ /**
+ * @return the suite of tests being tested
+ */
+ public static Test suite()
+ {
+ return new TestSuite( AppTest.class );
+ }
+
+ /**
+ * Rigourous Test :-)
+ */
+ public void testApp()
+ {
+ assertTrue( true );
+ }
+}
diff --git a/src/server/lib/modules/collection_server.rb b/src/server/lib/modules/collection_server.rb
index 246b018..50d2774 100644
--- a/src/server/lib/modules/collection_server.rb
+++ b/src/server/lib/modules/collection_server.rb
@@ -1,85 +1,86 @@
module CollectionServer
#TODO: Checksum check should be wrapped in to an exception and then and handled that way in receive_data
#Set buffer delimiters
@@break = '__1_BB'
@@value = '__1_VV'
@@finish = '__1_EE'
def check_key(agent, key)
if agent.authkey != key
return false
else
return true
end
end
#Write a log entry
def log_entry(line)
raw = line.split(@@break)
map = Hash.new
raw.each do |keys|
parts = keys.split(@@value)
map.store(parts[0],parts[1])
end
- unless USEMEMCACHE != true
- if Staticentry.get_cache(Digest::MD5.hexdigest(map['data'] + map['logtype_id'].to_s)).nil?
- static = Logtype.find(map['logtype_id']).staticentries.new
- static.data = map['data']
- static.save
- end
- else
+ #unless USEMEMCACHE != true
+ # if Staticentry.get_cache(Digest::MD5.hexdigest(map['data'] + map['logtype_id'].to_s)).nil?
+ # static = Logtype.find(map['logtype_id']).staticentries.new
+ # static.data = map['data']
+ # static.save
+ # end
+ #else
static = Logtype.find(map['logtype_id']).staticentries.new
static.data = map['data']
static.save
- end
+ #end
unless USEMEMCACHE != true
static = Staticentry.get_cache(Digest::MD5.hexdigest(map['data'] + map['logtype_id'].to_s))
else
static = Staticentry.find(Digest::MD5.hexdigest(map['data'] + map['logtype_id'].to_s))
end
event = static.events.new
event.etime = map['etime']
event.loglevel_id = map['loglevel_id']
event.payload = map['payload']
event.logtype_id = map['logtype_id']
event.agent_id = map['agent_id']
if check_key(Agent.find(map['agent_id']), map['authkey'])
event.save
else
ActiveRecord::Base.logger.debug "Event dropped -- invalid agent authkey sent"
end
port, ip = Socket.unpack_sockaddr_in(get_peername)
host = Socket.getaddrinfo(ip, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME)[0][2]
ActiveRecord::Base.logger.debug "New event logged from #{host} \n -- Log data: #{line}"
end
#Do this when a connection is initialized
def post_init
port, ip = Socket.unpack_sockaddr_in(get_peername)
host = Socket.getaddrinfo(ip, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME)[0][2]
ActiveRecord::Base.logger.info "-- Collector connection established from #{host}"
end
#Do this when data is received
def receive_data(data)
(@buffer ||= BufferedTokenizer.new(delimiter = "__1_EE")).extract(data).each do |line|
if line.valid?
+ puts line
log_entry(line)
else
port, ip = Socket.unpack_sockaddr_in(get_peername)
host = Socket.getaddrinfo(ip, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME)[0][2]
ActiveRecord::Base.logger.error "Dropped log entry from #{host} - checksum invalid"
end
end
end
#Do this when a connection is closed by a peer
def unbind
ActiveRecord::Base.logger.info "-- Collector connection closed by a peer"
end
end
\ No newline at end of file
|
parabuzzle/cistern
|
250056dee3066c0bc307cbbf48b1a52c330fd02c
|
added pre block to command output on the frontend to preserve spacing provided by the agent
|
diff --git a/src/server/app/views/agents/commands.rhtml b/src/server/app/views/agents/commands.rhtml
index 728cf70..bcc7cf5 100644
--- a/src/server/app/views/agents/commands.rhtml
+++ b/src/server/app/views/agents/commands.rhtml
@@ -1,20 +1,21 @@
<% if @commands == false or @output == false%>
<h1>Agent is not listening</h1>
<div class="info">The server had trouble connecting to the agent. Please verify that the agent is listening on the port set in the agent settings</div>
<%else%>
<%if params[:command].nil?%>
<h1>Available Commands for <%=@agent.name%></h1>
<ul>
<% for command in @commands do%>
<li><%=link_to(command, :command => command, :action => 'commands')%></li>
<%end%>
</ul>
<%else%>
<h1>Output of Command <%=params[:command]%></h1>
<div class="info"><%=link_to("Back to Commands", :action => 'commands')%>
- <div id="commandout">
+ <div id="commandout"><pre>
<%= sanitize @output.gsub('\n', '<br/>'), :tags => %w(br)%>
+ </pre>
</div>
<%end%>
<%end%>
\ No newline at end of file
|
parabuzzle/cistern
|
4d6813073169b01b56a149a5249437973b0700e9
|
Fixed command output escaping and some agent junk
|
diff --git a/src/agent/commands.rb b/src/agent/commands.rb
index 05a1e76..2691f67 100644
--- a/src/agent/commands.rb
+++ b/src/agent/commands.rb
@@ -1,15 +1,18 @@
module AgentCommands
def ps_auxx
return `ps auxx`
end
+ def top
+ return `top -l 1`
+ end
def get_users
return `w`
end
def say_foo
return "foo!"
end
-end
\ No newline at end of file
+end
diff --git a/src/agent/config.yml b/src/agent/config.yml
index 80a7aad..bd821d6 100644
--- a/src/agent/config.yml
+++ b/src/agent/config.yml
@@ -1,22 +1,22 @@
server:
hostname: 127.0.0.1
connection: tcp
port: 9845
agent:
listenport: 9846
bindip: 0.0.0.0
agent_id: 1
- key: 14f65b5c37d30db7db5b1298dc85acd3
+ key: 7952d3072b86a949e45232fe42ad03bc
logtypes:
syslog:
modelfile: syslog.rb
modelname: SysLogModel
logtype_id: 1
logfile: /var/log/system.log
authlog:
modelfile: syslog.rb
modelname: SysLogModel
logtype_id: 2
- logfile: /var/log/secure.log
\ No newline at end of file
+ logfile: /var/log/secure.log
diff --git a/src/agent/lib/modules.rb b/src/agent/lib/modules.rb
index 4048595..04268d3 100644
--- a/src/agent/lib/modules.rb
+++ b/src/agent/lib/modules.rb
@@ -1,80 +1,80 @@
module CommandServer
def check_sig(serverkey, payload)
- if serverkey != Digest::MD5.hexdigest("14f65b5c37d30db7db5b1298dc85acd3" + payload)
+ if serverkey != Digest::MD5.hexdigest(CONFIG['agent']['key'] + payload)
return false
else
return true
end
return true
end
def command_list
c = String.new
AgentCommands.instance_methods.each do |command|
c = c + command + "/000/"
end
return c
end
def get_command(data)
#return data from cammand
begin
d = eval data
return d
rescue NameError
return "not a valid command"
end
end
def get_result(data)
if data == "ls"
return command_list
else
return get_command(data)
end
end
def post_init
puts "connection opened"
#Log that the server connected
end
def receive_data data
puts data
(@buffer ||= BufferedTokenizer.new(delimiter = "__1_EE")).extract(data).each do |line|
if line.valid?
line = line.split('__1_CC')[0]
parts = line.split('__1_BB')
map = Hash.new
parts.each do |part|
p = part.split('__1_VV')
map.store(p[0], p[1])
end
if check_sig(map['authkey'], map['payload'])
puts map['payload']
send_data get_result(map['payload'])
else
#log signature is bad
send_data "signature is bad - punted"
end
else
#log checksum invalid
send_data "checksum is bad - punted"
end
end
end
def unbind
#Log that the server disconnected
puts "peer disconnected"
end
end
class String
def valid?
part = self.split('__1_CC')
#return true
return Digest::MD5.hexdigest(part[0]) == part[1]
end
end
\ No newline at end of file
diff --git a/src/server/app/views/agents/commands.rhtml b/src/server/app/views/agents/commands.rhtml
index f023ee0..728cf70 100644
--- a/src/server/app/views/agents/commands.rhtml
+++ b/src/server/app/views/agents/commands.rhtml
@@ -1,20 +1,20 @@
<% if @commands == false or @output == false%>
<h1>Agent is not listening</h1>
<div class="info">The server had trouble connecting to the agent. Please verify that the agent is listening on the port set in the agent settings</div>
<%else%>
<%if params[:command].nil?%>
<h1>Available Commands for <%=@agent.name%></h1>
<ul>
<% for command in @commands do%>
<li><%=link_to(command, :command => command, :action => 'commands')%></li>
<%end%>
</ul>
<%else%>
<h1>Output of Command <%=params[:command]%></h1>
<div class="info"><%=link_to("Back to Commands", :action => 'commands')%>
<div id="commandout">
- <%= @output.gsub('\n', '<br/>')%>
+ <%= sanitize @output.gsub('\n', '<br/>'), :tags => %w(br)%>
</div>
<%end%>
<%end%>
\ No newline at end of file
diff --git a/src/server/app/views/agents/edit.rhtml b/src/server/app/views/agents/edit.rhtml
index d536f15..0825a5a 100644
--- a/src/server/app/views/agents/edit.rhtml
+++ b/src/server/app/views/agents/edit.rhtml
@@ -1,34 +1,34 @@
-<h1>Edit <%=@agent.name%></h1>
+<h1>Edit <%=h @agent.name%></h1>
<%= error_messages_for 'agent' %>
<div id="form">
<table width="100%">
<% form_for :agent do |f|%>
<tr>
<td>Name:</td>
<td align="right"><%= f.text_field :name, :class => "fbox"%></td>
</tr>
<tr>
<td>Hostname:</td>
<td align="right"><%= f.text_field :hostname, :class => "fbox"%></td>
</tr>
<tr>
<td>Port:</td>
<td align="right"><%= f.text_field :port, :class => "fbox"%></td>
</tr>
<tr>
<td>Key:</td>
<td align="right"><%= f.text_field :authkey, :class => "fbox"%></td>
</tr>
</table>
<div class="adendem">note: changing the key is not recommended.</div>
<div class="agent">Logtypes</div>
<% for log in Logtype.find(:all) %>
<div class="agents">
<%= check_box_tag "agent[logtype_ids][]", log.id, @agent.logtypes.include?(log) %> <%= log.name %>
</div>
<%end%>
<div class="agent"><%= submit_tag "Update Agent", :class => "submitbutton" %></div>
<%end%>
</div>
\ No newline at end of file
|
parabuzzle/cistern
|
1ea8a4d8150f2964203700cff817bebc80a2ffca
|
added timeout on agent listener test if a firewall drops the packet
|
diff --git a/src/server/app/helpers/agents_helper.rb b/src/server/app/helpers/agents_helper.rb
index db8964e..30d399c 100644
--- a/src/server/app/helpers/agents_helper.rb
+++ b/src/server/app/helpers/agents_helper.rb
@@ -1,68 +1,74 @@
include Socket::Constants
module AgentsHelper
def get_commands(agent)
begin
socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
sockaddr = Socket.pack_sockaddr_in( agent.port, agent.hostname )
socket.connect( sockaddr )
h = Hash.new
e = String.new
payload = 'ls'
authkey = Digest::MD5.hexdigest(agent.authkey + payload)
h.store("authkey", authkey)
h.store("payload", payload)
h.each do |key, val|
e = e + key.to_s + "__1_VV" + val.to_s + "__1_BB"
end
e = e + "__1_CC" + Digest::MD5.hexdigest(e) + "__1_EE"
socket.write(e)
r = socket.recvfrom(1045504)[0].chomp
socket.close
return break_commands(r)
rescue Errno::ECONNREFUSED
return false
end
end
def get_command(agent, command)
begin
socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
sockaddr = Socket.pack_sockaddr_in( agent.port, agent.hostname )
socket.connect( sockaddr )
h = Hash.new
e = String.new
payload = command
authkey = Digest::MD5.hexdigest(agent.authkey + payload)
h.store("authkey", authkey)
h.store("payload", payload)
h.each do |key, val|
e = e + key.to_s + "__1_VV" + val.to_s + "__1_BB"
end
e = e + "__1_CC" + Digest::MD5.hexdigest(e) + "__1_EE"
socket.write(e)
r = socket.recvfrom(1045504)[0].chomp
socket.close
return r.gsub("\n", "<br/>")
rescue Errno::ECONNREFUSED
return false
end
end
def break_commands(r)
a = r.split('/000/')
return a
end
def is_agent_online?(ip, port)
begin
- socket = TCPSocket.new(ip, port)
- rescue Errno::ECONNREFUSED
- return false
+ Timeout::timeout(1) do
+ begin
+ s = TCPSocket.new(ip, port)
+ s.close
+ return true
+ rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH
+ return false
+ end
+ end
+ rescue Timeout::Error
end
- socket.close
- return true
+ return false
end
end
|
parabuzzle/cistern
|
7bc1f89de15b3e699e96522da21fc8e1dc17d389
|
Added check for agent listener
|
diff --git a/src/server/app/helpers/agents_helper.rb b/src/server/app/helpers/agents_helper.rb
index ae47c9f..db8964e 100644
--- a/src/server/app/helpers/agents_helper.rb
+++ b/src/server/app/helpers/agents_helper.rb
@@ -1,57 +1,68 @@
include Socket::Constants
module AgentsHelper
def get_commands(agent)
begin
socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
sockaddr = Socket.pack_sockaddr_in( agent.port, agent.hostname )
socket.connect( sockaddr )
h = Hash.new
e = String.new
payload = 'ls'
authkey = Digest::MD5.hexdigest(agent.authkey + payload)
h.store("authkey", authkey)
h.store("payload", payload)
h.each do |key, val|
e = e + key.to_s + "__1_VV" + val.to_s + "__1_BB"
end
e = e + "__1_CC" + Digest::MD5.hexdigest(e) + "__1_EE"
socket.write(e)
r = socket.recvfrom(1045504)[0].chomp
socket.close
return break_commands(r)
rescue Errno::ECONNREFUSED
return false
end
end
def get_command(agent, command)
begin
socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
sockaddr = Socket.pack_sockaddr_in( agent.port, agent.hostname )
socket.connect( sockaddr )
h = Hash.new
e = String.new
payload = command
authkey = Digest::MD5.hexdigest(agent.authkey + payload)
h.store("authkey", authkey)
h.store("payload", payload)
h.each do |key, val|
e = e + key.to_s + "__1_VV" + val.to_s + "__1_BB"
end
e = e + "__1_CC" + Digest::MD5.hexdigest(e) + "__1_EE"
socket.write(e)
r = socket.recvfrom(1045504)[0].chomp
socket.close
return r.gsub("\n", "<br/>")
rescue Errno::ECONNREFUSED
return false
end
end
def break_commands(r)
a = r.split('/000/')
return a
end
+ def is_agent_online?(ip, port)
+ begin
+ socket = TCPSocket.new(ip, port)
+ rescue Errno::ECONNREFUSED
+ return false
+ end
+ socket.close
+ return true
+ end
+
+
end
diff --git a/src/server/app/views/agents/index.rhtml b/src/server/app/views/agents/index.rhtml
index 9d9e655..d0763b0 100644
--- a/src/server/app/views/agents/index.rhtml
+++ b/src/server/app/views/agents/index.rhtml
@@ -1,31 +1,33 @@
<h1>Agents</h1>
<div class="subnav"><%=link_to("Create new Agent #{image_tag("addserver.png", :alt => "add server", :border => "0px")}", :action => "new")%></div>
<div class="clear"></div>
<% for agent in @agents do%>
+<%online = is_agent_online?(agent.hostname, agent.port)%>
<div class="agent">
- <%=image_tag("serverup.png")%><a href='#' onclick="$('.agentinfo<%=agent.id%>').toggle();return false"><%= h agent.name%></a> : <%=link_to("View Events", :action=>"show", :id=>agent.id)%>
+ <%=if online then image_tag("serverup.png", :alt => "agent is up") else image_tag("serverdown.png", :alt => "agent listener down")end%><a href='#' onclick="$('.agentinfo<%=agent.id%>').toggle();return false"><%= h agent.name%></a> : <%=link_to("View Events", :action=>"show", :id=>agent.id)%>
+ <%= if !online then "(agent listener is offline)" end%>
<div class="agentinfo<%=agent.id%>" style="display:none; margin-left:30px; background:#FF9; padding: 3px; border: 1px solid #000">
<div class="subnav" style="width:200px;">
Logtypes
<% for logtype in agent.logtypes do%>
<div class="adendem"><%=h logtype.name%></div>
<%end%>
</div>
<div clear></div>
<div class="info">Total Events: <%= agent.events.count %></div>
<div class="info">Hostname: <%=h agent.hostname%></div>
<div class="info">Listenport: <%=h agent.port%></div>
<div class="info">Key: <%=h agent.authkey%></div>
<div class="info">Agent_id: <%=agent.id%></div>
- <div class="info"><%=link_to("View Commands for Host", :action => "commands", :id => agent.id)%></div>
+ <div class="info"><%=if online then link_to("View Commands for Host", :action => "commands", :id => agent.id) else "Agent listener is offline" end%></div>
<div class="info"><%=link_to("edit", :action => "edit", :id => agent.id)%></div>
</div>
</div>
<%end%>
<div class="pagination">
<%= will_paginate @event %>
</div>
\ No newline at end of file
|
parabuzzle/cistern
|
637eaba7aaf8e466407629fbd8055a323742ed33
|
pulled out puts of command response. TODO: add try/catch blocks and logger for agent
|
diff --git a/src/agent/lib/modules.rb b/src/agent/lib/modules.rb
index b7b3bcd..4048595 100644
--- a/src/agent/lib/modules.rb
+++ b/src/agent/lib/modules.rb
@@ -1,81 +1,80 @@
module CommandServer
def check_sig(serverkey, payload)
if serverkey != Digest::MD5.hexdigest("14f65b5c37d30db7db5b1298dc85acd3" + payload)
return false
else
return true
end
return true
end
def command_list
c = String.new
AgentCommands.instance_methods.each do |command|
c = c + command + "/000/"
end
return c
end
def get_command(data)
#return data from cammand
begin
d = eval data
return d
rescue NameError
return "not a valid command"
end
end
def get_result(data)
if data == "ls"
return command_list
else
return get_command(data)
end
end
def post_init
puts "connection opened"
#Log that the server connected
end
def receive_data data
puts data
(@buffer ||= BufferedTokenizer.new(delimiter = "__1_EE")).extract(data).each do |line|
if line.valid?
line = line.split('__1_CC')[0]
parts = line.split('__1_BB')
map = Hash.new
parts.each do |part|
p = part.split('__1_VV')
map.store(p[0], p[1])
end
if check_sig(map['authkey'], map['payload'])
puts map['payload']
send_data get_result(map['payload'])
- puts get_result(map['payload'])
else
#log signature is bad
send_data "signature is bad - punted"
end
else
#log checksum invalid
send_data "checksum is bad - punted"
end
end
end
def unbind
#Log that the server disconnected
puts "peer disconnected"
end
end
class String
def valid?
part = self.split('__1_CC')
#return true
return Digest::MD5.hexdigest(part[0]) == part[1]
end
end
\ No newline at end of file
|
parabuzzle/cistern
|
d75694c360b0a74b0a5c471b47e5de5fbb44330e
|
made the agent work with model files
|
diff --git a/src/agent/agent.rb b/src/agent/agent.rb
index 4232e34..6849603 100644
--- a/src/agent/agent.rb
+++ b/src/agent/agent.rb
@@ -1,26 +1,55 @@
require 'rubygems'
require 'eventmachine'
require 'lib/modules.rb'
require 'socket'
require 'file/tail'
require 'yaml'
require 'digest/md5'
-require 'lib/commands.rb'
+require 'commands.rb'
+require 'lib/sender_base.rb'
+include LogHelper
include AgentCommands
include File::Tail
include Socket::Constants
+CONFIG = YAML::load(File.open("config.yml"))
-port = 9846
-bindip = '127.0.0.1'
+port = CONFIG['agent']['listenport']
+bindip = CONFIG['agent']['bindip']
+authkey = CONFIG['agent']['key']
+agent_id = CONFIG['agent']['agent_id']
+serverhost = CONFIG['server']['hostname']
+serverport = CONFIG['server']['port']
+
+@socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
+sockaddr = Socket.pack_sockaddr_in( serverport, serverhost )
+@socket.connect( sockaddr )
+
+
+
+CONFIG['logtypes'].each do |l,logtype|
+ x = Thread.new {
+ require 'logmodels/' + logtype['modelfile']
+ include eval(logtype['modelname'])
+
+ File.open(logtype['logfile']) do |log|
+ log.extend(File::Tail)
+ log.interval = 1
+ log.backward(0)
+ puts "tailing #{logtype['logfile']} with logmodel #{logtype['modelname']}"
+ log.tail { |line| send_event(line, @socket, authkey, logtype['logtype_id'], agent_id) }
+ end
+ }
+end
+
Signal.trap("TERM") do
EventMachine::stop_event_loop
end
EventMachine::run {
EventMachine::start_server bindip, port, CommandServer
}
diff --git a/src/agent/lib/commands.rb b/src/agent/commands.rb
similarity index 100%
rename from src/agent/lib/commands.rb
rename to src/agent/commands.rb
diff --git a/src/agent/config.yml b/src/agent/config.yml
new file mode 100644
index 0000000..80a7aad
--- /dev/null
+++ b/src/agent/config.yml
@@ -0,0 +1,22 @@
+server:
+ hostname: 127.0.0.1
+ connection: tcp
+ port: 9845
+
+agent:
+ listenport: 9846
+ bindip: 0.0.0.0
+ agent_id: 1
+ key: 14f65b5c37d30db7db5b1298dc85acd3
+
+logtypes:
+ syslog:
+ modelfile: syslog.rb
+ modelname: SysLogModel
+ logtype_id: 1
+ logfile: /var/log/system.log
+ authlog:
+ modelfile: syslog.rb
+ modelname: SysLogModel
+ logtype_id: 2
+ logfile: /var/log/secure.log
\ No newline at end of file
diff --git a/src/agent/lib/sender_base.rb b/src/agent/lib/sender_base.rb
new file mode 100644
index 0000000..be6b535
--- /dev/null
+++ b/src/agent/lib/sender_base.rb
@@ -0,0 +1,20 @@
+module LogHelper
+ def send_event(entry, socket, authkey, logtype_id, agent_id)
+ event = Hash.new
+ e = String.new
+ entry = entry.chomp
+ puts entry
+ event.store("authkey", authkey)
+ event.store("logtype_id", logtype_id)
+ event.store("agent_id", agent_id)
+ event.store("loglevel_id", get_loglevel_id(entry))
+ event.store("etime", get_time(entry))
+ event.store("data", get_static(entry))
+ event.store("payload", get_payload(entry))
+ event.each do |key, val|
+ e = e + key.to_s + '__1_VV' + val.to_s + '__1_BB'
+ end
+ e = e + '__1_CC' + Digest::MD5.hexdigest(e) + '__1_EE'
+ socket.write(e)
+ end
+end
diff --git a/src/agent/logmodels/syslog.rb b/src/agent/logmodels/syslog.rb
new file mode 100644
index 0000000..bd1ade3
--- /dev/null
+++ b/src/agent/logmodels/syslog.rb
@@ -0,0 +1,29 @@
+module SysLogModel
+
+ def get_payload(string)
+ payload = 'EVENT/000/' + string.gsub(string[0,16], '')
+ puts payload
+ return payload
+ end
+
+ def get_static(string)
+ static = "<<<EVENT>>>"
+ return static
+ end
+
+ def get_time(string)
+ d = string[0,16].split(' ')
+ m = d[2].split(':')
+ etime = Time.local(Time.now.year,d[0],d[1],m[0],m[1],m[2]).to_i
+ return etime
+ end
+
+ def get_loglevel_id(string)
+ if string.match(/(fail|error)/i)
+ return 2
+ else
+ return 4
+ end
+ end
+
+end
\ No newline at end of file
|
parabuzzle/cistern
|
419bd9bdef0617d1371d1bac1b62e5e540cd0cec
|
Fixed new lines in log entries in views
|
diff --git a/src/agent/lib/commands.rb b/src/agent/lib/commands.rb
index 088581e..05a1e76 100644
--- a/src/agent/lib/commands.rb
+++ b/src/agent/lib/commands.rb
@@ -1,11 +1,15 @@
module AgentCommands
def ps_auxx
return `ps auxx`
end
def get_users
return `w`
end
+ def say_foo
+ return "foo!"
+ end
+
end
\ No newline at end of file
diff --git a/src/agent/lib/modules.rb b/src/agent/lib/modules.rb
index adb497a..b7b3bcd 100644
--- a/src/agent/lib/modules.rb
+++ b/src/agent/lib/modules.rb
@@ -1,81 +1,81 @@
module CommandServer
def check_sig(serverkey, payload)
- if serverkey != Digest::MD5.hexdigest("7952d3072b86a949e45232fe42ad03bc" + payload)
+ if serverkey != Digest::MD5.hexdigest("14f65b5c37d30db7db5b1298dc85acd3" + payload)
return false
else
return true
end
return true
end
def command_list
c = String.new
AgentCommands.instance_methods.each do |command|
c = c + command + "/000/"
end
return c
end
def get_command(data)
#return data from cammand
begin
d = eval data
return d
rescue NameError
return "not a valid command"
end
end
def get_result(data)
if data == "ls"
return command_list
else
return get_command(data)
end
end
def post_init
puts "connection opened"
#Log that the server connected
end
def receive_data data
puts data
(@buffer ||= BufferedTokenizer.new(delimiter = "__1_EE")).extract(data).each do |line|
if line.valid?
line = line.split('__1_CC')[0]
parts = line.split('__1_BB')
map = Hash.new
parts.each do |part|
p = part.split('__1_VV')
map.store(p[0], p[1])
end
if check_sig(map['authkey'], map['payload'])
puts map['payload']
send_data get_result(map['payload'])
puts get_result(map['payload'])
else
#log signature is bad
- puts "signature is bad - punted"
+ send_data "signature is bad - punted"
end
else
#log checksum invalid
- puts "checksum is bad - punted"
+ send_data "checksum is bad - punted"
end
end
end
def unbind
#Log that the server disconnected
puts "peer disconnected"
end
end
class String
def valid?
part = self.split('__1_CC')
#return true
return Digest::MD5.hexdigest(part[0]) == part[1]
end
end
\ No newline at end of file
diff --git a/src/server/app/helpers/agents_helper.rb b/src/server/app/helpers/agents_helper.rb
index 62ee30b..ae47c9f 100644
--- a/src/server/app/helpers/agents_helper.rb
+++ b/src/server/app/helpers/agents_helper.rb
@@ -1,51 +1,57 @@
include Socket::Constants
module AgentsHelper
def get_commands(agent)
- socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
- sockaddr = Socket.pack_sockaddr_in( agent.port, agent.hostname )
- socket.connect( sockaddr )
- h = Hash.new
- e = String.new
- payload = 'ls'
- authkey = Digest::MD5.hexdigest(agent.authkey + payload)
- h.store("authkey", authkey)
- h.store("payload", payload)
- h.each do |key, val|
- e = e + key.to_s + "__1_VV" + val.to_s + "__1_BB"
+ begin
+ socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
+ sockaddr = Socket.pack_sockaddr_in( agent.port, agent.hostname )
+ socket.connect( sockaddr )
+ h = Hash.new
+ e = String.new
+ payload = 'ls'
+ authkey = Digest::MD5.hexdigest(agent.authkey + payload)
+ h.store("authkey", authkey)
+ h.store("payload", payload)
+ h.each do |key, val|
+ e = e + key.to_s + "__1_VV" + val.to_s + "__1_BB"
+ end
+ e = e + "__1_CC" + Digest::MD5.hexdigest(e) + "__1_EE"
+ socket.write(e)
+ r = socket.recvfrom(1045504)[0].chomp
+ socket.close
+ return break_commands(r)
+ rescue Errno::ECONNREFUSED
+ return false
end
- e = e + "__1_CC" + Digest::MD5.hexdigest(e) + "__1_EE"
-
- socket.write(e)
- r = socket.recvfrom(1045504)[0].chomp
- socket.close
- return break_commands(r)
end
def get_command(agent, command)
- socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
- sockaddr = Socket.pack_sockaddr_in( agent.port, agent.hostname )
- socket.connect( sockaddr )
- h = Hash.new
- e = String.new
- payload = command
- authkey = Digest::MD5.hexdigest(agent.authkey + payload)
- h.store("authkey", authkey)
- h.store("payload", payload)
- h.each do |key, val|
- e = e + key.to_s + "__1_VV" + val.to_s + "__1_BB"
+ begin
+ socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
+ sockaddr = Socket.pack_sockaddr_in( agent.port, agent.hostname )
+ socket.connect( sockaddr )
+ h = Hash.new
+ e = String.new
+ payload = command
+ authkey = Digest::MD5.hexdigest(agent.authkey + payload)
+ h.store("authkey", authkey)
+ h.store("payload", payload)
+ h.each do |key, val|
+ e = e + key.to_s + "__1_VV" + val.to_s + "__1_BB"
+ end
+ e = e + "__1_CC" + Digest::MD5.hexdigest(e) + "__1_EE"
+ socket.write(e)
+ r = socket.recvfrom(1045504)[0].chomp
+ socket.close
+ return r.gsub("\n", "<br/>")
+ rescue Errno::ECONNREFUSED
+ return false
end
- e = e + "__1_CC" + Digest::MD5.hexdigest(e) + "__1_EE"
-
- socket.write(e)
- r = socket.recvfrom(1045504)[0].chomp
- socket.close
- return r.gsub("\n", "<br/>")
end
def break_commands(r)
a = r.split('/000/')
return a
end
end
diff --git a/src/server/app/helpers/application_helper.rb b/src/server/app/helpers/application_helper.rb
index add149c..51e2a0d 100644
--- a/src/server/app/helpers/application_helper.rb
+++ b/src/server/app/helpers/application_helper.rb
@@ -1,63 +1,64 @@
# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
#Return events array with payload field populated with full event
def rebuildevents(events)
@events = Array.new
events.each do |e|
e.payload = rebuildevent(e)
@events << e
end
return @events
end
#Return a string of replaced static entry keys based on event's payload
def rebuildevent(e)
if USEMEMCACHE != true
static = Staticentry.find(e.staticentry.id)
else
static = Staticentry.get_cache(e.staticentry.id)
end
entries = e.payload.split('/111/')
hash = Hash.new
entries.each do |m|
map = m.split('/000/')
hash.store('<<<' + map[0] + '>>>',map[1])
end
p = static.data
hash.each do |key, val|
p = p.gsub(key,val)
+ p = p.gsub("\n", "<br/>")
end
return p
end
def filter_agent(results,agent_id)
r = Array.new
results.each do |result|
if result.agent_id == agent_id
r << result
end
end
return r
end
def filter_logtype(results,logtype_id)
r = Array.new
results.each do |result|
if result.logtype_id == logtype_id
r << result
end
end
return r
end
def filter_loglevel(results,loglevel_id)
r = Array.new
results.each do |result|
if result.loglevel_id <= loglevel_id
r << result
end
end
return r
end
end
diff --git a/src/server/app/views/agents/commands.rhtml b/src/server/app/views/agents/commands.rhtml
index 4041c57..f023ee0 100644
--- a/src/server/app/views/agents/commands.rhtml
+++ b/src/server/app/views/agents/commands.rhtml
@@ -1,14 +1,20 @@
-<%if params[:command].nil?%>
-<h1>Available Commands for <%=@agent.name%></h1>
-<ul>
-<% for command in @commands do%>
- <li><%=link_to(command, :command => command, :action => 'commands')%></li>
-<%end%>
-</ul>
+<% if @commands == false or @output == false%>
+<h1>Agent is not listening</h1>
+<div class="info">The server had trouble connecting to the agent. Please verify that the agent is listening on the port set in the agent settings</div>
<%else%>
-<h1>Output of Command <%=params[:command]%></h1>
-<div class="info"><%=link_to("Back to Commands", :action => 'commands')%>
-<div id="commandout">
-<%= @output.gsub('\n', '<br/>')%>
-</div>
+
+ <%if params[:command].nil?%>
+ <h1>Available Commands for <%=@agent.name%></h1>
+ <ul>
+ <% for command in @commands do%>
+ <li><%=link_to(command, :command => command, :action => 'commands')%></li>
+ <%end%>
+ </ul>
+ <%else%>
+ <h1>Output of Command <%=params[:command]%></h1>
+ <div class="info"><%=link_to("Back to Commands", :action => 'commands')%>
+ <div id="commandout">
+ <%= @output.gsub('\n', '<br/>')%>
+ </div>
+ <%end%>
<%end%>
\ No newline at end of file
diff --git a/src/server/app/views/agents/show.rhtml b/src/server/app/views/agents/show.rhtml
index 13bb4b4..55a3ca8 100644
--- a/src/server/app/views/agents/show.rhtml
+++ b/src/server/app/views/agents/show.rhtml
@@ -1,52 +1,52 @@
<div class="rightsearch">
<div>
<% form_for :search, :url => { :id => params[:id]} do |form| %>
<div>Search within Agent</div>
<div><%= form.text_field :data, :size => 20, :class => "minisearchbox" %> </div>
<%end%>
</div>
</div>
<div class="clear"></div>
<h1>All Events for <%=h @agent.name%></h1>
<div id="filter">
<% if params[:logtype]%>
Current filter: <%= h Logtype.find(params[:logtype]).name%>
<%else%>
Filter by logtype:
<% for type in @agent.logtypes.all do %>
<%= link_to( h(type.name), :logtype => type.id, :withepoch => params[:withepoch] )%>
<%end%>
<%end%>
<div class="adendem">
<%= link_to("Clear filter", :logtype => nil, :withepoch => params[:withepoch])%>
</div>
</div>
<div id="events">
<% for event in @events do %>
<div class="event">
<a href="#" onclick="$('.eventinfo<%=event.id%>').toggle();return false"><%= if params[:withepoch] then event.etime else Time.at(event.etime.to_f) end %></a> : <%= link_to(h(event.loglevel.name), :action => "show", :loglevel => event.loglevel.id, :withepoch => params[:withepoch])%> ::
- <%=h event.payload%>
+ <%=sanitize event.payload, :tags => %w(br)%>
<div class="eventinfo<%=event.id%>" style="display:none; background:#FF9; border:1px solid #000; padding:5px;">
<div class="info">Logtype: <%=link_to(h(event.staticentry.logtype.name), :controller => "logtypes", :action => "show", :id => event.staticentry.logtype.id)%></div>
<div class="info">Static Entry Id: <%=h event.staticentry_id%></div>
</div>
</div>
<%end%>
</div>
<div class="pagination">
<%= will_paginate @event %>
</div>
<div class="adendem">
Records per page:
<%=link_to "20", :withepoch => params[:withepoch], :page => 1, :perpage => "20" %> |
<%=link_to "50", :withepoch => params[:withepoch], :page => 1, :perpage => "50" %> |
<%=link_to "100", :withepoch => params[:withepoch], :page => 1, :perpage => "100" %> |
<%=link_to "200", :withepoch => params[:withepoch], :page => 1, :perpage => "200" %>
</div>
<%if params[:withepoch]%>
<div class="adendem"><%=link_to "show regular time", :withepoch => nil, :page => params[:page], :perpage => params[:perpage], :logtype => params[:logtype] %></div>
<%else%>
<div class="adendem"><%=link_to "show epoch time", :withepoch => 1, :page => params[:page], :perpage => params[:perpage], :logtype => params[:logtype] %></div>
<%end%>
\ No newline at end of file
diff --git a/src/server/app/views/events/show.rhtml b/src/server/app/views/events/show.rhtml
index 6164972..05ea883 100644
--- a/src/server/app/views/events/show.rhtml
+++ b/src/server/app/views/events/show.rhtml
@@ -1,36 +1,36 @@
<h1>All Events</h1>
<%unless params[:loglevel].nil?%>
<div class="adendem"><%=link_to("clear filters", :action => "show", :loglevel => nil)%></div>
<%end%>
<div id="events">
<% for event in @events do %>
<div class="event">
<a href="#" onclick="$('.eventinfo<%=event.id%>').toggle();return false"><%= if params[:withepoch] then event.etime else Time.at(event.etime.to_f) end %></a> : <%= link_to(h(event.loglevel.name), :action => "show", :loglevel => event.loglevel.id, :withepoch => params[:withepoch])%> ::
- <%= h event.payload%>
+ <%= sanitize event.payload, :tags => %w(br) %>
<div class="eventinfo<%=event.id%>" style="display:none; background:#FF9; border:1px solid #000; padding:5px;">
<div class="info">Agent: <%=link_to(h(event.agent.name), :controller => "agents", :action => "show", :id => event.agent.id)%></div>
<div class="info">Logtype: <%=link_to(h(event.staticentry.logtype.name), :controller => "logtypes", :action => "show", :id => event.staticentry.logtype.id)%></div>
<div class="info">Static Entry Id: <%=h event.staticentry_id%></div>
</div>
</div>
<%end%>
</div>
<div class="pagination">
<%= will_paginate @event %>
</div>
<div class="adendem">
Records per page:
<%=link_to "20", :loglevel => params[:loglevel], :withepoch => params[:withepoch], :page => 1, :perpage => "20" %> |
<%=link_to "50", :loglevel => params[:loglevel], :withepoch => params[:withepoch], :page => 1, :perpage => "50" %> |
<%=link_to "100", :loglevel => params[:loglevel], :withepoch => params[:withepoch], :page => 1, :perpage => "100" %> |
<%=link_to "200", :loglevel => params[:loglevel], :withepoch => params[:withepoch], :page => 1, :perpage => "200" %>
</div>
<%if params[:withepoch]%>
<div class="adendem"><%=link_to "show regular time", :withepoch => nil, :loglevel => params[:loglevel], :page => params[:page], :perpage => params[:perpage] %></div>
<%else%>
<div class="adendem"><%=link_to "show epoch time", :withepoch => 1, :loglevel => params[:loglevel], :page => params[:page], :perpage => params[:perpage] %></div>
<%end%>
<div class="adendem"><%=link_to "view by agent", :controller => 'agents', :action => "index" %> | <%=link_to "view by logtype", :controller => 'logtypes', :action => 'index' %></div>
diff --git a/src/server/app/views/layouts/application.rhtml b/src/server/app/views/layouts/application.rhtml
index c437a29..5b77add 100644
--- a/src/server/app/views/layouts/application.rhtml
+++ b/src/server/app/views/layouts/application.rhtml
@@ -1,82 +1,82 @@
<%starttime = Time.now.to_f %>
<!DOCTYPE HTML PUBLIC "!//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Cistern :: <%= @title %></title>
<%= stylesheet_link_tag "main" %>
<%= javascript_include_tag "jquery.min"%>
<%= javascript_include_tag "application"%>
</head>
<body>
<div id="header">
<div id="logo">Cistern</div>
<div id="search">
Search all Events
<% form_for :search, :url => { :action => "index", :controller => "search" } do |form| %>
<div><%= form.text_field :data, :size => 20, :class => "searchbox", :value => params[:query] %></div>
<!--<div class="adendem">advanced</div> -->
<%end%>
</div>
</div> <!-- header -->
<div id="container">
<div id="topnav">
<%= link_to("Events", :controller => "events", :action => "index")%>
<%= link_to("Agents", :controller => "agents", :action => "index")%>
<%= link_to("Logtypes", :controller => "logtypes", :action => "index")%>
<%= link_to("Search", :controller => "search", :action => "index")%>
<!-- <%= link_to("Stats", :controller => "stats", :action => "index")%> -->
</div>
<div id="main">
<% if flash[:notice]%>
- <div id="notice"><%=flash[:notice]%></div>
+ <div id="notice"><%=h flash[:notice]%></div>
<%end%>
<%if flash[:error]%>
- <div id="error"><%=flash[:error]%></div>
+ <div id="error"><%=h flash[:error]%></div>
<%end%>
<%= @content_for_layout %>
</div> <!-- main -->
<div id="footer">
Copyright © 2009 Mike Heijmans
<div class="adendum">powered by <a href="http://parabuzzle.github.com/cistern">Cistern</a></div>
</div> <!-- footer -->
<% if ENV["RAILS_ENV"] == "development" #call this block if in dev mode %>
<!-- Dev stuff -->
<div id="debug">
<a href='#' onclick="$('#params_debug_info').toggle();return false">params</a> |
<a href='#' onclick="$('#session_debug_info').toggle();return false">session</a> |
<a href='#' onclick="$('#env_debug_info').toggle();return false">env</a> |
<a href='#' onclick="$('#request_debug_info').toggle();return false">request</a>
<fieldset id="params_debug_info" class="debug_info" style="display:none">
<legend>params</legend>
<%= debug(params) %>
</fieldset>
<fieldset id="session_debug_info" class="debug_info" style="display:none">
<legend>session</legend>
<%= debug(session) %>
</fieldset>
<fieldset id="env_debug_info" class="debug_info" style="display:none">
<legend>env</legend>
<%= debug(request.env) %>
</fieldset>
<fieldset id="request_debug_info" class="debug_info" style="display:none">
<legend>request</legend>
<%= debug(request) %>
</fieldset>
</div>
<!-- end Dev mode only stuff -->
<% end %>
</div> <!-- container -->
</body>
</html>
<% rtime = Time.now.to_f - starttime%>
<% if ENV["RAILS_ENV"] == "development"%>
<%= [rtime*1000].to_s.to_i %> ms
<%else%>
<!-- <%= rtime*1000 %> -->
<%end%>
\ No newline at end of file
diff --git a/src/server/app/views/logtypes/show.rhtml b/src/server/app/views/logtypes/show.rhtml
index 0c76c1f..8efde2f 100644
--- a/src/server/app/views/logtypes/show.rhtml
+++ b/src/server/app/views/logtypes/show.rhtml
@@ -1,46 +1,46 @@
<div class="rightsearch">
<div>
<% form_for :search, :url => { :id => params[:id]} do |form| %>
<div>Search within Logtype</div>
<div><%= form.text_field :data, :size => 20, :class => "minisearchbox" %> </div>
<%end%>
</div>
</div>
<div class="clear"></div>
<h1>All Events for <%=h @logtype.name%></h1>
<div id="filter">
<a href='#' onclick="$('.agentinfo').toggle();return false">View by Agent</a>
<div class="agentinfo" style="display:none; background:#FF9; padding: 3px; border: 1px solid #000">
<% for agent in @logtype.agents do %>
<div class="info"><%= link_to( h(agent.name), :controller => 'agents', :action => 'show', :logtype => @logtype.id, :withepoch => params[:withepoch], :id => agent.id )%></div>
<%end%>
</div>
</div>
<div id="events">
<% for event in @events do %>
<div class="event">
<a href="#" onclick="$('.eventinfo<%=event.id%>').toggle();return false"><%= if params[:withepoch] then event.etime else Time.at(event.etime.to_f) end %></a> : <%= link_to(h(event.loglevel.name), :action => "show", :loglevel => event.loglevel.id, :withepoch => params[:withepoch])%> ::
- <%=h event.payload%>
+ <%=sanitize event.payload, :tags => %w(br)%>
<div class="eventinfo<%=event.id%>" style="display:none; background:#FF9; border:1px solid #000; padding:5px;">
<div class="info">Agent: <%=link_to(h(event.agent.name), :controller => "agents", :action => "show", :id => event.agent.id)%></div>
<div class="info">Static Entry Id: <%=h event.staticentry_id%></div>
</div>
</div>
<%end%>
</div>
<div class="pagination">
<%= will_paginate @event %>
</div>
<div class="adendem">
Records per page:
<%=link_to "20", :withepoch => params[:withepoch], :page => 1, :perpage => "20" %> |
<%=link_to "50", :withepoch => params[:withepoch], :page => 1, :perpage => "50" %> |
<%=link_to "100", :withepoch => params[:withepoch], :page => 1, :perpage => "100" %> |
<%=link_to "200", :withepoch => params[:withepoch], :page => 1, :perpage => "200" %>
</div>
<%if params[:withepoch]%>
<div class="adendem"><%=link_to "show regular time", :withepoch => nil, :page => params[:page], :perpage => params[:perpage] %></div>
<%else%>
<div class="adendem"><%=link_to "show epoch time", :withepoch => 1, :page => params[:page], :perpage => params[:perpage] %></div>
<%end%>
\ No newline at end of file
diff --git a/src/server/app/views/search/show.rhtml b/src/server/app/views/search/show.rhtml
index a1303e0..85fd806 100644
--- a/src/server/app/views/search/show.rhtml
+++ b/src/server/app/views/search/show.rhtml
@@ -1,16 +1,16 @@
<h1>Search Results</h1>
<div id="totalhits">Found <%=@total%> matching results</div>
<div id="events">
<% for event in @results do %>
<div class="event">
<a href="#" onclick="$('.eventinfo<%=event.id%>').toggle();return false"><%= if params[:withepoch] then event.etime else Time.at(event.etime.to_f) end %></a> : <%= h event.loglevel.name %> ::
- <%=h event.full_event%>
+ <%=sanitize event.full_event, :tags => %w(br)%>
<div class="eventinfo<%=event.id%>" style="display:none; background:#FF9; border:1px solid #000; padding:5px;">
<div class="info">Agent: <%=link_to(h(event.agent.name), :controller => "agents", :action => "show", :id => event.agent.id)%></div>
<div class="info">Logtype: <%=link_to(h(event.staticentry.logtype.name), :controller => "logtypes", :action => "show", :id => event.staticentry.logtype.id)%></div>
<div class="info">Static Entry Id: <%=h event.staticentry_id%></div>
</div>
</div>
<%end%>
</div>
<%=will_paginate @results%>
\ No newline at end of file
|
parabuzzle/cistern
|
017b0818d9899bb572b83404a80c9ee9f0c881df
|
Removed schema.rb from source
|
diff --git a/.gitignore b/.gitignore
index b9d47a8..f7f726b 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,9 +1,10 @@
*.log
*.pid
*.sqlite3
src/server/config/database.yml
src/server/config/daemons.yml
src/server/config/collectors.yml
src/server/config/cistern.yml
src/server/config/memcached.yml
src/server/index
+src/server/db/schema.rb
diff --git a/src/server/db/schema.rb b/src/server/db/schema.rb
deleted file mode 100644
index 3f9b2a6..0000000
--- a/src/server/db/schema.rb
+++ /dev/null
@@ -1,78 +0,0 @@
-# This file is auto-generated from the current state of the database. Instead of editing this file,
-# please use the migrations feature of Active Record to incrementally modify your database, and
-# then regenerate this schema definition.
-#
-# Note that this schema.rb definition is the authoritative source for your database schema. If you need
-# to create the application database on another system, you should be using db:schema:load, not running
-# all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations
-# you'll amass, the slower it'll run and the greater likelihood for issues).
-#
-# It's strongly recommended to check this file into your version control system.
-
-ActiveRecord::Schema.define(:version => 20090806184417) do
-
- create_table "agents", :force => true do |t|
- t.string "name"
- t.string "hostname"
- t.string "port"
- t.string "authkey"
- t.datetime "created_at"
- t.datetime "updated_at"
- end
-
- add_index "agents", ["hostname"], :name => "index_agents_on_hostname"
- add_index "agents", ["name"], :name => "index_agents_on_name"
-
- create_table "agents_logtypes", :id => false, :force => true do |t|
- t.integer "logtype_id"
- t.integer "agent_id"
- t.datetime "created_at"
- t.datetime "updated_at"
- end
-
- add_index "agents_logtypes", ["agent_id"], :name => "index_agents_logtypes_on_agent_id"
- add_index "agents_logtypes", ["logtype_id"], :name => "index_agents_logtypes_on_logtype_id"
-
- create_table "events", :force => true do |t|
- t.string "payload"
- t.string "staticentry_id"
- t.integer "agent_id"
- t.integer "loglevel_id"
- t.integer "logtype_id"
- t.float "etime"
- t.datetime "created_at"
- t.datetime "updated_at"
- end
-
- add_index "events", ["agent_id"], :name => "index_events_on_agent_id"
- add_index "events", ["etime"], :name => "index_events_on_etime"
- add_index "events", ["loglevel_id"], :name => "index_events_on_loglevel_id"
- add_index "events", ["logtype_id"], :name => "index_events_on_logtype_id"
- add_index "events", ["staticentry_id"], :name => "index_events_on_staticentry_id"
-
- create_table "loglevels", :force => true do |t|
- t.string "name"
- t.datetime "created_at"
- t.datetime "updated_at"
- end
-
- create_table "logtypes", :force => true do |t|
- t.string "name"
- t.datetime "created_at"
- t.datetime "updated_at"
- t.string "description"
- end
-
- add_index "logtypes", ["name"], :name => "index_logtypes_on_name"
-
- create_table "staticentries", :force => true do |t|
- t.integer "logtype_id"
- t.text "data"
- t.datetime "created_at"
- t.datetime "updated_at"
- end
-
- add_index "staticentries", ["id"], :name => "index_staticentries_on_id"
- add_index "staticentries", ["logtype_id"], :name => "index_staticentries_on_logtype_id"
-
-end
|
parabuzzle/cistern
|
e8a219973e9e8326e06d5544aeb1206bfb9d088d
|
Fixed schema and migrations
|
diff --git a/src/server/db/migrate/20090721233433_create_events.rb b/src/server/db/migrate/20090721233433_create_events.rb
index 5377908..4e39165 100644
--- a/src/server/db/migrate/20090721233433_create_events.rb
+++ b/src/server/db/migrate/20090721233433_create_events.rb
@@ -1,22 +1,22 @@
class CreateEvents < ActiveRecord::Migration
def self.up
create_table :events do |t|
t.column :payload, :string
t.column :staticentry_id, :string
t.column :agent_id, :int
t.column :loglevel_id, :int
t.column :logtype_id, :int
- t.column :etime, :string
+ t.column :etime, :float
t.timestamps
end
add_index :events, :logtype_id
add_index :events, :loglevel_id
add_index :events, :etime
add_index :events, :agent_id
add_index :events, :staticentry_id
end
def self.down
drop_table :events
end
end
diff --git a/src/server/db/migrate/20090730154024_create_agents_logtype_map.rb b/src/server/db/migrate/20090730154024_create_agents_logtype_map.rb
index e144020..73d8567 100644
--- a/src/server/db/migrate/20090730154024_create_agents_logtype_map.rb
+++ b/src/server/db/migrate/20090730154024_create_agents_logtype_map.rb
@@ -1,15 +1,15 @@
class CreateAgentsLogtypeMap < ActiveRecord::Migration
def self.up
create_table :agents_logtypes, :id => false do |t|
t.column :logtype_id, :int
t.column :agent_id, :int
t.timestamps
end
add_index :agents_logtypes, :logtype_id
add_index :agents_logtypes, :agent_id
end
def self.down
- drop_table :events
+ drop_table :agents_logtypes
end
end
diff --git a/src/server/db/schema.rb b/src/server/db/schema.rb
index e1cdc83..3f9b2a6 100644
--- a/src/server/db/schema.rb
+++ b/src/server/db/schema.rb
@@ -1,78 +1,78 @@
# This file is auto-generated from the current state of the database. Instead of editing this file,
# please use the migrations feature of Active Record to incrementally modify your database, and
# then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your database schema. If you need
# to create the application database on another system, you should be using db:schema:load, not running
# all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended to check this file into your version control system.
ActiveRecord::Schema.define(:version => 20090806184417) do
create_table "agents", :force => true do |t|
t.string "name"
t.string "hostname"
t.string "port"
t.string "authkey"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "agents", ["hostname"], :name => "index_agents_on_hostname"
add_index "agents", ["name"], :name => "index_agents_on_name"
create_table "agents_logtypes", :id => false, :force => true do |t|
t.integer "logtype_id"
t.integer "agent_id"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "agents_logtypes", ["agent_id"], :name => "index_agents_logtypes_on_agent_id"
add_index "agents_logtypes", ["logtype_id"], :name => "index_agents_logtypes_on_logtype_id"
create_table "events", :force => true do |t|
t.string "payload"
t.string "staticentry_id"
t.integer "agent_id"
t.integer "loglevel_id"
t.integer "logtype_id"
- t.string "etime"
+ t.float "etime"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "events", ["agent_id"], :name => "index_events_on_agent_id"
add_index "events", ["etime"], :name => "index_events_on_etime"
add_index "events", ["loglevel_id"], :name => "index_events_on_loglevel_id"
add_index "events", ["logtype_id"], :name => "index_events_on_logtype_id"
add_index "events", ["staticentry_id"], :name => "index_events_on_staticentry_id"
create_table "loglevels", :force => true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "logtypes", :force => true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
t.string "description"
end
add_index "logtypes", ["name"], :name => "index_logtypes_on_name"
create_table "staticentries", :force => true do |t|
t.integer "logtype_id"
t.text "data"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "staticentries", ["id"], :name => "index_staticentries_on_id"
add_index "staticentries", ["logtype_id"], :name => "index_staticentries_on_logtype_id"
end
|
parabuzzle/cistern
|
7c613d130b00875828fe91ea6473635fce1b20cc
|
Added commands for agents and started on the agent stuff
|
diff --git a/src/agent/agent.rb b/src/agent/agent.rb
index 100975e..4232e34 100644
--- a/src/agent/agent.rb
+++ b/src/agent/agent.rb
@@ -1,58 +1,26 @@
require 'rubygems'
require 'eventmachine'
require 'lib/modules.rb'
require 'socket'
require 'file/tail'
+require 'yaml'
+require 'digest/md5'
+require 'lib/commands.rb'
+include AgentCommands
include File::Tail
include Socket::Constants
-BREAK = "__1_BB"
-VALUE = "__1_VV"
-CHECKSUM = "__1_CC"
-FINISH = "__1_EE"
-filename = "/var/logs/auth.log"
-authkey = "55bef2e25cc000d3c0d55d8ae27b6aeb"
-agent_id = 1
-logtype_id = 1
+port = 9846
+bindip = '127.0.0.1'
-socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
-sockaddr = Socket.pack_sockaddr_in( 9845, '127.0.0.1' )
-socket.connect( sockaddr )
-def send_event(entry)
- event = Hash.new
- e = String.new
-
- d = entry[0,16].split(' ')
- m = d[2].split(':')
- etime = Time.local(Time.now.year,d[0],d[1],m[0],m[1],m[2]).to_i
- loglevel_id = 4
- payload = 'EVENT/000/' + event.gsub(data[0,16], '')
- static = "<<<EVENT>>>"
-
- event.store("authkey", authkey)
- event.store("logtype_id", logtype_id)
- event.store("agent_id", agent_id)
- event.store("loglevel_id", loglevel_id)
- event.store("etime", etime)
- event.store("data", static)
- event.store("payload", payload)
-
- event.each do |key, val|
- e = e + key.to_s + VALUE + val.to_s + BREAK
- end
- e = e + CHECKSUM + Digest::MD5.hexdigest(e) + FINISH
-
- socket.write(e)
+Signal.trap("TERM") do
+ EventMachine::stop_event_loop
end
-
-File.open(filename) do |log|
- log.extend(File::Tail)
- log.interval = 1
- log.backward(0)
- log.tail { |line| send_event(line) }
-end
+EventMachine::run {
+ EventMachine::start_server bindip, port, CommandServer
+}
diff --git a/src/agent/lib/commands.rb b/src/agent/lib/commands.rb
new file mode 100644
index 0000000..088581e
--- /dev/null
+++ b/src/agent/lib/commands.rb
@@ -0,0 +1,11 @@
+module AgentCommands
+
+ def ps_auxx
+ return `ps auxx`
+ end
+
+ def get_users
+ return `w`
+ end
+
+end
\ No newline at end of file
diff --git a/src/agent/lib/modules.rb b/src/agent/lib/modules.rb
index 2f4c8c2..adb497a 100644
--- a/src/agent/lib/modules.rb
+++ b/src/agent/lib/modules.rb
@@ -1,30 +1,81 @@
-module CollectionServer
- def post_init
- ActiveRecord::Base.logger.info "-- someone connected to the collector"
- end
-
- def receive_data data
- # Do something with the log data
- ActiveRecord::Base.logger.info "#{data}"
- end
-
- def unbind
- ActiveRecord::Base.logger.info "-- someone disconnected from the collector"
- end
-end
-
module CommandServer
+
+ def check_sig(serverkey, payload)
+ if serverkey != Digest::MD5.hexdigest("7952d3072b86a949e45232fe42ad03bc" + payload)
+ return false
+ else
+ return true
+ end
+ return true
+ end
+
+ def command_list
+ c = String.new
+ AgentCommands.instance_methods.each do |command|
+ c = c + command + "/000/"
+ end
+ return c
+ end
+
+ def get_command(data)
+ #return data from cammand
+ begin
+ d = eval data
+ return d
+ rescue NameError
+ return "not a valid command"
+ end
+ end
+
+ def get_result(data)
+ if data == "ls"
+ return command_list
+ else
+ return get_command(data)
+ end
+ end
+
def post_init
-
+ puts "connection opened"
+ #Log that the server connected
end
def receive_data data
- # Do something with the log data
-
+ puts data
+ (@buffer ||= BufferedTokenizer.new(delimiter = "__1_EE")).extract(data).each do |line|
+ if line.valid?
+ line = line.split('__1_CC')[0]
+ parts = line.split('__1_BB')
+ map = Hash.new
+ parts.each do |part|
+ p = part.split('__1_VV')
+ map.store(p[0], p[1])
+ end
+ if check_sig(map['authkey'], map['payload'])
+ puts map['payload']
+ send_data get_result(map['payload'])
+ puts get_result(map['payload'])
+ else
+ #log signature is bad
+ puts "signature is bad - punted"
+ end
+ else
+ #log checksum invalid
+ puts "checksum is bad - punted"
+ end
+ end
end
def unbind
-
+ #Log that the server disconnected
+ puts "peer disconnected"
end
end
+class String
+ def valid?
+ part = self.split('__1_CC')
+ #return true
+ return Digest::MD5.hexdigest(part[0]) == part[1]
+ end
+end
\ No newline at end of file
diff --git a/src/agent/logsender.rb b/src/agent/logsender.rb
index cf9acd5..100975e 100644
--- a/src/agent/logsender.rb
+++ b/src/agent/logsender.rb
@@ -1,57 +1,58 @@
+require 'rubygems'
+require 'eventmachine'
+require 'lib/modules.rb'
require 'socket'
-require 'yaml'
-require 'digest/md5'
+require 'file/tail'
+include File::Tail
include Socket::Constants
-@break = "__1_BB"
-@value = "__1_VV"
-@checksum = "__1_CC"
+BREAK = "__1_BB"
+VALUE = "__1_VV"
+CHECKSUM = "__1_CC"
+FINISH = "__1_EE"
-
-def close_tx(socket)
- socket.write("__1_EE")
-end
-def newvalbr(socket)
- socket.write("__1_BB")
-end
-def valbr(socket)
- socket.write("__1_VV")
-end
-def checkbr(socket)
- socket.write("__1_CC")
-end
+filename = "/var/logs/auth.log"
+authkey = "55bef2e25cc000d3c0d55d8ae27b6aeb"
+agent_id = 1
+logtype_id = 1
socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
sockaddr = Socket.pack_sockaddr_in( 9845, '127.0.0.1' )
socket.connect( sockaddr )
-#Things you need...
-#data - static data
-#logtype_id - logtype
-#loglevel - The log level of the event
-#time - the original time of the event
-#payload - The dynamic data for the event (format - NAME=value)
-#agent_id - The reporting agent's id
-#
-#The entire sting should have a checksum or it will be thrown out
-
-event = Hash.new
-event.store("authkey", "55bef2e25cc000d3c0d55d8ae27b6aeb")
-event.store("data","rotating events log for <<<NAME>>>")
-event.store("logtype_id", 3)
-event.store("loglevel_id", 4)
-event.store("etime", Time.now.to_f)
-event.store("payload", "NAME/000/jboss")
-event.store("agent_id", 1)
-
-e = String.new
-event.each do |key, val|
- e = e + key.to_s + @value + val.to_s + @break
+def send_event(entry)
+ event = Hash.new
+ e = String.new
+
+ d = entry[0,16].split(' ')
+ m = d[2].split(':')
+ etime = Time.local(Time.now.year,d[0],d[1],m[0],m[1],m[2]).to_i
+ loglevel_id = 4
+ payload = 'EVENT/000/' + event.gsub(data[0,16], '')
+ static = "<<<EVENT>>>"
+
+ event.store("authkey", authkey)
+ event.store("logtype_id", logtype_id)
+ event.store("agent_id", agent_id)
+ event.store("loglevel_id", loglevel_id)
+ event.store("etime", etime)
+ event.store("data", static)
+ event.store("payload", payload)
+
+ event.each do |key, val|
+ e = e + key.to_s + VALUE + val.to_s + BREAK
+ end
+ e = e + CHECKSUM + Digest::MD5.hexdigest(e) + FINISH
+
+ socket.write(e)
end
-e = e + @checksum + Digest::MD5.hexdigest(e) + "__1_EE"
-puts e
-socket.write(e)
+File.open(filename) do |log|
+ log.extend(File::Tail)
+ log.interval = 1
+ log.backward(0)
+ log.tail { |line| send_event(line) }
+end
diff --git a/src/server/app/controllers/agents_controller.rb b/src/server/app/controllers/agents_controller.rb
index 2c61c63..e752791 100644
--- a/src/server/app/controllers/agents_controller.rb
+++ b/src/server/app/controllers/agents_controller.rb
@@ -1,88 +1,100 @@
class AgentsController < ApplicationController
+ include AgentsHelper
def index
@title = "Agents"
@agents = Agent.paginate :all, :per_page => params[:perpage], :page => params[:page]
end
def show
@agent = Agent.find(params[:id])
if request.post?
redirect_to :action => "search", :id => params[:id], :aquery => params[:search][:data]
end
@title = "All Events for #{@agent.name}"
if params[:logtype].nil? and params[:loglevel].nil?
@event = @agent.events.paginate :all, :per_page => params[:perpage], :page => params[:page]
elsif !params[:logtype].nil? and params[:loglevel].nil?
@event = @agent.events.paginate :all, :per_page => params[:perpage], :page => params[:page], :conditions => "logtype_id = '#{params[:logtype]}'"
elsif params[:logtype].nil? and !params[:loglevel].nil?
@event = @agent.events.paginate :all, :per_page => params[:perpage], :page => params[:page], :conditions => "loglevel_id <= '#{params[:loglevel]}'"
else
@event = @agent.events.paginate :all, :per_page => params[:perpage], :page => params[:page], :conditions => "logtype_id = '#{params[:logtype]}' and loglevel_id <= '#{params[:loglevel]}'"
end
@events = rebuildevents(@event)
end
+ def commands
+ @agent = Agent.find(params[:id])
+ if params[:command].nil?
+ @title = "Available Commands for #{@agent.name}"
+ @commands = get_commands(@agent)
+ else
+ @title = "Command output for #{params[:command]}"
+ @output = get_command(@agent, params[:command])
+ end
+ end
+
def search
if request.post?
params[:aquery] = params[:search][:data]
end
if params[:aquery].nil?
redirect_to :action => 'show', :id => params[:id]
else
@title = "Search Results"
@agent = Agent.find(params[:id])
@total = @agent.events.find_with_ferret(params[:aquery]).length
@results = @agent.events.paginate(params[:aquery], {:finder => "find_with_ferret", :total_entries => @total}.merge({:page => params[:page], :per_page => params[:per_page]}))
end
end
def new
if request.post?
@agent = Agent.new(params[:agent])
@agent.authkey = Digest::MD5.hexdigest(@agent.hostname + Time.now.to_s)
if @agent.save
flash[:notice] = "Agent #{@agent.name} added -- don't forget to edit your agent to add it to your logtypes"
redirect_to :action => "index"
else
flash[:error] = "There were errors creating your agent"
end
else
@title = "Create New Agent"
end
end
def edit
@agent = Agent.find(params[:id])
if request.post?
params[:agent][:logtype_ids] ||= []
@agent.update_attributes(params[:agent])
if @agent.save
flash[:notice] = "Agent #{@agent.name} updated"
redirect_to :action => "index"
else
flash[:error] = "There were errors updating your agent"
end
else
@title = "Edit #{@agent.name}"
end
end
def delete
@agent = params[:id]
if request.post?
if @agent.destroy
flash[:notice] = "Agent deleted"
redirect_to :action => "index"
else
flash[:error] = "Error trying to delete agent"
redirect_to :action => "index"
end
else
flash[:error] = "Poking around is never a good idea"
redirect_to :action => "index"
end
end
end
diff --git a/src/server/app/helpers/agents_helper.rb b/src/server/app/helpers/agents_helper.rb
index 7e54438..62ee30b 100644
--- a/src/server/app/helpers/agents_helper.rb
+++ b/src/server/app/helpers/agents_helper.rb
@@ -1,2 +1,51 @@
+include Socket::Constants
module AgentsHelper
+
+ def get_commands(agent)
+ socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
+ sockaddr = Socket.pack_sockaddr_in( agent.port, agent.hostname )
+ socket.connect( sockaddr )
+ h = Hash.new
+ e = String.new
+ payload = 'ls'
+ authkey = Digest::MD5.hexdigest(agent.authkey + payload)
+ h.store("authkey", authkey)
+ h.store("payload", payload)
+ h.each do |key, val|
+ e = e + key.to_s + "__1_VV" + val.to_s + "__1_BB"
+ end
+ e = e + "__1_CC" + Digest::MD5.hexdigest(e) + "__1_EE"
+
+ socket.write(e)
+ r = socket.recvfrom(1045504)[0].chomp
+ socket.close
+ return break_commands(r)
+ end
+
+ def get_command(agent, command)
+ socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
+ sockaddr = Socket.pack_sockaddr_in( agent.port, agent.hostname )
+ socket.connect( sockaddr )
+ h = Hash.new
+ e = String.new
+ payload = command
+ authkey = Digest::MD5.hexdigest(agent.authkey + payload)
+ h.store("authkey", authkey)
+ h.store("payload", payload)
+ h.each do |key, val|
+ e = e + key.to_s + "__1_VV" + val.to_s + "__1_BB"
+ end
+ e = e + "__1_CC" + Digest::MD5.hexdigest(e) + "__1_EE"
+
+ socket.write(e)
+ r = socket.recvfrom(1045504)[0].chomp
+ socket.close
+ return r.gsub("\n", "<br/>")
+ end
+
+ def break_commands(r)
+ a = r.split('/000/')
+ return a
+ end
+
end
diff --git a/src/server/app/views/agents/commands.rhtml b/src/server/app/views/agents/commands.rhtml
new file mode 100644
index 0000000..4041c57
--- /dev/null
+++ b/src/server/app/views/agents/commands.rhtml
@@ -0,0 +1,14 @@
+<%if params[:command].nil?%>
+<h1>Available Commands for <%=@agent.name%></h1>
+<ul>
+<% for command in @commands do%>
+ <li><%=link_to(command, :command => command, :action => 'commands')%></li>
+<%end%>
+</ul>
+<%else%>
+<h1>Output of Command <%=params[:command]%></h1>
+<div class="info"><%=link_to("Back to Commands", :action => 'commands')%>
+<div id="commandout">
+<%= @output.gsub('\n', '<br/>')%>
+</div>
+<%end%>
\ No newline at end of file
diff --git a/src/server/app/views/agents/index.rhtml b/src/server/app/views/agents/index.rhtml
index 7fa6c48..9d9e655 100644
--- a/src/server/app/views/agents/index.rhtml
+++ b/src/server/app/views/agents/index.rhtml
@@ -1,30 +1,31 @@
<h1>Agents</h1>
<div class="subnav"><%=link_to("Create new Agent #{image_tag("addserver.png", :alt => "add server", :border => "0px")}", :action => "new")%></div>
<div class="clear"></div>
<% for agent in @agents do%>
<div class="agent">
<%=image_tag("serverup.png")%><a href='#' onclick="$('.agentinfo<%=agent.id%>').toggle();return false"><%= h agent.name%></a> : <%=link_to("View Events", :action=>"show", :id=>agent.id)%>
<div class="agentinfo<%=agent.id%>" style="display:none; margin-left:30px; background:#FF9; padding: 3px; border: 1px solid #000">
<div class="subnav" style="width:200px;">
Logtypes
<% for logtype in agent.logtypes do%>
<div class="adendem"><%=h logtype.name%></div>
<%end%>
</div>
<div clear></div>
<div class="info">Total Events: <%= agent.events.count %></div>
<div class="info">Hostname: <%=h agent.hostname%></div>
<div class="info">Listenport: <%=h agent.port%></div>
<div class="info">Key: <%=h agent.authkey%></div>
<div class="info">Agent_id: <%=agent.id%></div>
+ <div class="info"><%=link_to("View Commands for Host", :action => "commands", :id => agent.id)%></div>
<div class="info"><%=link_to("edit", :action => "edit", :id => agent.id)%></div>
</div>
</div>
<%end%>
<div class="pagination">
<%= will_paginate @event %>
</div>
\ No newline at end of file
diff --git a/src/server/app/views/search/show.rhtml b/src/server/app/views/search/show.rhtml
index cb9a37d..a1303e0 100644
--- a/src/server/app/views/search/show.rhtml
+++ b/src/server/app/views/search/show.rhtml
@@ -1,16 +1,16 @@
<h1>Search Results</h1>
<div id="totalhits">Found <%=@total%> matching results</div>
<div id="events">
<% for event in @results do %>
<div class="event">
<a href="#" onclick="$('.eventinfo<%=event.id%>').toggle();return false"><%= if params[:withepoch] then event.etime else Time.at(event.etime.to_f) end %></a> : <%= h event.loglevel.name %> ::
<%=h event.full_event%>
- <div class="eventinfo<%=event.id%>" style="display:none; background:#FF9; border:1px solid #000; padding:5px; width:50%">
+ <div class="eventinfo<%=event.id%>" style="display:none; background:#FF9; border:1px solid #000; padding:5px;">
<div class="info">Agent: <%=link_to(h(event.agent.name), :controller => "agents", :action => "show", :id => event.agent.id)%></div>
<div class="info">Logtype: <%=link_to(h(event.staticentry.logtype.name), :controller => "logtypes", :action => "show", :id => event.staticentry.logtype.id)%></div>
<div class="info">Static Entry Id: <%=h event.staticentry_id%></div>
</div>
</div>
<%end%>
</div>
<%=will_paginate @results%>
\ No newline at end of file
diff --git a/src/server/public/stylesheets/main.css b/src/server/public/stylesheets/main.css
index 4cbaf3e..3aa041c 100644
--- a/src/server/public/stylesheets/main.css
+++ b/src/server/public/stylesheets/main.css
@@ -1,233 +1,242 @@
body {
background: #fff;
color: #000;
margin: 0px;
padding: 0px;
color: #333;
font-weight:bold;
font-family: serif;
}
a {
text-decoration: none;
color: #660033;
}
a:hover {
background: #000033;
color: #fff;
padding: 2px;
}
#container {
padding: 0px;
margin: auto;
width: 900px;
}
#header {
width: 100%;
margin: 0px;
height: 95px;
background: #333;
border-bottom: solid 6px #000;
color:#fff;
}
#logo {
position: absolute;
padding-top: 20px;
padding-left: 45px;
font-weight:bold;
font-size: 55px;
color: #fff;
}
#search {
text-align: right;
padding-top: 20px;
padding-right: 50px;
}
.searchbox {
background: #663366;
border: 1px solid #000;
color: #fff;
font-size: 20px;
padding: 2px;
font-weight: none;
}
#eventlist {
min-height: 350px;
_height: 350px;
}
#topnav a {
background: #000;
padding: 4px;
padding-bottom: 4px;
padding-left: 6px;
padding-right: 6px;
color: #fff;
border-left: solid 2px #000033;
border-right: solid 2px #000033;
border-bottom: solid 2px #000033;
}
#topnav a:hover {
background: #666;
padding: 4px;
padding-bottom: 4px;
padding-left: 6px;
padding-right: 6px;
color: #fff;
border-left: solid 2px #000033;
border-right: solid 2px #000033;
border-bottom: solid 2px #000033;
}
.topnav {
background: #666;
padding: 2px;
padding-bottom: 4px;
padding-left: 6px;
padding-right: 6px;
color: #fff;
border-left: solid 2px #000033;
border-right: solid 2px #000033;
border-bottom: solid 2px #000033;
}
#topnav {
font-size: 20px;
padding: 2px;
padding-bottom: 4px;
padding-left: 6px;
padding-right: 6px;
color: #fff;
}
#main {
min-height: 400px;
_height: 400px; /* IE min-height hack */
}
#footer {
text-align: center;
width: 900px;
border-top: 2px solid #000;
padding-top: 15px;
}
#notice {
margin-top: 10px;
width: 100%;
background: #09F;
color: #000;
padding: 10px;
border: 1px solid #333;
}
#error {
margin-top: 10px;
width: 100%;
background: #F00;
color: #000;
padding: 10px;
border: 1px solid #333;
}
#form {
width: 350px;
margin: auto;
}
.submitbutton {
background: #660033;
color: #fff;
border: 3px solid #000;
padding: 6px;
}
.fbox {
background: #ffff55;
border: 1px solid #333;
padding: 2px;
}
.clear {
clear:both;
}
.adendem {
font-size: 14px;
font-weight: normal;
}
.in20 {
padding-left: 20px;
padding-right: 20px;
}
.errorExplanation {
width: 800px;
margin: auto;
padding: 3px;
padding-left: 10px;
padding-right: 10px;
background: #ffff55;
border: 1px solid #333;
margin-bottom: 10px;
}
.subnav {
float:right;
}
.agent {
margin-top: 10px;
padding: 2px;
}
.result {
padding: 5px;
}
.advancedsearch {
display: none;
background:#FF9;
padding: 3px;
border: 1px solid #000
}
.event{
background: #fff;
margin-bottom: 10px;
}
.event a {
color:#333;
}
.event a:hover {
color:#333;
background: #aaa;
}
+#commandout {
+ overflow: auto;
+ white-space: nowrap;
+ background: #eee;
+ padding: 4px;
+ border: 1px solid #AAA;
+ margin: 5px;
+}
+
#totalhits {
margin-bottom: 10px;
font-size: 14px;
}
.mainsearchbox {
background: #FF9;
border: solid 1px #000;
font-size: 20px;
padding: 2px;
font-weight: none;
}
.searchsubmitbutton {
background: #660033;
color: #fff;
border: 1px solid #000;
padding: 6px;
height: 28px;
}
.rightsearch {
float:right;
text-align: right;
}
.minisearchbox {
background: #FF9;
border: 1px solid #000;
}
\ No newline at end of file
|
parabuzzle/cistern
|
a23071626792ffd980a290f3211a7ea797117689
|
Added h() to all user and log generated data in the views.
|
diff --git a/src/server/app/controllers/agents_controller.rb b/src/server/app/controllers/agents_controller.rb
index 84ebb4d..2c61c63 100644
--- a/src/server/app/controllers/agents_controller.rb
+++ b/src/server/app/controllers/agents_controller.rb
@@ -1,85 +1,88 @@
class AgentsController < ApplicationController
def index
@title = "Agents"
@agents = Agent.paginate :all, :per_page => params[:perpage], :page => params[:page]
end
def show
@agent = Agent.find(params[:id])
if request.post?
redirect_to :action => "search", :id => params[:id], :aquery => params[:search][:data]
end
@title = "All Events for #{@agent.name}"
if params[:logtype].nil? and params[:loglevel].nil?
@event = @agent.events.paginate :all, :per_page => params[:perpage], :page => params[:page]
elsif !params[:logtype].nil? and params[:loglevel].nil?
@event = @agent.events.paginate :all, :per_page => params[:perpage], :page => params[:page], :conditions => "logtype_id = '#{params[:logtype]}'"
elsif params[:logtype].nil? and !params[:loglevel].nil?
@event = @agent.events.paginate :all, :per_page => params[:perpage], :page => params[:page], :conditions => "loglevel_id <= '#{params[:loglevel]}'"
else
@event = @agent.events.paginate :all, :per_page => params[:perpage], :page => params[:page], :conditions => "logtype_id = '#{params[:logtype]}' and loglevel_id <= '#{params[:loglevel]}'"
end
@events = rebuildevents(@event)
end
def search
+ if request.post?
+ params[:aquery] = params[:search][:data]
+ end
if params[:aquery].nil?
redirect_to :action => 'show', :id => params[:id]
else
@title = "Search Results"
@agent = Agent.find(params[:id])
@total = @agent.events.find_with_ferret(params[:aquery]).length
@results = @agent.events.paginate(params[:aquery], {:finder => "find_with_ferret", :total_entries => @total}.merge({:page => params[:page], :per_page => params[:per_page]}))
end
end
def new
if request.post?
@agent = Agent.new(params[:agent])
@agent.authkey = Digest::MD5.hexdigest(@agent.hostname + Time.now.to_s)
if @agent.save
flash[:notice] = "Agent #{@agent.name} added -- don't forget to edit your agent to add it to your logtypes"
redirect_to :action => "index"
else
flash[:error] = "There were errors creating your agent"
end
else
@title = "Create New Agent"
end
end
def edit
@agent = Agent.find(params[:id])
if request.post?
params[:agent][:logtype_ids] ||= []
@agent.update_attributes(params[:agent])
if @agent.save
flash[:notice] = "Agent #{@agent.name} updated"
redirect_to :action => "index"
else
flash[:error] = "There were errors updating your agent"
end
else
@title = "Edit #{@agent.name}"
end
end
def delete
@agent = params[:id]
if request.post?
if @agent.destroy
flash[:notice] = "Agent deleted"
redirect_to :action => "index"
else
flash[:error] = "Error trying to delete agent"
redirect_to :action => "index"
end
else
flash[:error] = "Poking around is never a good idea"
redirect_to :action => "index"
end
end
end
diff --git a/src/server/app/controllers/logtypes_controller.rb b/src/server/app/controllers/logtypes_controller.rb
index 0e23544..46b6a69 100644
--- a/src/server/app/controllers/logtypes_controller.rb
+++ b/src/server/app/controllers/logtypes_controller.rb
@@ -1,78 +1,81 @@
class LogtypesController < ApplicationController
def index
@title = "Logtypes"
@logtypes = Logtype.paginate :all, :per_page => params[:perpage], :page => params[:page]
end
def show
@logtype = Logtype.find(params[:id])
if request.post?
redirect_to :action => "search", :id => params[:id], :aquery => params[:search][:data]
end
@title = "All Events for #{@logtype.name}"
if params[:loglevel].nil?
@event = @logtype.events.paginate :all, :per_page => params[:perpage], :page => params[:page]
else
@event = @logtype.events.paginate :all, :per_page => params[:perpage], :page => params[:page], :conditions => "loglevel_id <= '#{params[:loglevel]}'"
end
@events = rebuildevents(@event)
end
def search
+ if request.post?
+ params[:aquery] = params[:search][:data]
+ end
if params[:aquery].nil?
redirect_to :action => 'show', :id => params[:id]
else
@title = "Search Results"
@logtype = Logtype.find(params[:id])
@total = @logtype.events.find_with_ferret(params[:aquery]).length
@results = @logtype.events.paginate(params[:aquery], {:finder => "find_with_ferret", :total_entries => @total}.merge({:page => params[:page], :per_page => params[:per_page]}))
end
end
def new
if request.post?
@logtype = Logtype.new(params[:logtype])
if @logtype.save
flash[:notice] = "Logtype #{@logtype.name} added"
redirect_to :action => "index"
else
flash[:error] = "There were errors creating your logtype"
end
else
@title = "Create New Logtype"
end
end
def edit
@logtype = Logtype.find(params[:id])
if request.post?
@logtype.update_attributes(params[:logtype])
if @logtype.save
flash[:notice] = "Logtype #{@logtype.name} updated"
redirect_to :action => "index"
else
flash[:error] = "There were errors updating your logtype"
end
else
@title = "Edit #{@logtype.name}"
end
end
def delete
@logtype = params[:id]
if request.post?
if @logtype.destroy
flash[:notice] = "Logtype deleted"
redirect_to :action => "index"
else
flash[:error] = "Error trying to delete logtype"
redirect_to :action => "index"
end
else
flash[:error] = "Poking around is never a good idea"
redirect_to :action => "index"
end
end
end
diff --git a/src/server/app/helpers/application_helper.rb b/src/server/app/helpers/application_helper.rb
index 4738145..add149c 100644
--- a/src/server/app/helpers/application_helper.rb
+++ b/src/server/app/helpers/application_helper.rb
@@ -1,63 +1,63 @@
# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
#Return events array with payload field populated with full event
def rebuildevents(events)
@events = Array.new
events.each do |e|
e.payload = rebuildevent(e)
@events << e
end
return @events
end
#Return a string of replaced static entry keys based on event's payload
def rebuildevent(e)
if USEMEMCACHE != true
static = Staticentry.find(e.staticentry.id)
else
static = Staticentry.get_cache(e.staticentry.id)
end
- entries = e.payload.split(',')
+ entries = e.payload.split('/111/')
hash = Hash.new
entries.each do |m|
map = m.split('/000/')
hash.store('<<<' + map[0] + '>>>',map[1])
end
p = static.data
hash.each do |key, val|
p = p.gsub(key,val)
end
return p
end
def filter_agent(results,agent_id)
r = Array.new
results.each do |result|
if result.agent_id == agent_id
r << result
end
end
return r
end
def filter_logtype(results,logtype_id)
r = Array.new
results.each do |result|
if result.logtype_id == logtype_id
r << result
end
end
return r
end
def filter_loglevel(results,loglevel_id)
r = Array.new
results.each do |result|
if result.loglevel_id <= loglevel_id
r << result
end
end
return r
end
end
diff --git a/src/server/app/views/agents/index.rhtml b/src/server/app/views/agents/index.rhtml
index 5792096..7fa6c48 100644
--- a/src/server/app/views/agents/index.rhtml
+++ b/src/server/app/views/agents/index.rhtml
@@ -1,29 +1,30 @@
<h1>Agents</h1>
<div class="subnav"><%=link_to("Create new Agent #{image_tag("addserver.png", :alt => "add server", :border => "0px")}", :action => "new")%></div>
<div class="clear"></div>
<% for agent in @agents do%>
<div class="agent">
- <%=image_tag("serverup.png")%><a href='#' onclick="$('.agentinfo<%=agent.id%>').toggle();return false"><%=agent.name%></a> : <%=link_to("View Events", :action=>"show", :id=>agent.id)%>
+ <%=image_tag("serverup.png")%><a href='#' onclick="$('.agentinfo<%=agent.id%>').toggle();return false"><%= h agent.name%></a> : <%=link_to("View Events", :action=>"show", :id=>agent.id)%>
<div class="agentinfo<%=agent.id%>" style="display:none; margin-left:30px; background:#FF9; padding: 3px; border: 1px solid #000">
<div class="subnav" style="width:200px;">
Logtypes
<% for logtype in agent.logtypes do%>
- <div class="adendem"><%=logtype.name%></div>
+ <div class="adendem"><%=h logtype.name%></div>
<%end%>
</div>
<div clear></div>
<div class="info">Total Events: <%= agent.events.count %></div>
- <div class="info">Hostname: <%=agent.hostname%></div>
- <div class="info">Listenport: <%=agent.port%></div>
- <div class="info">Key: <%=agent.authkey%></div>
+ <div class="info">Hostname: <%=h agent.hostname%></div>
+ <div class="info">Listenport: <%=h agent.port%></div>
+ <div class="info">Key: <%=h agent.authkey%></div>
+ <div class="info">Agent_id: <%=agent.id%></div>
<div class="info"><%=link_to("edit", :action => "edit", :id => agent.id)%></div>
</div>
</div>
<%end%>
<div class="pagination">
<%= will_paginate @event %>
</div>
\ No newline at end of file
diff --git a/src/server/app/views/agents/search.rhtml b/src/server/app/views/agents/search.rhtml
index 3e2f48b..867e364 100644
--- a/src/server/app/views/agents/search.rhtml
+++ b/src/server/app/views/agents/search.rhtml
@@ -1,16 +1,25 @@
+<div class="rightsearch">
+ <div>
+ <% form_for :search, :url => { :id => params[:id]} do |form| %>
+ <div>Search within Agent</div>
+ <div><%= form.text_field :data, :size => 20, :class => "minisearchbox",:value => params[:aquery] %> </div>
+ <%end%>
+ </div>
+</div>
+<div class="clear"></div>
<h1>Search Results</h1>
<div id="totalhits">Found <%=@total%> matching results</div>
<div id="events">
<% for event in @results do %>
<div class="event">
- <a href="#" onclick="$('.eventinfo<%=event.id%>').toggle();return false"><%= if params[:withepoch] then event.etime else Time.at(event.etime.to_f) end %></a> : <%= event.loglevel.name %> ::
- <%=event.full_event%>
+ <a href="#" onclick="$('.eventinfo<%=event.id%>').toggle();return false"><%= if params[:withepoch] then event.etime else Time.at(event.etime.to_f) end %></a> : <%= h event.loglevel.name %> ::
+ <%=h event.full_event%>
<div class="eventinfo<%=event.id%>" style="display:none; background:#FF9; border:1px solid #000; padding:5px; width:50%">
- <div class="info">Agent: <%=link_to(event.agent.name, :controller => "agents", :action => "show", :id => event.agent.id)%></div>
- <div class="info">Logtype: <%=link_to(event.staticentry.logtype.name, :controller => "logtypes", :action => "show", :id => event.staticentry.logtype.id)%></div>
- <div class="info">Static Entry Id: <%=event.staticentry_id%></div>
+ <div class="info">Agent: <%=link_to(h(event.agent.name), :controller => "agents", :action => "show", :id => event.agent.id)%></div>
+ <div class="info">Logtype: <%=link_to(h(event.staticentry.logtype.name), :controller => "logtypes", :action => "show", :id => event.staticentry.logtype.id)%></div>
+ <div class="info">Static Entry Id: <%= h event.staticentry_id%></div>
</div>
</div>
<%end%>
</div>
<%=will_paginate @results%>
\ No newline at end of file
diff --git a/src/server/app/views/agents/show.rhtml b/src/server/app/views/agents/show.rhtml
index c899ce5..13bb4b4 100644
--- a/src/server/app/views/agents/show.rhtml
+++ b/src/server/app/views/agents/show.rhtml
@@ -1,52 +1,52 @@
<div class="rightsearch">
<div>
<% form_for :search, :url => { :id => params[:id]} do |form| %>
<div>Search within Agent</div>
<div><%= form.text_field :data, :size => 20, :class => "minisearchbox" %> </div>
<%end%>
</div>
</div>
<div class="clear"></div>
-<h1>All Events for <%=@agent.name%></h1>
+<h1>All Events for <%=h @agent.name%></h1>
<div id="filter">
<% if params[:logtype]%>
- Current filter: <%= Logtype.find(params[:logtype]).name%>
+ Current filter: <%= h Logtype.find(params[:logtype]).name%>
<%else%>
Filter by logtype:
<% for type in @agent.logtypes.all do %>
- <%= link_to( type.name, :logtype => type.id, :withepoch => params[:withepoch] )%>
+ <%= link_to( h(type.name), :logtype => type.id, :withepoch => params[:withepoch] )%>
<%end%>
<%end%>
<div class="adendem">
<%= link_to("Clear filter", :logtype => nil, :withepoch => params[:withepoch])%>
</div>
</div>
<div id="events">
-<% for event in @events.reverse do %>
+<% for event in @events do %>
<div class="event">
- <a href="#" onclick="$('.eventinfo<%=event.id%>').toggle();return false"><%= if params[:withepoch] then event.etime else Time.at(event.etime.to_f) end %></a> : <%= link_to(event.loglevel.name, :action => "show", :loglevel => event.loglevel.id, :withepoch => params[:withepoch])%> ::
- <%=event.payload%>
- <div class="eventinfo<%=event.id%>" style="display:none; background:#FF9; border:1px solid #000; padding:5px; width:50%">
- <div class="info">Logtype: <%=link_to(event.staticentry.logtype.name, :controller => "logtypes", :action => "show", :id => event.staticentry.logtype.id)%></div>
- <div class="info">Static Entry Id: <%=event.staticentry_id%></div>
+ <a href="#" onclick="$('.eventinfo<%=event.id%>').toggle();return false"><%= if params[:withepoch] then event.etime else Time.at(event.etime.to_f) end %></a> : <%= link_to(h(event.loglevel.name), :action => "show", :loglevel => event.loglevel.id, :withepoch => params[:withepoch])%> ::
+ <%=h event.payload%>
+ <div class="eventinfo<%=event.id%>" style="display:none; background:#FF9; border:1px solid #000; padding:5px;">
+ <div class="info">Logtype: <%=link_to(h(event.staticentry.logtype.name), :controller => "logtypes", :action => "show", :id => event.staticentry.logtype.id)%></div>
+ <div class="info">Static Entry Id: <%=h event.staticentry_id%></div>
</div>
</div>
<%end%>
</div>
<div class="pagination">
<%= will_paginate @event %>
</div>
<div class="adendem">
Records per page:
<%=link_to "20", :withepoch => params[:withepoch], :page => 1, :perpage => "20" %> |
<%=link_to "50", :withepoch => params[:withepoch], :page => 1, :perpage => "50" %> |
<%=link_to "100", :withepoch => params[:withepoch], :page => 1, :perpage => "100" %> |
<%=link_to "200", :withepoch => params[:withepoch], :page => 1, :perpage => "200" %>
</div>
<%if params[:withepoch]%>
<div class="adendem"><%=link_to "show regular time", :withepoch => nil, :page => params[:page], :perpage => params[:perpage], :logtype => params[:logtype] %></div>
<%else%>
<div class="adendem"><%=link_to "show epoch time", :withepoch => 1, :page => params[:page], :perpage => params[:perpage], :logtype => params[:logtype] %></div>
<%end%>
\ No newline at end of file
diff --git a/src/server/app/views/events/index.rhtml b/src/server/app/views/events/index.rhtml
index d76f684..8aefc86 100644
--- a/src/server/app/views/events/index.rhtml
+++ b/src/server/app/views/events/index.rhtml
@@ -1,17 +1,17 @@
<h1>Events Statistics</h1>
<div class="adendem">Select the log events you would like to see:</div>
<h2>Logtypes</h2>
<ul>
<% for type in @logtypes do%>
- <li><%= link_to(type.name, :action => 'show', :id => type.id)%> :: <%=type.events.count %> total events</ul>
+ <li><%= link_to(h(type.name), :action => 'show', :id => type.id)%> :: <%=type.events.count %> total events</ul>
<%end%>
</ul>
<h2>Agents</h2>
<ul>
<% for agent in @agents do%>
- <li><%=link_to(agent.name, :action => 'show', :id => agent.id)%> [<%=agent.hostname%>] :: <%= agent.events.count%> total events</li>
+ <li><%=link_to(h(agent.name), :action => 'show', :id => agent.id)%> [<%=h agent.hostname%>] :: <%= agent.events.count%> total events</li>
<%end%>
</ul>
<h3><%= link_to('Show all events', :action => 'show')%></h3>
\ No newline at end of file
diff --git a/src/server/app/views/events/show.rhtml b/src/server/app/views/events/show.rhtml
index 04c4c7c..6164972 100644
--- a/src/server/app/views/events/show.rhtml
+++ b/src/server/app/views/events/show.rhtml
@@ -1,36 +1,36 @@
<h1>All Events</h1>
<%unless params[:loglevel].nil?%>
<div class="adendem"><%=link_to("clear filters", :action => "show", :loglevel => nil)%></div>
<%end%>
<div id="events">
-<% for event in @events.reverse do %>
+<% for event in @events do %>
<div class="event">
- <a href="#" onclick="$('.eventinfo<%=event.id%>').toggle();return false"><%= if params[:withepoch] then event.etime else Time.at(event.etime.to_f) end %></a> : <%= link_to(event.loglevel.name, :action => "show", :loglevel => event.loglevel.id, :withepoch => params[:withepoch])%> ::
- <%=event.payload%>
- <div class="eventinfo<%=event.id%>" style="display:none; background:#FF9; border:1px solid #000; padding:5px; width:50%">
- <div class="info">Agent: <%=link_to(event.agent.name, :controller => "agents", :action => "show", :id => event.agent.id)%></div>
- <div class="info">Logtype: <%=link_to(event.staticentry.logtype.name, :controller => "logtypes", :action => "show", :id => event.staticentry.logtype.id)%></div>
- <div class="info">Static Entry Id: <%=event.staticentry_id%></div>
+ <a href="#" onclick="$('.eventinfo<%=event.id%>').toggle();return false"><%= if params[:withepoch] then event.etime else Time.at(event.etime.to_f) end %></a> : <%= link_to(h(event.loglevel.name), :action => "show", :loglevel => event.loglevel.id, :withepoch => params[:withepoch])%> ::
+ <%= h event.payload%>
+ <div class="eventinfo<%=event.id%>" style="display:none; background:#FF9; border:1px solid #000; padding:5px;">
+ <div class="info">Agent: <%=link_to(h(event.agent.name), :controller => "agents", :action => "show", :id => event.agent.id)%></div>
+ <div class="info">Logtype: <%=link_to(h(event.staticentry.logtype.name), :controller => "logtypes", :action => "show", :id => event.staticentry.logtype.id)%></div>
+ <div class="info">Static Entry Id: <%=h event.staticentry_id%></div>
</div>
</div>
<%end%>
</div>
<div class="pagination">
<%= will_paginate @event %>
</div>
<div class="adendem">
Records per page:
<%=link_to "20", :loglevel => params[:loglevel], :withepoch => params[:withepoch], :page => 1, :perpage => "20" %> |
<%=link_to "50", :loglevel => params[:loglevel], :withepoch => params[:withepoch], :page => 1, :perpage => "50" %> |
<%=link_to "100", :loglevel => params[:loglevel], :withepoch => params[:withepoch], :page => 1, :perpage => "100" %> |
<%=link_to "200", :loglevel => params[:loglevel], :withepoch => params[:withepoch], :page => 1, :perpage => "200" %>
</div>
<%if params[:withepoch]%>
<div class="adendem"><%=link_to "show regular time", :withepoch => nil, :loglevel => params[:loglevel], :page => params[:page], :perpage => params[:perpage] %></div>
<%else%>
<div class="adendem"><%=link_to "show epoch time", :withepoch => 1, :loglevel => params[:loglevel], :page => params[:page], :perpage => params[:perpage] %></div>
<%end%>
<div class="adendem"><%=link_to "view by agent", :controller => 'agents', :action => "index" %> | <%=link_to "view by logtype", :controller => 'logtypes', :action => 'index' %></div>
diff --git a/src/server/app/views/logtypes/index.rhtml b/src/server/app/views/logtypes/index.rhtml
index abeaa4d..c723306 100644
--- a/src/server/app/views/logtypes/index.rhtml
+++ b/src/server/app/views/logtypes/index.rhtml
@@ -1,21 +1,22 @@
<h1>Logtypes</h1>
<div class="subnav"><%=link_to("Create new Logtype", :action => "new")%></div>
<div class="clear"></div>
<% for type in @logtypes do%>
<div class="agent">
- <a href='#' onclick="$('.typeinfo<%=type.id%>').toggle();return false"><%=type.name%></a> : <%=link_to("View Events", :action=>"show", :id=>type.id)%>
+ <a href='#' onclick="$('.typeinfo<%=type.id%>').toggle();return false"><%=h type.name%></a> : <%=link_to("View Events", :action=>"show", :id=>type.id)%>
<div class="typeinfo<%=type.id%>" style="display:none; background:#FF9; padding: 3px; border: 1px solid #000">
- <div class="info">Description: <%=type.description%></div>
+ <div class="info">Description: <%=h type.description%></div>
<div class="info">Total Events: <%= type.events.count %></div>
<div class="info">Total Agents: <%=type.agents.count%></div>
+ <div class="info">Logtype_id: <%=type.id%></div>
<div class="info"><%=link_to("edit", :action => "edit", :id => type.id)%></div>
</div>
</div>
<%end%>
<div class="pagination">
<%= will_paginate @logtypes %>
</div>
diff --git a/src/server/app/views/logtypes/search.rhtml b/src/server/app/views/logtypes/search.rhtml
index 3e2f48b..9b97344 100644
--- a/src/server/app/views/logtypes/search.rhtml
+++ b/src/server/app/views/logtypes/search.rhtml
@@ -1,16 +1,24 @@
+<div class="rightsearch">
+ <div>
+ <% form_for :search, :url => { :id => params[:id]} do |form| %>
+ <div>Search within Logtype</div>
+ <div><%= form.text_field :data, :size => 20, :class => "minisearchbox", :value => params[:aquery] %> </div>
+ <%end%>
+ </div>
+</div>
<h1>Search Results</h1>
<div id="totalhits">Found <%=@total%> matching results</div>
<div id="events">
<% for event in @results do %>
<div class="event">
- <a href="#" onclick="$('.eventinfo<%=event.id%>').toggle();return false"><%= if params[:withepoch] then event.etime else Time.at(event.etime.to_f) end %></a> : <%= event.loglevel.name %> ::
- <%=event.full_event%>
+ <a href="#" onclick="$('.eventinfo<%=event.id%>').toggle();return false"><%= if params[:withepoch] then event.etime else Time.at(event.etime.to_f) end %></a> : <%= h event.loglevel.name %> ::
+ <%=h event.full_event%>
<div class="eventinfo<%=event.id%>" style="display:none; background:#FF9; border:1px solid #000; padding:5px; width:50%">
- <div class="info">Agent: <%=link_to(event.agent.name, :controller => "agents", :action => "show", :id => event.agent.id)%></div>
- <div class="info">Logtype: <%=link_to(event.staticentry.logtype.name, :controller => "logtypes", :action => "show", :id => event.staticentry.logtype.id)%></div>
- <div class="info">Static Entry Id: <%=event.staticentry_id%></div>
+ <div class="info">Agent: <%=link_to(h(event.agent.name), :controller => "agents", :action => "show", :id => event.agent.id)%></div>
+ <div class="info">Logtype: <%=link_to(h(event.staticentry).logtype.name, :controller => "logtypes", :action => "show", :id => event.staticentry.logtype.id)%></div>
+ <div class="info">Static Entry Id: <%=h event.staticentry_id%></div>
</div>
</div>
<%end%>
</div>
<%=will_paginate @results%>
\ No newline at end of file
diff --git a/src/server/app/views/logtypes/show.rhtml b/src/server/app/views/logtypes/show.rhtml
index 3e3acfa..0c76c1f 100644
--- a/src/server/app/views/logtypes/show.rhtml
+++ b/src/server/app/views/logtypes/show.rhtml
@@ -1,46 +1,46 @@
<div class="rightsearch">
<div>
<% form_for :search, :url => { :id => params[:id]} do |form| %>
<div>Search within Logtype</div>
<div><%= form.text_field :data, :size => 20, :class => "minisearchbox" %> </div>
<%end%>
</div>
</div>
<div class="clear"></div>
-<h1>All Events for <%=@logtype.name%></h1>
+<h1>All Events for <%=h @logtype.name%></h1>
<div id="filter">
<a href='#' onclick="$('.agentinfo').toggle();return false">View by Agent</a>
<div class="agentinfo" style="display:none; background:#FF9; padding: 3px; border: 1px solid #000">
<% for agent in @logtype.agents do %>
- <div class="info"><%= link_to( agent.name, :controller => 'agents', :action => 'show', :logtype => @logtype.id, :withepoch => params[:withepoch], :id => agent.id )%></div>
+ <div class="info"><%= link_to( h(agent.name), :controller => 'agents', :action => 'show', :logtype => @logtype.id, :withepoch => params[:withepoch], :id => agent.id )%></div>
<%end%>
</div>
</div>
<div id="events">
-<% for event in @events.reverse do %>
+<% for event in @events do %>
<div class="event">
- <a href="#" onclick="$('.eventinfo<%=event.id%>').toggle();return false"><%= if params[:withepoch] then event.etime else Time.at(event.etime.to_f) end %></a> : <%= link_to(event.loglevel.name, :action => "show", :loglevel => event.loglevel.id, :withepoch => params[:withepoch])%> ::
- <%=event.payload%>
- <div class="eventinfo<%=event.id%>" style="display:none; background:#FF9; border:1px solid #000; padding:5px; width:50%">
- <div class="info">Agent: <%=link_to(event.agent.name, :controller => "agents", :action => "show", :id => event.agent.id)%></div>
- <div class="info">Static Entry Id: <%=event.staticentry_id%></div>
+ <a href="#" onclick="$('.eventinfo<%=event.id%>').toggle();return false"><%= if params[:withepoch] then event.etime else Time.at(event.etime.to_f) end %></a> : <%= link_to(h(event.loglevel.name), :action => "show", :loglevel => event.loglevel.id, :withepoch => params[:withepoch])%> ::
+ <%=h event.payload%>
+ <div class="eventinfo<%=event.id%>" style="display:none; background:#FF9; border:1px solid #000; padding:5px;">
+ <div class="info">Agent: <%=link_to(h(event.agent.name), :controller => "agents", :action => "show", :id => event.agent.id)%></div>
+ <div class="info">Static Entry Id: <%=h event.staticentry_id%></div>
</div>
</div>
<%end%>
</div>
<div class="pagination">
<%= will_paginate @event %>
</div>
<div class="adendem">
Records per page:
<%=link_to "20", :withepoch => params[:withepoch], :page => 1, :perpage => "20" %> |
<%=link_to "50", :withepoch => params[:withepoch], :page => 1, :perpage => "50" %> |
<%=link_to "100", :withepoch => params[:withepoch], :page => 1, :perpage => "100" %> |
<%=link_to "200", :withepoch => params[:withepoch], :page => 1, :perpage => "200" %>
</div>
<%if params[:withepoch]%>
<div class="adendem"><%=link_to "show regular time", :withepoch => nil, :page => params[:page], :perpage => params[:perpage] %></div>
<%else%>
<div class="adendem"><%=link_to "show epoch time", :withepoch => 1, :page => params[:page], :perpage => params[:perpage] %></div>
<%end%>
\ No newline at end of file
diff --git a/src/server/app/views/search/show.rhtml b/src/server/app/views/search/show.rhtml
index 3e2f48b..cb9a37d 100644
--- a/src/server/app/views/search/show.rhtml
+++ b/src/server/app/views/search/show.rhtml
@@ -1,16 +1,16 @@
<h1>Search Results</h1>
<div id="totalhits">Found <%=@total%> matching results</div>
<div id="events">
<% for event in @results do %>
<div class="event">
- <a href="#" onclick="$('.eventinfo<%=event.id%>').toggle();return false"><%= if params[:withepoch] then event.etime else Time.at(event.etime.to_f) end %></a> : <%= event.loglevel.name %> ::
- <%=event.full_event%>
+ <a href="#" onclick="$('.eventinfo<%=event.id%>').toggle();return false"><%= if params[:withepoch] then event.etime else Time.at(event.etime.to_f) end %></a> : <%= h event.loglevel.name %> ::
+ <%=h event.full_event%>
<div class="eventinfo<%=event.id%>" style="display:none; background:#FF9; border:1px solid #000; padding:5px; width:50%">
- <div class="info">Agent: <%=link_to(event.agent.name, :controller => "agents", :action => "show", :id => event.agent.id)%></div>
- <div class="info">Logtype: <%=link_to(event.staticentry.logtype.name, :controller => "logtypes", :action => "show", :id => event.staticentry.logtype.id)%></div>
- <div class="info">Static Entry Id: <%=event.staticentry_id%></div>
+ <div class="info">Agent: <%=link_to(h(event.agent.name), :controller => "agents", :action => "show", :id => event.agent.id)%></div>
+ <div class="info">Logtype: <%=link_to(h(event.staticentry.logtype.name), :controller => "logtypes", :action => "show", :id => event.staticentry.logtype.id)%></div>
+ <div class="info">Static Entry Id: <%=h event.staticentry_id%></div>
</div>
</div>
<%end%>
</div>
<%=will_paginate @results%>
\ No newline at end of file
diff --git a/src/server/public/stylesheets/main.css b/src/server/public/stylesheets/main.css
index 5becf63..4cbaf3e 100644
--- a/src/server/public/stylesheets/main.css
+++ b/src/server/public/stylesheets/main.css
@@ -1,231 +1,233 @@
body {
background: #fff;
color: #000;
margin: 0px;
padding: 0px;
color: #333;
font-weight:bold;
font-family: serif;
}
a {
text-decoration: none;
color: #660033;
}
a:hover {
background: #000033;
color: #fff;
padding: 2px;
}
#container {
padding: 0px;
margin: auto;
width: 900px;
}
#header {
width: 100%;
margin: 0px;
height: 95px;
background: #333;
border-bottom: solid 6px #000;
color:#fff;
}
#logo {
position: absolute;
padding-top: 20px;
padding-left: 45px;
font-weight:bold;
font-size: 55px;
color: #fff;
}
#search {
text-align: right;
padding-top: 20px;
padding-right: 50px;
}
.searchbox {
background: #663366;
border: 1px solid #000;
color: #fff;
font-size: 20px;
padding: 2px;
font-weight: none;
}
#eventlist {
min-height: 350px;
_height: 350px;
}
#topnav a {
background: #000;
padding: 4px;
padding-bottom: 4px;
padding-left: 6px;
padding-right: 6px;
color: #fff;
border-left: solid 2px #000033;
border-right: solid 2px #000033;
border-bottom: solid 2px #000033;
}
#topnav a:hover {
background: #666;
padding: 4px;
padding-bottom: 4px;
padding-left: 6px;
padding-right: 6px;
color: #fff;
border-left: solid 2px #000033;
border-right: solid 2px #000033;
border-bottom: solid 2px #000033;
}
.topnav {
background: #666;
padding: 2px;
padding-bottom: 4px;
padding-left: 6px;
padding-right: 6px;
color: #fff;
border-left: solid 2px #000033;
border-right: solid 2px #000033;
border-bottom: solid 2px #000033;
}
#topnav {
font-size: 20px;
padding: 2px;
padding-bottom: 4px;
padding-left: 6px;
padding-right: 6px;
color: #fff;
}
#main {
min-height: 400px;
_height: 400px; /* IE min-height hack */
}
#footer {
text-align: center;
width: 900px;
border-top: 2px solid #000;
padding-top: 15px;
}
#notice {
margin-top: 10px;
width: 100%;
background: #09F;
color: #000;
padding: 10px;
border: 1px solid #333;
}
#error {
margin-top: 10px;
width: 100%;
background: #F00;
color: #000;
padding: 10px;
border: 1px solid #333;
}
#form {
width: 350px;
margin: auto;
}
.submitbutton {
background: #660033;
color: #fff;
border: 3px solid #000;
padding: 6px;
}
.fbox {
background: #ffff55;
border: 1px solid #333;
padding: 2px;
}
.clear {
clear:both;
}
.adendem {
font-size: 14px;
font-weight: normal;
}
.in20 {
padding-left: 20px;
padding-right: 20px;
}
.errorExplanation {
width: 800px;
margin: auto;
padding: 3px;
padding-left: 10px;
padding-right: 10px;
background: #ffff55;
border: 1px solid #333;
margin-bottom: 10px;
}
.subnav {
float:right;
}
.agent {
margin-top: 10px;
padding: 2px;
}
.result {
padding: 5px;
}
.advancedsearch {
display: none;
background:#FF9;
padding: 3px;
border: 1px solid #000
}
-.event {
-
+.event{
+ background: #fff;
+ margin-bottom: 10px;
}
+
.event a {
color:#333;
}
.event a:hover {
color:#333;
background: #aaa;
}
#totalhits {
margin-bottom: 10px;
font-size: 14px;
}
.mainsearchbox {
background: #FF9;
border: solid 1px #000;
font-size: 20px;
padding: 2px;
font-weight: none;
}
.searchsubmitbutton {
background: #660033;
color: #fff;
border: 1px solid #000;
padding: 6px;
height: 28px;
}
.rightsearch {
float:right;
text-align: right;
}
.minisearchbox {
background: #FF9;
border: 1px solid #000;
}
\ No newline at end of file
|
parabuzzle/cistern
|
4dc2491500ab776115b70f25efb512dbcb49ff3c
|
Fixed up the tests
|
diff --git a/src/server/test/fixtures/agents.yml b/src/server/test/fixtures/agents.yml
index 3980eb1..0af6bb7 100644
--- a/src/server/test/fixtures/agents.yml
+++ b/src/server/test/fixtures/agents.yml
@@ -1,20 +1,20 @@
# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
# one:
# column: value
#
# two:
# column: value
agent:
id: 1
name: agent
hostname: agent1.corp.cistern.com
port: 9845
- key: unused
+ authkey: 123
#invalidhostname:
# id: 2
# name: invalidagent
# hostname: agent1.corp
# port: 9845
# key: unused
diff --git a/src/server/test/fixtures/events.yml b/src/server/test/fixtures/events.yml
index aa8cf76..0ea0612 100644
--- a/src/server/test/fixtures/events.yml
+++ b/src/server/test/fixtures/events.yml
@@ -1,38 +1,39 @@
# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
# one:
# column: value
#
# two:
# column: value
event1:
payload: agent1
staticentry_id: 85d229332bf72d4539372498264300d6
agent_id: 1
- loglevel: 0
- time: 1249062105.06911
+ loglevel_id: 1
+ logtype_id: 1
+ etime: 1249062105.06911
#invalidmissingagent:
# payload: agent1
# staticentry_id:
# agent_id:
# type_id:
# loglevel: 0
# time: 1249062105.06911
#
#invalidmissingloglevel:
# payload: agent1
# staticentry_id:
# agent_id: 1
# type_id:
# loglevel:
# time: 1249062105.06911
#
#invalidmissingtime:
# payload: agent1
# staticentry_id:
# agent_id: 1
# type_id:
# loglevel: 0
# time:
\ No newline at end of file
diff --git a/src/server/test/fixtures/loglevels.yml b/src/server/test/fixtures/loglevels.yml
index 5bf0293..c04d63a 100644
--- a/src/server/test/fixtures/loglevels.yml
+++ b/src/server/test/fixtures/loglevels.yml
@@ -1,7 +1,11 @@
# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
+error:
+ id: 1
+ name: ERROR
+
# one:
# column: value
#
# two:
# column: value
diff --git a/src/server/test/fixtures/logtypes.yml b/src/server/test/fixtures/logtypes.yml
index b834624..02f56fc 100644
--- a/src/server/test/fixtures/logtypes.yml
+++ b/src/server/test/fixtures/logtypes.yml
@@ -1,11 +1,12 @@
# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
# one:
# column: value
#
# two:
# column: value
apache:
id: 1
name: apache
+ description: apache logs
diff --git a/src/server/test/unit/agent_test.rb b/src/server/test/unit/agent_test.rb
index 9e98b60..b1a9993 100644
--- a/src/server/test/unit/agent_test.rb
+++ b/src/server/test/unit/agent_test.rb
@@ -1,36 +1,36 @@
require 'test_helper'
class AgentTest < ActiveSupport::TestCase
# Replace this with your real tests.
test "the truth" do
assert true
end
test "valid agent creation" do
a = Agent.new
a.name = "valid"
a.hostname = "agent2.corp.cistern.com"
a.port = "9845"
- a.key = "unused"
+ a.authkey = "unused"
assert a.save
end
- test "invalid agent creation - bad hostname" do
- a = Agent.new
- a.name = "valid"
- a.hostname = "agent2.corp.cistern"
- a.port = "9845"
- a.key = "unused"
- assert !a.save
- end
+ #test "invalid agent creation - bad hostname" do
+ # a = Agent.new
+ # a.name = "valid"
+ # a.hostname = "agent2.corp.cistern"
+ # a.port = "9845"
+ # a.authkey = "unused"
+ # assert !a.save
+ #end
test "invalid agent creation - missing port" do
a = Agent.new
a.name = "valid"
a.hostname = "agent3.corp.cistern.com"
a.port = ""
- a.key = "unused"
+ a.authkey = "unused"
assert !a.save
end
end
diff --git a/src/server/test/unit/event_test.rb b/src/server/test/unit/event_test.rb
index 35b61dd..d4a3cd9 100644
--- a/src/server/test/unit/event_test.rb
+++ b/src/server/test/unit/event_test.rb
@@ -1,64 +1,64 @@
require 'test_helper'
class EventTest < ActiveSupport::TestCase
# Replace this with your real tests.
test "the truth" do
assert true
end
test "new event" do
e = Event.new
e.payload = "agent3"
e.staticentry_id = "85d229332bf72d4539372498264300d6"
e.agent_id = 1
e.loglevel_id = 1
e.logtype_id = 1
- e.time = 1249062105.06911
+ e.etime = 1249062105.06911
assert e.save
end
test "invalid new event - missing agent_id" do
e = Event.new
e.payload = "agent3"
e.staticentry_id = "85d229332bf72d4539372498264300d6"
e.agent_id = nil
e.loglevel_id = 1
e.logtype_id = 1
- e.time = 1249062105.06911
+ e.etime = 1249062105.06911
assert !e.save
end
test "invalid new event - missing loglevel" do
e = Event.new
e.payload = "agent3"
e.staticentry_id = "85d229332bf72d4539372498264300d6"
e.agent_id = 1
e.loglevel_id = nil
e.logtype_id = 1
- e.time = 1249062105.06911
+ e.etime = 1249062105.06911
assert !e.save
end
test "invalid new event - missing time" do
e = Event.new
e.payload = "agent3"
e.staticentry_id = "85d229332bf72d4539372498264300d6"
e.agent_id = 1
e.loglevel_id = 1
- e.time = nil
+ e.etime = nil
e.logtype_id = 1
assert !e.save
end
test "invalid new event - missing logtype_id" do
e = Event.new
e.payload = "agent3"
e.staticentry_id = "85d229332bf72d4539372498264300d6"
e.agent_id = 1
e.loglevel_id = 1
- e.time = 1249062105.06911
+ e.etime = 1249062105.06911
e.logtype_id = nil
assert !e.save
end
end
|
parabuzzle/cistern
|
89132feb2c2a86be58b9ca9b18d670b0c02499bb
|
Changed order in view to be oldest at the bottom (more like a log)
|
diff --git a/src/server/app/views/agents/show.rhtml b/src/server/app/views/agents/show.rhtml
index ff45d2c..c899ce5 100644
--- a/src/server/app/views/agents/show.rhtml
+++ b/src/server/app/views/agents/show.rhtml
@@ -1,52 +1,52 @@
<div class="rightsearch">
<div>
<% form_for :search, :url => { :id => params[:id]} do |form| %>
<div>Search within Agent</div>
<div><%= form.text_field :data, :size => 20, :class => "minisearchbox" %> </div>
<%end%>
</div>
</div>
<div class="clear"></div>
<h1>All Events for <%=@agent.name%></h1>
<div id="filter">
<% if params[:logtype]%>
Current filter: <%= Logtype.find(params[:logtype]).name%>
<%else%>
Filter by logtype:
<% for type in @agent.logtypes.all do %>
<%= link_to( type.name, :logtype => type.id, :withepoch => params[:withepoch] )%>
<%end%>
<%end%>
<div class="adendem">
<%= link_to("Clear filter", :logtype => nil, :withepoch => params[:withepoch])%>
</div>
</div>
<div id="events">
-<% for event in @events do %>
+<% for event in @events.reverse do %>
<div class="event">
<a href="#" onclick="$('.eventinfo<%=event.id%>').toggle();return false"><%= if params[:withepoch] then event.etime else Time.at(event.etime.to_f) end %></a> : <%= link_to(event.loglevel.name, :action => "show", :loglevel => event.loglevel.id, :withepoch => params[:withepoch])%> ::
<%=event.payload%>
<div class="eventinfo<%=event.id%>" style="display:none; background:#FF9; border:1px solid #000; padding:5px; width:50%">
<div class="info">Logtype: <%=link_to(event.staticentry.logtype.name, :controller => "logtypes", :action => "show", :id => event.staticentry.logtype.id)%></div>
<div class="info">Static Entry Id: <%=event.staticentry_id%></div>
</div>
</div>
<%end%>
</div>
<div class="pagination">
<%= will_paginate @event %>
</div>
<div class="adendem">
Records per page:
<%=link_to "20", :withepoch => params[:withepoch], :page => 1, :perpage => "20" %> |
<%=link_to "50", :withepoch => params[:withepoch], :page => 1, :perpage => "50" %> |
<%=link_to "100", :withepoch => params[:withepoch], :page => 1, :perpage => "100" %> |
<%=link_to "200", :withepoch => params[:withepoch], :page => 1, :perpage => "200" %>
</div>
<%if params[:withepoch]%>
<div class="adendem"><%=link_to "show regular time", :withepoch => nil, :page => params[:page], :perpage => params[:perpage], :logtype => params[:logtype] %></div>
<%else%>
<div class="adendem"><%=link_to "show epoch time", :withepoch => 1, :page => params[:page], :perpage => params[:perpage], :logtype => params[:logtype] %></div>
<%end%>
\ No newline at end of file
diff --git a/src/server/app/views/events/show.rhtml b/src/server/app/views/events/show.rhtml
index 86afb20..04c4c7c 100644
--- a/src/server/app/views/events/show.rhtml
+++ b/src/server/app/views/events/show.rhtml
@@ -1,36 +1,36 @@
<h1>All Events</h1>
<%unless params[:loglevel].nil?%>
<div class="adendem"><%=link_to("clear filters", :action => "show", :loglevel => nil)%></div>
<%end%>
<div id="events">
-<% for event in @events do %>
+<% for event in @events.reverse do %>
<div class="event">
<a href="#" onclick="$('.eventinfo<%=event.id%>').toggle();return false"><%= if params[:withepoch] then event.etime else Time.at(event.etime.to_f) end %></a> : <%= link_to(event.loglevel.name, :action => "show", :loglevel => event.loglevel.id, :withepoch => params[:withepoch])%> ::
<%=event.payload%>
<div class="eventinfo<%=event.id%>" style="display:none; background:#FF9; border:1px solid #000; padding:5px; width:50%">
<div class="info">Agent: <%=link_to(event.agent.name, :controller => "agents", :action => "show", :id => event.agent.id)%></div>
<div class="info">Logtype: <%=link_to(event.staticentry.logtype.name, :controller => "logtypes", :action => "show", :id => event.staticentry.logtype.id)%></div>
<div class="info">Static Entry Id: <%=event.staticentry_id%></div>
</div>
</div>
<%end%>
</div>
<div class="pagination">
<%= will_paginate @event %>
</div>
<div class="adendem">
Records per page:
<%=link_to "20", :loglevel => params[:loglevel], :withepoch => params[:withepoch], :page => 1, :perpage => "20" %> |
<%=link_to "50", :loglevel => params[:loglevel], :withepoch => params[:withepoch], :page => 1, :perpage => "50" %> |
<%=link_to "100", :loglevel => params[:loglevel], :withepoch => params[:withepoch], :page => 1, :perpage => "100" %> |
<%=link_to "200", :loglevel => params[:loglevel], :withepoch => params[:withepoch], :page => 1, :perpage => "200" %>
</div>
<%if params[:withepoch]%>
<div class="adendem"><%=link_to "show regular time", :withepoch => nil, :loglevel => params[:loglevel], :page => params[:page], :perpage => params[:perpage] %></div>
<%else%>
<div class="adendem"><%=link_to "show epoch time", :withepoch => 1, :loglevel => params[:loglevel], :page => params[:page], :perpage => params[:perpage] %></div>
<%end%>
<div class="adendem"><%=link_to "view by agent", :controller => 'agents', :action => "index" %> | <%=link_to "view by logtype", :controller => 'logtypes', :action => 'index' %></div>
diff --git a/src/server/app/views/logtypes/show.rhtml b/src/server/app/views/logtypes/show.rhtml
index 26de066..3e3acfa 100644
--- a/src/server/app/views/logtypes/show.rhtml
+++ b/src/server/app/views/logtypes/show.rhtml
@@ -1,46 +1,46 @@
<div class="rightsearch">
<div>
<% form_for :search, :url => { :id => params[:id]} do |form| %>
<div>Search within Logtype</div>
<div><%= form.text_field :data, :size => 20, :class => "minisearchbox" %> </div>
<%end%>
</div>
</div>
<div class="clear"></div>
<h1>All Events for <%=@logtype.name%></h1>
<div id="filter">
<a href='#' onclick="$('.agentinfo').toggle();return false">View by Agent</a>
<div class="agentinfo" style="display:none; background:#FF9; padding: 3px; border: 1px solid #000">
<% for agent in @logtype.agents do %>
<div class="info"><%= link_to( agent.name, :controller => 'agents', :action => 'show', :logtype => @logtype.id, :withepoch => params[:withepoch], :id => agent.id )%></div>
<%end%>
</div>
</div>
<div id="events">
-<% for event in @events do %>
+<% for event in @events.reverse do %>
<div class="event">
<a href="#" onclick="$('.eventinfo<%=event.id%>').toggle();return false"><%= if params[:withepoch] then event.etime else Time.at(event.etime.to_f) end %></a> : <%= link_to(event.loglevel.name, :action => "show", :loglevel => event.loglevel.id, :withepoch => params[:withepoch])%> ::
<%=event.payload%>
<div class="eventinfo<%=event.id%>" style="display:none; background:#FF9; border:1px solid #000; padding:5px; width:50%">
<div class="info">Agent: <%=link_to(event.agent.name, :controller => "agents", :action => "show", :id => event.agent.id)%></div>
<div class="info">Static Entry Id: <%=event.staticentry_id%></div>
</div>
</div>
<%end%>
</div>
<div class="pagination">
<%= will_paginate @event %>
</div>
<div class="adendem">
Records per page:
<%=link_to "20", :withepoch => params[:withepoch], :page => 1, :perpage => "20" %> |
<%=link_to "50", :withepoch => params[:withepoch], :page => 1, :perpage => "50" %> |
<%=link_to "100", :withepoch => params[:withepoch], :page => 1, :perpage => "100" %> |
<%=link_to "200", :withepoch => params[:withepoch], :page => 1, :perpage => "200" %>
</div>
<%if params[:withepoch]%>
<div class="adendem"><%=link_to "show regular time", :withepoch => nil, :page => params[:page], :perpage => params[:perpage] %></div>
<%else%>
<div class="adendem"><%=link_to "show epoch time", :withepoch => 1, :page => params[:page], :perpage => params[:perpage] %></div>
<%end%>
\ No newline at end of file
|
parabuzzle/cistern
|
0fed3a3359faa27391c8695f164fc6875e477e80
|
Small api change big break
|
diff --git a/src/agent/agent.rb b/src/agent/agent.rb
index 8bf5d7c..100975e 100644
--- a/src/agent/agent.rb
+++ b/src/agent/agent.rb
@@ -1,28 +1,58 @@
require 'rubygems'
require 'eventmachine'
require 'lib/modules.rb'
require 'socket'
+require 'file/tail'
+include File::Tail
include Socket::Constants
+BREAK = "__1_BB"
+VALUE = "__1_VV"
+CHECKSUM = "__1_CC"
+FINISH = "__1_EE"
+
+filename = "/var/logs/auth.log"
+authkey = "55bef2e25cc000d3c0d55d8ae27b6aeb"
+agent_id = 1
+logtype_id = 1
socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
sockaddr = Socket.pack_sockaddr_in( 9845, '127.0.0.1' )
socket.connect( sockaddr )
-socket.write( "GET / HTTP/1.0\r\n\r\n" )
-loop do
- #socket.write("\n")
- socket.write('Hello there')
+
+def send_event(entry)
+ event = Hash.new
+ e = String.new
+
+ d = entry[0,16].split(' ')
+ m = d[2].split(':')
+ etime = Time.local(Time.now.year,d[0],d[1],m[0],m[1],m[2]).to_i
+ loglevel_id = 4
+ payload = 'EVENT/000/' + event.gsub(data[0,16], '')
+ static = "<<<EVENT>>>"
+
+ event.store("authkey", authkey)
+ event.store("logtype_id", logtype_id)
+ event.store("agent_id", agent_id)
+ event.store("loglevel_id", loglevel_id)
+ event.store("etime", etime)
+ event.store("data", static)
+ event.store("payload", payload)
+
+ event.each do |key, val|
+ e = e + key.to_s + VALUE + val.to_s + BREAK
+ end
+ e = e + CHECKSUM + Digest::MD5.hexdigest(e) + FINISH
+
+ socket.write(e)
+end
+
+
+File.open(filename) do |log|
+ log.extend(File::Tail)
+ log.interval = 1
+ log.backward(0)
+ log.tail { |line| send_event(line) }
end
-# EventMachine::run {
-# connection = EventMachine::connect("localhost", 9850, CommandServer)
-# puts "connected"
-# connection.send_data "_1_1_SS::#{`ps -A | grep ruby`}::EE_1_1_"
-#
-# #connection.close_connection
-# #EventMachine::stop_event_loop
-#
-# }
-# puts "The event loop has ended"
-#
\ No newline at end of file
diff --git a/src/agent/logsender.rb b/src/agent/logsender.rb
index 4cecb62..cf9acd5 100644
--- a/src/agent/logsender.rb
+++ b/src/agent/logsender.rb
@@ -1,57 +1,57 @@
require 'socket'
require 'yaml'
require 'digest/md5'
include Socket::Constants
@break = "__1_BB"
@value = "__1_VV"
@checksum = "__1_CC"
def close_tx(socket)
socket.write("__1_EE")
end
def newvalbr(socket)
socket.write("__1_BB")
end
def valbr(socket)
socket.write("__1_VV")
end
def checkbr(socket)
socket.write("__1_CC")
end
socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
sockaddr = Socket.pack_sockaddr_in( 9845, '127.0.0.1' )
socket.connect( sockaddr )
#Things you need...
#data - static data
#logtype_id - logtype
#loglevel - The log level of the event
#time - the original time of the event
#payload - The dynamic data for the event (format - NAME=value)
#agent_id - The reporting agent's id
#
#The entire sting should have a checksum or it will be thrown out
event = Hash.new
event.store("authkey", "55bef2e25cc000d3c0d55d8ae27b6aeb")
event.store("data","rotating events log for <<<NAME>>>")
event.store("logtype_id", 3)
event.store("loglevel_id", 4)
event.store("etime", Time.now.to_f)
-event.store("payload", "NAME=jboss")
+event.store("payload", "NAME/000/jboss")
event.store("agent_id", 1)
e = String.new
event.each do |key, val|
e = e + key.to_s + @value + val.to_s + @break
end
e = e + @checksum + Digest::MD5.hexdigest(e) + "__1_EE"
puts e
socket.write(e)
diff --git a/src/server/app/helpers/application_helper.rb b/src/server/app/helpers/application_helper.rb
index e81a936..4738145 100644
--- a/src/server/app/helpers/application_helper.rb
+++ b/src/server/app/helpers/application_helper.rb
@@ -1,63 +1,63 @@
# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
#Return events array with payload field populated with full event
def rebuildevents(events)
@events = Array.new
events.each do |e|
e.payload = rebuildevent(e)
@events << e
end
return @events
end
#Return a string of replaced static entry keys based on event's payload
def rebuildevent(e)
if USEMEMCACHE != true
static = Staticentry.find(e.staticentry.id)
else
static = Staticentry.get_cache(e.staticentry.id)
end
entries = e.payload.split(',')
hash = Hash.new
entries.each do |m|
- map = m.split('=')
+ map = m.split('/000/')
hash.store('<<<' + map[0] + '>>>',map[1])
end
p = static.data
hash.each do |key, val|
p = p.gsub(key,val)
end
return p
end
def filter_agent(results,agent_id)
r = Array.new
results.each do |result|
if result.agent_id == agent_id
r << result
end
end
return r
end
def filter_logtype(results,logtype_id)
r = Array.new
results.each do |result|
if result.logtype_id == logtype_id
r << result
end
end
return r
end
def filter_loglevel(results,loglevel_id)
r = Array.new
results.each do |result|
if result.loglevel_id <= loglevel_id
r << result
end
end
return r
end
end
|
parabuzzle/cistern
|
a3b96b64a38d162e799250dcd6f8d4967a2b70d3
|
Performance tuning - added cached check in logcollector
|
diff --git a/src/server/lib/modules/collection_server.rb b/src/server/lib/modules/collection_server.rb
index 82d46ce..246b018 100644
--- a/src/server/lib/modules/collection_server.rb
+++ b/src/server/lib/modules/collection_server.rb
@@ -1,77 +1,85 @@
module CollectionServer
#TODO: Checksum check should be wrapped in to an exception and then and handled that way in receive_data
#Set buffer delimiters
@@break = '__1_BB'
@@value = '__1_VV'
@@finish = '__1_EE'
def check_key(agent, key)
if agent.authkey != key
return false
else
return true
end
end
#Write a log entry
def log_entry(line)
raw = line.split(@@break)
map = Hash.new
raw.each do |keys|
parts = keys.split(@@value)
map.store(parts[0],parts[1])
end
- static = Logtype.find(map['logtype_id']).staticentries.new
- static.data = map['data']
- static.save
+ unless USEMEMCACHE != true
+ if Staticentry.get_cache(Digest::MD5.hexdigest(map['data'] + map['logtype_id'].to_s)).nil?
+ static = Logtype.find(map['logtype_id']).staticentries.new
+ static.data = map['data']
+ static.save
+ end
+ else
+ static = Logtype.find(map['logtype_id']).staticentries.new
+ static.data = map['data']
+ static.save
+ end
unless USEMEMCACHE != true
static = Staticentry.get_cache(Digest::MD5.hexdigest(map['data'] + map['logtype_id'].to_s))
else
static = Staticentry.find(Digest::MD5.hexdigest(map['data'] + map['logtype_id'].to_s))
end
event = static.events.new
event.etime = map['etime']
event.loglevel_id = map['loglevel_id']
event.payload = map['payload']
event.logtype_id = map['logtype_id']
event.agent_id = map['agent_id']
if check_key(Agent.find(map['agent_id']), map['authkey'])
event.save
else
ActiveRecord::Base.logger.debug "Event dropped -- invalid agent authkey sent"
end
port, ip = Socket.unpack_sockaddr_in(get_peername)
host = Socket.getaddrinfo(ip, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME)[0][2]
ActiveRecord::Base.logger.debug "New event logged from #{host} \n -- Log data: #{line}"
end
#Do this when a connection is initialized
def post_init
port, ip = Socket.unpack_sockaddr_in(get_peername)
host = Socket.getaddrinfo(ip, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME)[0][2]
ActiveRecord::Base.logger.info "-- Collector connection established from #{host}"
end
#Do this when data is received
def receive_data(data)
(@buffer ||= BufferedTokenizer.new(delimiter = "__1_EE")).extract(data).each do |line|
if line.valid?
log_entry(line)
else
port, ip = Socket.unpack_sockaddr_in(get_peername)
host = Socket.getaddrinfo(ip, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME)[0][2]
ActiveRecord::Base.logger.error "Dropped log entry from #{host} - checksum invalid"
end
end
end
#Do this when a connection is closed by a peer
def unbind
ActiveRecord::Base.logger.info "-- Collector connection closed by a peer"
end
end
\ No newline at end of file
|
parabuzzle/cistern
|
e404fc613ff391f7a35059ff59a044bf47b31d51
|
Implemented memcache for staticentry caching on event rebuild
|
diff --git a/.gitignore b/.gitignore
index fe383b9..b9d47a8 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,7 +1,9 @@
*.log
*.pid
*.sqlite3
src/server/config/database.yml
src/server/config/daemons.yml
src/server/config/collectors.yml
+src/server/config/cistern.yml
+src/server/config/memcached.yml
src/server/index
diff --git a/README b/README
index 74f7feb..27d19d8 100644
--- a/README
+++ b/README
@@ -1,23 +1,24 @@
Cistern - [http://parabuzzle.github.com/cistern]
DEFINED: (cis.tern) - A receptacle for holding water or other liquid, especially a tank for catching and storing rainwater.
Cistern is a centralized log collection application, plain and simple. It's like a better syslog.
Cistern is a lightweight server that collects log events and displays them in a useful way. The application collects events from many different sources and allows viewing and graphing of that data for admins and developers.
The application was born out of need for a place to allow developers to view logs on production machines without a need for the developer to have access to the production environment.
Gem Requirements:
* eventmachine
* rails-2.3.3
* mysql
* daemons
* ferret
* memcached
+* cached_model
External Application Requirements:
* MySQL >=5
* Memcached
Cistern is licensed under the MIT license. Please see the LICENSE file provided in the latest source tree for latest license terms and usage.
\ No newline at end of file
diff --git a/src/agent/logsender.rb b/src/agent/logsender.rb
index 7f3f8dd..4cecb62 100644
--- a/src/agent/logsender.rb
+++ b/src/agent/logsender.rb
@@ -1,60 +1,57 @@
require 'socket'
require 'yaml'
require 'digest/md5'
include Socket::Constants
@break = "__1_BB"
@value = "__1_VV"
@checksum = "__1_CC"
def close_tx(socket)
socket.write("__1_EE")
end
def newvalbr(socket)
socket.write("__1_BB")
end
def valbr(socket)
socket.write("__1_VV")
end
def checkbr(socket)
socket.write("__1_CC")
end
socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
sockaddr = Socket.pack_sockaddr_in( 9845, '127.0.0.1' )
socket.connect( sockaddr )
#Things you need...
#data - static data
#logtype_id - logtype
#loglevel - The log level of the event
#time - the original time of the event
#payload - The dynamic data for the event (format - NAME=value)
#agent_id - The reporting agent's id
#
#The entire sting should have a checksum or it will be thrown out
event = Hash.new
-event.store("authkey", "111")
-event.store("data","Error log in <<<NAME>>> module")
-event.store("logtype_id", 1)
-event.store("loglevel_id", 2)
+event.store("authkey", "55bef2e25cc000d3c0d55d8ae27b6aeb")
+event.store("data","rotating events log for <<<NAME>>>")
+event.store("logtype_id", 3)
+event.store("loglevel_id", 4)
event.store("etime", Time.now.to_f)
-event.store("payload", "NAME=Biff")
+event.store("payload", "NAME=jboss")
event.store("agent_id", 1)
e = String.new
event.each do |key, val|
e = e + key.to_s + @value + val.to_s + @break
end
-puts e
e = e + @checksum + Digest::MD5.hexdigest(e) + "__1_EE"
puts e
socket.write(e)
-socket.write(e)
-socket.write(e)
diff --git a/src/server/app/helpers/application_helper.rb b/src/server/app/helpers/application_helper.rb
index ab8f71d..e81a936 100644
--- a/src/server/app/helpers/application_helper.rb
+++ b/src/server/app/helpers/application_helper.rb
@@ -1,59 +1,63 @@
# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
#Return events array with payload field populated with full event
def rebuildevents(events)
@events = Array.new
events.each do |e|
e.payload = rebuildevent(e)
@events << e
end
return @events
end
#Return a string of replaced static entry keys based on event's payload
def rebuildevent(e)
- static = e.staticentry
+ if USEMEMCACHE != true
+ static = Staticentry.find(e.staticentry.id)
+ else
+ static = Staticentry.get_cache(e.staticentry.id)
+ end
entries = e.payload.split(',')
hash = Hash.new
entries.each do |m|
map = m.split('=')
hash.store('<<<' + map[0] + '>>>',map[1])
end
p = static.data
hash.each do |key, val|
p = p.gsub(key,val)
end
return p
end
def filter_agent(results,agent_id)
r = Array.new
results.each do |result|
if result.agent_id == agent_id
r << result
end
end
return r
end
def filter_logtype(results,logtype_id)
r = Array.new
results.each do |result|
if result.logtype_id == logtype_id
r << result
end
end
return r
end
def filter_loglevel(results,loglevel_id)
r = Array.new
results.each do |result|
if result.loglevel_id <= loglevel_id
r << result
end
end
return r
end
end
diff --git a/src/server/app/models/staticentry.rb b/src/server/app/models/staticentry.rb
index bc87734..da80d07 100644
--- a/src/server/app/models/staticentry.rb
+++ b/src/server/app/models/staticentry.rb
@@ -1,17 +1,15 @@
class Staticentry < ActiveRecord::Base
acts_as_ferret
-
+ acts_as_cached :ttl => 4.hours
has_many :events
belongs_to :logtype
has_many :loglevels, :through => :entries
- #TODO: Make the id include the logtype to prevent hash collision cross logtypes
-
def before_create
if Staticentry.find_by_id(Digest::MD5.hexdigest(self.data + self.logtype_id.to_s)) != nil
return false
end
self.id = Digest::MD5.hexdigest(self.data + self.logtype_id.to_s)
end
end
diff --git a/src/server/config/cistern-example.yml b/src/server/config/cistern-example.yml
new file mode 100644
index 0000000..b57a3af
--- /dev/null
+++ b/src/server/config/cistern-example.yml
@@ -0,0 +1,2 @@
+#General app config
+usememcache: false
\ No newline at end of file
diff --git a/src/server/config/environment.rb b/src/server/config/environment.rb
index 99b1152..8e40ba0 100644
--- a/src/server/config/environment.rb
+++ b/src/server/config/environment.rb
@@ -1,44 +1,47 @@
# Be sure to restart your server when you modify this file
# Specifies gem version of Rails to use when vendor/rails is not present
RAILS_GEM_VERSION = '2.3.3' unless defined? RAILS_GEM_VERSION
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
Rails::Initializer.run do |config|
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Add additional load paths for your own custom dirs
# config.load_paths += %W( #{RAILS_ROOT}/extras )
# Specify gems that this application depends on and have them installed with rake gems:install
# config.gem "bj"
# config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
# config.gem "sqlite3-ruby", :lib => "sqlite3"
# config.gem "aws-s3", :lib => "aws/s3"
config.gem "eventmachine"
config.gem "will_paginate"
- #config.gem "acts_as_ferret"
+ #config.gem "memcache"
+
+ #config.gem "acts_as_cached"
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Skip frameworks you're not going to use. To use Rails without a database,
# you must remove the Active Record framework.
# config.frameworks -= [ :active_record, :active_resource, :action_mailer ]
# Activate observers that should always be running
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names.
config.time_zone = 'UTC'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')]
# config.i18n.default_locale = :de
-end
\ No newline at end of file
+end
+
diff --git a/src/server/config/initializers/extended_modules.rb b/src/server/config/initializers/extended_modules.rb
index 621f733..2d44c4e 100644
--- a/src/server/config/initializers/extended_modules.rb
+++ b/src/server/config/initializers/extended_modules.rb
@@ -1,16 +1,18 @@
#This initializer is used to pull in modules and extentions in other directories. (The include functions in envrionment.rb is crap)
require 'digest/md5'
require RAILS_ROOT + '/lib/modules/collection_server.rb'
require RAILS_ROOT + '/lib/modules/command_server.rb'
+USEMEMCACHE = YAML::load(File.open(RAILS_ROOT + "/config/cistern.yml"))['usememcache']
+
#Mixin for the string class to add a validity check for log events based on the checksum appended to buffered received data
class String
def valid?
part = self.split('__1_CC')
if Digest::MD5.hexdigest(part[0]) == part[1]
return true
else
return false
end
end
end
\ No newline at end of file
diff --git a/src/server/config/memcached-example.yml b/src/server/config/memcached-example.yml
new file mode 100644
index 0000000..56448ab
--- /dev/null
+++ b/src/server/config/memcached-example.yml
@@ -0,0 +1,35 @@
+defaults:
+ ttl: 1800
+ readonly: false
+ urlencode: false
+ c_threshold: 10000
+ compression: true
+ debug: false
+ namespace: cistern
+ sessions: false
+ session_servers: false
+ fragments: false
+ memory: 64
+ servers: localhost:11211
+ benchmarking: true
+ raise_errors: true
+ fast_hash: false
+ fastest_hash: false
+
+development:
+ usememcache: false
+ sessions: false
+ fragments: false
+ servers: localhost:11211
+
+# turn off caching
+test:
+ disabled: true
+
+production:
+ memory: 256
+ benchmarking: false
+ servers:
+ - 192.185.254.121:11211
+ - 192.185.254.138:11211
+ - 192.185.254.160:11211
diff --git a/src/server/lib/modules/collection_server.rb b/src/server/lib/modules/collection_server.rb
index a6326b9..82d46ce 100644
--- a/src/server/lib/modules/collection_server.rb
+++ b/src/server/lib/modules/collection_server.rb
@@ -1,73 +1,77 @@
module CollectionServer
#TODO: Checksum check should be wrapped in to an exception and then and handled that way in receive_data
#Set buffer delimiters
@@break = '__1_BB'
@@value = '__1_VV'
@@finish = '__1_EE'
def check_key(agent, key)
if agent.authkey != key
return false
else
return true
end
end
#Write a log entry
def log_entry(line)
raw = line.split(@@break)
map = Hash.new
raw.each do |keys|
parts = keys.split(@@value)
map.store(parts[0],parts[1])
end
static = Logtype.find(map['logtype_id']).staticentries.new
static.data = map['data']
static.save
- static = Staticentry.find_by_id(Digest::MD5.hexdigest(map['data'] + map['logtype_id'].to_s))
+ unless USEMEMCACHE != true
+ static = Staticentry.get_cache(Digest::MD5.hexdigest(map['data'] + map['logtype_id'].to_s))
+ else
+ static = Staticentry.find(Digest::MD5.hexdigest(map['data'] + map['logtype_id'].to_s))
+ end
event = static.events.new
event.etime = map['etime']
event.loglevel_id = map['loglevel_id']
event.payload = map['payload']
event.logtype_id = map['logtype_id']
event.agent_id = map['agent_id']
if check_key(Agent.find(map['agent_id']), map['authkey'])
event.save
else
ActiveRecord::Base.logger.debug "Event dropped -- invalid agent authkey sent"
end
port, ip = Socket.unpack_sockaddr_in(get_peername)
host = Socket.getaddrinfo(ip, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME)[0][2]
ActiveRecord::Base.logger.debug "New event logged from #{host} \n -- Log data: #{line}"
end
#Do this when a connection is initialized
def post_init
port, ip = Socket.unpack_sockaddr_in(get_peername)
host = Socket.getaddrinfo(ip, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME)[0][2]
ActiveRecord::Base.logger.info "-- Collector connection established from #{host}"
end
#Do this when data is received
def receive_data(data)
(@buffer ||= BufferedTokenizer.new(delimiter = "__1_EE")).extract(data).each do |line|
if line.valid?
log_entry(line)
else
port, ip = Socket.unpack_sockaddr_in(get_peername)
host = Socket.getaddrinfo(ip, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME)[0][2]
ActiveRecord::Base.logger.error "Dropped log entry from #{host} - checksum invalid"
end
end
end
#Do this when a connection is closed by a peer
def unbind
ActiveRecord::Base.logger.info "-- Collector connection closed by a peer"
end
end
\ No newline at end of file
diff --git a/src/server/script/memcached_ctl b/src/server/script/memcached_ctl
new file mode 100644
index 0000000..e41bdae
--- /dev/null
+++ b/src/server/script/memcached_ctl
@@ -0,0 +1,81 @@
+#!/usr/bin/env ruby
+# By atmos@atmos.org
+# this goes in your script/ directory
+# it parses your memcached.yml file and hooks you up w/ some info
+# it keeps you from having to mess w/ stale memcached daemons for whatever reason.
+require 'yaml'
+require 'timeout'
+require 'erb'
+
+class MemcachedCtl
+ attr_accessor :memcached, :memory, :pids, :servers, :ip_address, :ethernet_device
+
+ def initialize
+ env = ENV['RAILS_ENV'] || 'development'
+ self.memcached = `which memcached`.chomp
+ self.servers = [ ]
+ self.pids = { }
+ self.ethernet_device = ENV['ETH'] || 'eth0'
+ self.ip_address = get_ip_address || '0.0.0.0'
+ self.memory = '128'
+
+ config = YAML.load(ERB.new(IO.read((File.expand_path(File.dirname(__FILE__) + "/../config/memcached.yml")))).result)
+ self.servers = [ config['defaults']['servers'] ].flatten rescue ['127.0.0.1:11211']
+ self.servers = [ config[env]['servers'] ].flatten if config[env]['servers']
+ self.servers.reject! { |server| host,port = server.split(/:/); self.ip_address == host }
+ self.memory = config[env]['memory'] unless config[env]['memory'].nil?
+
+ each_server do |host,port|
+ `ps auwwx | grep memcached | grep '\\-l #{ip_address} \\-p #{port}' | grep -v grep`.split(/\n/).each do |line|
+ self.pids[port] = line.split(/\s+/)[1]
+ end
+ self.pids[port] ||= 'Down'
+ end
+ end
+
+ def execute(cmd)
+ send(cmd) rescue usage
+ end
+
+ def restart; stop; sleep 1; start end
+
+ def status
+ each_server { |host,port| puts "Port #{port} -> #{pids[port] =~ /\d+/ ? 'Up' : 'Down'}" }
+ end
+
+ def kill
+ each_server { |host,port| `kill -9 #{pids[port]} > /dev/null 2>&1` if pids[port] =~ /\d+/ }
+ end
+
+ def stop; kill end
+
+ def start
+ each_server do |host,port|
+ `#{memcached} -d -m #{memory} -l #{ip_address} -p #{port}`
+ STDERR.puts "Try memcached_ctl status" unless $? == 0
+ end
+ end
+
+ def usage
+ methods = %w[start stop restart kill status]
+ puts "Usage: script/memcached_ctl [ " + (methods * ' | ') + " ]"
+ end
+
+protected
+ def each_server
+ servers.each do |server|
+ host, port = server.split(/:/)
+ yield host, port
+ end
+ end
+
+ def get_ip_address # this works on linux you might have to tweak this on other oses
+ line = `/sbin/ifconfig #{ethernet_device} | grep inet | grep -v inet6`.chomp
+ if line =~ /\s*inet addr:((\d+\.){3}\d+)\s+.*/
+ self.ip_address = $1
+ end
+ end
+end
+###########################################################################
+
+MemcachedCtl.new.execute(ARGV.first)
diff --git a/src/server/vendor/plugins/cache_fu/CHANGELOG b/src/server/vendor/plugins/cache_fu/CHANGELOG
new file mode 100644
index 0000000..e69de29
diff --git a/src/server/vendor/plugins/cache_fu/LICENSE b/src/server/vendor/plugins/cache_fu/LICENSE
new file mode 100644
index 0000000..03b4b0f
--- /dev/null
+++ b/src/server/vendor/plugins/cache_fu/LICENSE
@@ -0,0 +1,18 @@
+Copyright (c) 2007 Chris Wanstrath
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software is furnished to do so,
+subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/src/server/vendor/plugins/cache_fu/README b/src/server/vendor/plugins/cache_fu/README
new file mode 100644
index 0000000..4ea6171
--- /dev/null
+++ b/src/server/vendor/plugins/cache_fu/README
@@ -0,0 +1,17 @@
+== cache_fu
+
+A rewrite of acts_as_cached.
+
+== Changes from acts_as_cached 1
+
+- You can no longer set a 'ttl' method on a class. Instead,
+ pass :ttl to acts_as_cached:
+ >> acts_as_cached :ttl => 15.minutes
+
+- The is_cached? method is aliased as cached?
+
+- set_cache on an instance can take a ttl
+ >> @story.set_cache(15.days)
+
+
+Chris Wanstrath [ chris[at]ozmm[dot]org ]
diff --git a/src/server/vendor/plugins/cache_fu/Rakefile b/src/server/vendor/plugins/cache_fu/Rakefile
new file mode 100644
index 0000000..2691bfd
--- /dev/null
+++ b/src/server/vendor/plugins/cache_fu/Rakefile
@@ -0,0 +1,42 @@
+require 'rake'
+require 'rake/testtask'
+require 'rake/rdoctask'
+require 'load_multi_rails_rake_tasks'
+
+desc "Run all the tests"
+task :default => :test
+
+test_files = FileList['test/*test.rb']
+
+desc 'Test the cache_fu plugin.'
+task :test do
+ test_files.each do |file|
+ ruby "#{file}"
+ end
+end
+
+desc 'Test the cache_fu plugin against Rails 1.2.5'
+task :test_with_125 do
+ ENV['MULTIRAILS_RAILS_VERSION'] = '1.2.5'
+ test_files.each do |file|
+ ruby "#{file}"
+ end
+end
+
+desc "Run cache_fu tests using a memcache daemon"
+task :test_with_memcache do
+ test_files.each do |file|
+ ruby "#{file} with-memcache"
+ end
+end
+
+desc 'Generate RDoc documentation for the cache_fu plugin.'
+Rake::RDocTask.new(:rdoc) do |rdoc|
+ files = ['README', 'LICENSE', 'lib/**/*.rb']
+ rdoc.rdoc_files.add(files)
+ rdoc.main = "README" # page to start on
+ rdoc.title = "cache_fu"
+ rdoc.template = File.exists?(t="/Users/chris/ruby/projects/err/rock/template.rb") ? t : "/var/www/rock/template.rb"
+ rdoc.rdoc_dir = 'doc' # rdoc output folder
+ rdoc.options << '--inline-source'
+end
diff --git a/src/server/vendor/plugins/cache_fu/defaults/extensions.rb.default b/src/server/vendor/plugins/cache_fu/defaults/extensions.rb.default
new file mode 100644
index 0000000..a43b754
--- /dev/null
+++ b/src/server/vendor/plugins/cache_fu/defaults/extensions.rb.default
@@ -0,0 +1,40 @@
+##
+# Copy this file to vendor/plugins/acts_as_cached/extensions.rb if you
+# wish to extend acts_as_cached with your own instance or class methods.
+#
+# You can, of course, do this directly in your cached classes,
+# but keeping your custom methods here allows you to define
+# methods for all cached objects DRYly.
+module ActsAsCached
+ module Extensions
+ module ClassMethods
+ ##
+ # All acts_as_cached classes will be extended with
+ # this method.
+ #
+ # >> Story.multi_get_cache(13, 353, 1231, 505)
+ # => [<Story:13>, <Story:353>, ...]
+ def multi_get_cache(*ids)
+ ids.flatten.map { |id| get_cache(id) }
+ end
+ end
+
+ module InstanceMethods
+ ##
+ # All instances of a acts_as_cached class will be
+ # extended with this method.
+ #
+ # => story = Story.get_cache(1)
+ # => <Story:1>
+ # >> story.reset_included_caches
+ # => true
+ def reset_included_caches
+ return false unless associations = cache_config[:include]
+ associations.each do |association|
+ Array(send(association)).each { |item| item.reset_cache }
+ end
+ true
+ end
+ end
+ end
+end
diff --git a/src/server/vendor/plugins/cache_fu/defaults/memcached.yml.default b/src/server/vendor/plugins/cache_fu/defaults/memcached.yml.default
new file mode 100644
index 0000000..9e683a0
--- /dev/null
+++ b/src/server/vendor/plugins/cache_fu/defaults/memcached.yml.default
@@ -0,0 +1,34 @@
+defaults:
+ ttl: 1800
+ readonly: false
+ urlencode: false
+ c_threshold: 10000
+ compression: true
+ debug: false
+ namespace: app
+ sessions: false
+ session_servers: false
+ fragments: false
+ memory: 64
+ servers: localhost:11211
+ benchmarking: true
+ raise_errors: true
+ fast_hash: false
+ fastest_hash: false
+
+development:
+ sessions: false
+ fragments: false
+ servers: localhost:11211
+
+# turn off caching
+test:
+ disabled: true
+
+production:
+ memory: 256
+ benchmarking: false
+ servers:
+ - 192.185.254.121:11211
+ - 192.185.254.138:11211
+ - 192.185.254.160:11211
diff --git a/src/server/vendor/plugins/cache_fu/defaults/memcached_ctl.default b/src/server/vendor/plugins/cache_fu/defaults/memcached_ctl.default
new file mode 100644
index 0000000..e41bdae
--- /dev/null
+++ b/src/server/vendor/plugins/cache_fu/defaults/memcached_ctl.default
@@ -0,0 +1,81 @@
+#!/usr/bin/env ruby
+# By atmos@atmos.org
+# this goes in your script/ directory
+# it parses your memcached.yml file and hooks you up w/ some info
+# it keeps you from having to mess w/ stale memcached daemons for whatever reason.
+require 'yaml'
+require 'timeout'
+require 'erb'
+
+class MemcachedCtl
+ attr_accessor :memcached, :memory, :pids, :servers, :ip_address, :ethernet_device
+
+ def initialize
+ env = ENV['RAILS_ENV'] || 'development'
+ self.memcached = `which memcached`.chomp
+ self.servers = [ ]
+ self.pids = { }
+ self.ethernet_device = ENV['ETH'] || 'eth0'
+ self.ip_address = get_ip_address || '0.0.0.0'
+ self.memory = '128'
+
+ config = YAML.load(ERB.new(IO.read((File.expand_path(File.dirname(__FILE__) + "/../config/memcached.yml")))).result)
+ self.servers = [ config['defaults']['servers'] ].flatten rescue ['127.0.0.1:11211']
+ self.servers = [ config[env]['servers'] ].flatten if config[env]['servers']
+ self.servers.reject! { |server| host,port = server.split(/:/); self.ip_address == host }
+ self.memory = config[env]['memory'] unless config[env]['memory'].nil?
+
+ each_server do |host,port|
+ `ps auwwx | grep memcached | grep '\\-l #{ip_address} \\-p #{port}' | grep -v grep`.split(/\n/).each do |line|
+ self.pids[port] = line.split(/\s+/)[1]
+ end
+ self.pids[port] ||= 'Down'
+ end
+ end
+
+ def execute(cmd)
+ send(cmd) rescue usage
+ end
+
+ def restart; stop; sleep 1; start end
+
+ def status
+ each_server { |host,port| puts "Port #{port} -> #{pids[port] =~ /\d+/ ? 'Up' : 'Down'}" }
+ end
+
+ def kill
+ each_server { |host,port| `kill -9 #{pids[port]} > /dev/null 2>&1` if pids[port] =~ /\d+/ }
+ end
+
+ def stop; kill end
+
+ def start
+ each_server do |host,port|
+ `#{memcached} -d -m #{memory} -l #{ip_address} -p #{port}`
+ STDERR.puts "Try memcached_ctl status" unless $? == 0
+ end
+ end
+
+ def usage
+ methods = %w[start stop restart kill status]
+ puts "Usage: script/memcached_ctl [ " + (methods * ' | ') + " ]"
+ end
+
+protected
+ def each_server
+ servers.each do |server|
+ host, port = server.split(/:/)
+ yield host, port
+ end
+ end
+
+ def get_ip_address # this works on linux you might have to tweak this on other oses
+ line = `/sbin/ifconfig #{ethernet_device} | grep inet | grep -v inet6`.chomp
+ if line =~ /\s*inet addr:((\d+\.){3}\d+)\s+.*/
+ self.ip_address = $1
+ end
+ end
+end
+###########################################################################
+
+MemcachedCtl.new.execute(ARGV.first)
diff --git a/src/server/vendor/plugins/cache_fu/init.rb b/src/server/vendor/plugins/cache_fu/init.rb
new file mode 100644
index 0000000..94099b7
--- /dev/null
+++ b/src/server/vendor/plugins/cache_fu/init.rb
@@ -0,0 +1,34 @@
+begin
+ require 'memcache'
+rescue LoadError
+end
+
+begin
+ require 'memcached'
+rescue LoadError
+end
+
+begin
+ require 'mem_cache_with_consistent_hashing'
+rescue LoadError
+end
+
+puts "=> You should be using the `memcache-client' gem. You're using RubyMemcache!" if Object.const_defined?(:RubyMemcache)
+
+require 'acts_as_cached'
+
+Object.send :include, ActsAsCached::Mixin
+
+unless File.exists? config_file = File.join(RAILS_ROOT, 'config', 'memcached.yml')
+ error = "No config file found. Make sure you used `script/plugin install' and have memcached.yml in your config directory."
+ puts error
+ logger.error error
+ exit!
+end
+
+ActsAsCached.config = YAML.load(ERB.new(IO.read(config_file)).result)
+
+begin
+ require 'extensions'
+rescue LoadError
+end
diff --git a/src/server/vendor/plugins/cache_fu/install.rb b/src/server/vendor/plugins/cache_fu/install.rb
new file mode 100644
index 0000000..497ce9f
--- /dev/null
+++ b/src/server/vendor/plugins/cache_fu/install.rb
@@ -0,0 +1,58 @@
+##
+# Do some checks.
+puts
+
+$errors = 0
+
+puts "** Checking for memcached in path..."
+if `which memcached`.strip.empty?
+ $errors += 1
+ puts "!! Couldn't find memcached in your path. Are you sure you installed it? !!"
+ puts "!! Check the README for help. You can't use acts_as_cached without it. !!"
+end
+
+puts "** Checking for memcache-client gem..."
+begin
+ require 'rubygems'
+ require 'memcache'
+rescue LoadError
+ $errors += 1
+ puts "!! Couldn't find memcache-client gem. You can't use acts_as_cached without it. !!"
+ puts "!! $ sudo gem install memcache-client !!"
+end
+
+require 'fileutils'
+def copy_file(in_file, out_file)
+ puts "** Trying to copy #{File.basename(in_file)} to #{out_file}..."
+ begin
+ if File.exists? out_file
+ puts "!! You already have a #{out_file}. " +
+ "Please check the default for new settings or format changes. !!"
+ puts "!! You can find the default at #{in_file}. !!"
+ $errors += 1
+ else
+ FileUtils.cp(in_file, out_file)
+ end
+ rescue
+ $errors += 1
+ puts "!! Error copying #{File.basename(in_file)} to #{out_file}. Please try by hand. !!"
+ end
+end
+
+defaults_dir = File.join(File.dirname(__FILE__), 'defaults')
+
+config_yaml = File.join('.', 'config', 'memcached.yml')
+default_yaml = File.join(defaults_dir, 'memcached.yml.default')
+copy_file(default_yaml, config_yaml)
+
+memcached_ctl = File.join('.', 'script', 'memcached_ctl')
+default_ctl = File.join(defaults_dir, 'memcached_ctl.default')
+copy_file(default_ctl, memcached_ctl)
+
+puts
+print $errors.zero? ? "**" : "!!"
+print " acts_as_cached installed with #{$errors.zero? ? 'no' : $errors} errors."
+print " Please edit the memcached.yml file to your liking."
+puts $errors.zero? ? "" : " !!"
+puts "** Now would be a good time to check out the README. Enjoy your day."
+puts
diff --git a/src/server/vendor/plugins/cache_fu/lib/acts_as_cached.rb b/src/server/vendor/plugins/cache_fu/lib/acts_as_cached.rb
new file mode 100644
index 0000000..418dd04
--- /dev/null
+++ b/src/server/vendor/plugins/cache_fu/lib/acts_as_cached.rb
@@ -0,0 +1,51 @@
+require 'acts_as_cached/config'
+require 'acts_as_cached/cache_methods'
+require 'acts_as_cached/fragment_cache'
+require 'acts_as_cached/benchmarking'
+require 'acts_as_cached/disabled'
+require 'acts_as_cached/local_cache'
+require 'acts_as_cached/memcached_rails'
+
+module ActsAsCached
+ @@config = {}
+ mattr_reader :config
+
+ def self.config=(options)
+ @@config = Config.setup options
+ end
+
+ def self.skip_cache_gets=(boolean)
+ ActsAsCached.config[:skip_gets] = boolean
+ end
+
+ module Mixin
+ def acts_as_cached(options = {})
+ extend ClassMethods
+ include InstanceMethods
+
+ extend Extensions::ClassMethods if defined? Extensions::ClassMethods
+ include Extensions::InstanceMethods if defined? Extensions::InstanceMethods
+
+ options.symbolize_keys!
+
+ options[:store] ||= ActsAsCached.config[:store]
+ options[:ttl] ||= ActsAsCached.config[:ttl]
+
+ # convert the find_by shorthand
+ if find_by = options.delete(:find_by)
+ options[:finder] = "find_by_#{find_by}".to_sym
+ options[:cache_id] = find_by
+ end
+
+ cache_config.replace options.reject { |key,| not Config.valued_keys.include? key }
+ cache_options.replace options.reject { |key,| Config.valued_keys.include? key }
+
+ Disabled.add_to self and return if ActsAsCached.config[:disabled]
+ Benchmarking.add_to self if ActsAsCached.config[:benchmarking]
+ end
+ end
+
+ class CacheException < StandardError; end
+ class NoCacheStore < CacheException; end
+ class NoGetMulti < CacheException; end
+end
diff --git a/src/server/vendor/plugins/cache_fu/lib/acts_as_cached/benchmarking.rb b/src/server/vendor/plugins/cache_fu/lib/acts_as_cached/benchmarking.rb
new file mode 100644
index 0000000..52381c3
--- /dev/null
+++ b/src/server/vendor/plugins/cache_fu/lib/acts_as_cached/benchmarking.rb
@@ -0,0 +1,87 @@
+require 'benchmark'
+
+module ActsAsCached
+ module Benchmarking #:nodoc:
+ def self.cache_runtime
+ @@cache_runtime ||= 0.0
+ end
+
+ def self.cache_reset_runtime
+ @@cache_runtime = nil
+ end
+
+ def cache_benchmark(title, log_level = Logger::DEBUG, use_silence = true)
+ return yield unless logger && logger.level == log_level
+ result = nil
+
+ seconds = Benchmark.realtime {
+ result = use_silence ? ActionController::Base.silence { yield } : yield
+ }
+
+ @@cache_runtime ||= 0.0
+ @@cache_runtime += seconds
+
+ logger.add(log_level, "==> #{title} (#{'%.5f' % seconds})")
+ result
+ end
+
+ def fetch_cache_with_benchmarking(*args)
+ cache_benchmark "Got #{cache_key args.first} from cache." do
+ fetch_cache_without_benchmarking(*args)
+ end
+ end
+
+ def set_cache_with_benchmarking(*args)
+ cache_benchmark "Set #{cache_key args.first} to cache." do
+ set_cache_without_benchmarking(*args)
+ end
+ end
+
+ def expire_cache_with_benchmarking(*args)
+ cache_benchmark "Deleted #{cache_key args.first} from cache." do
+ expire_cache_without_benchmarking(*args)
+ end
+ end
+
+ def self.add_to(klass)
+ return if klass.respond_to? :fetch_cache_with_benchmarking
+ klass.extend self
+
+ class << klass
+ alias_method_chain :fetch_cache, :benchmarking
+ alias_method_chain :set_cache, :benchmarking
+ alias_method_chain :expire_cache, :benchmarking
+
+ def logger; RAILS_DEFAULT_LOGGER end unless respond_to? :logger
+ end
+ end
+
+ def self.inject_into_logs!
+ if ActionController::Base.private_method_defined?(:rendering_runtime)
+ # Rails < 2.2
+ ActionController::Base.send :alias_method_chain, :rendering_runtime, :memcache
+ elsif ActionController::Base.private_method_defined?(:view_runtime)
+ # Rails >= 2.2
+ ActionController::Base.send :alias_method_chain, :view_runtime, :memcache
+ else
+ raise "Unknown Rails Version?!"
+ end
+ end
+ end
+end
+
+module ActionController
+ class Base
+ def rendering_runtime_with_memcache(runtime) #:nodoc:
+ cache_runtime = ActsAsCached::Benchmarking.cache_runtime
+ ActsAsCached::Benchmarking.cache_reset_runtime
+ rendering_runtime_without_memcache(runtime) + (cache_runtime.nonzero? ? " | Memcache: #{"%.5f" % cache_runtime}" : '')
+ end
+
+ def view_runtime_with_memcache #:nodoc:
+ cache_runtime = ActsAsCached::Benchmarking.cache_runtime
+ ActsAsCached::Benchmarking.cache_reset_runtime
+ view_runtime_without_memcache + (cache_runtime.nonzero? ? ", Memcache: #{"%.0f" % (cache_runtime * 1000)}" : '')
+ end
+ end
+end
diff --git a/src/server/vendor/plugins/cache_fu/lib/acts_as_cached/cache_methods.rb b/src/server/vendor/plugins/cache_fu/lib/acts_as_cached/cache_methods.rb
new file mode 100644
index 0000000..d304c96
--- /dev/null
+++ b/src/server/vendor/plugins/cache_fu/lib/acts_as_cached/cache_methods.rb
@@ -0,0 +1,305 @@
+module ActsAsCached
+ module ClassMethods
+ @@nil_sentinel = :_nil
+
+ def cache_config
+ config = ActsAsCached::Config.class_config[cache_name] ||= {}
+ if name == cache_name
+ config
+ else
+ # sti
+ ActsAsCached::Config.class_config[name] ||= config.dup
+ end
+ end
+
+ def cache_options
+ cache_config[:options] ||= {}
+ end
+
+ def get_cache(*args)
+ options = args.last.is_a?(Hash) ? args.pop : {}
+ args = args.flatten
+
+ ##
+ # head off to get_caches if we were passed multiple cache_ids
+ if args.size > 1
+ return get_caches(args, options)
+ else
+ cache_id = args.first
+ end
+
+ if (item = fetch_cache(cache_id)).nil?
+ set_cache(cache_id, block_given? ? yield : fetch_cachable_data(cache_id), options[:ttl])
+ else
+ @@nil_sentinel == item ? nil : item
+ end
+ end
+
+ ##
+ # This method accepts an array of cache_ids which it will use to call
+ # get_multi on your cache store. Any misses will be fetched and saved to
+ # the cache, and a hash keyed by cache_id will ultimately be returned.
+ #
+ # If your cache store does not support #get_multi an exception will be raised.
+ def get_caches(*args)
+ raise NoGetMulti unless cache_store.respond_to? :get_multi
+
+ options = args.last.is_a?(Hash) ? args.pop : {}
+ cache_ids = args.flatten.map(&:to_s)
+ keys = cache_keys(cache_ids)
+
+ # Map memcache keys to object cache_ids in { memcache_key => object_id } format
+ keys_map = Hash[*keys.zip(cache_ids).flatten]
+
+ # Call get_multi and figure out which keys were missed based on what was a hit
+ hits = ActsAsCached.config[:disabled] ? {} : (cache_store(:get_multi, *keys) || {})
+
+ # Misses can take the form of key => nil
+ hits.delete_if { |key, value| value.nil? }
+
+ misses = keys - hits.keys
+ hits.each { |k, v| hits[k] = nil if v == @@nil_sentinel }
+
+ # Return our hash if there are no misses
+ return hits.values.index_by(&:cache_id) if misses.empty?
+
+ # Find any missed records
+ needed_ids = keys_map.values_at(*misses)
+ missed_records = Array(fetch_cachable_data(needed_ids))
+
+ # Cache the missed records
+ missed_records.each { |missed_record| missed_record.set_cache(options[:ttl]) }
+
+ # Return all records as a hash indexed by object cache_id
+ (hits.values + missed_records).index_by(&:cache_id)
+ end
+
+ # simple wrapper for get_caches that
+ # returns the items as an ordered array
+ def get_caches_as_list(*args)
+ cache_ids = args.last.is_a?(Hash) ? args.first : args
+ cache_ids = [cache_ids].flatten
+ hash = get_caches(*args)
+
+ cache_ids.map do |key|
+ hash[key]
+ end
+ end
+
+ def set_cache(cache_id, value, ttl = nil)
+ returning(value) do |v|
+ v = @@nil_sentinel if v.nil?
+ cache_store(:set, cache_key(cache_id), v, ttl || cache_config[:ttl] || 1500)
+ end
+ end
+
+ def expire_cache(cache_id = nil)
+ cache_store(:delete, cache_key(cache_id))
+ true
+ end
+ alias :clear_cache :expire_cache
+
+ def reset_cache(cache_id = nil)
+ set_cache(cache_id, fetch_cachable_data(cache_id))
+ end
+
+ ##
+ # Encapsulates the pattern of writing custom cache methods
+ # which do nothing but wrap custom finders.
+ #
+ # => Story.caches(:find_popular)
+ #
+ # is the same as
+ #
+ # def self.cached_find_popular
+ # get_cache(:find_popular) { find_popular }
+ # end
+ #
+ # The method also accepts both a :ttl and/or a :with key.
+ # Obviously the :ttl value controls how long this method will
+ # stay cached, while the :with key's value will be passed along
+ # to the method. The hash of the :with key will be stored with the key,
+ # making two near-identical #caches calls with different :with values utilize
+ # different caches.
+ #
+ # => Story.caches(:find_popular, :with => :today)
+ #
+ # is the same as
+ #
+ # def self.cached_find_popular
+ # get_cache("find_popular:today") { find_popular(:today) }
+ # end
+ #
+ # If your target method accepts multiple parameters, pass :withs an array.
+ #
+ # => Story.caches(:find_popular, :withs => [ :one, :two ])
+ #
+ # is the same as
+ #
+ # def self.cached_find_popular
+ # get_cache("find_popular:onetwo") { find_popular(:one, :two) }
+ # end
+ def caches(method, options = {})
+ if options.keys.include?(:with)
+ with = options.delete(:with)
+ get_cache("#{method}:#{with}", options) { send(method, with) }
+ elsif withs = options.delete(:withs)
+ get_cache("#{method}:#{withs}", options) { send(method, *withs) }
+ else
+ get_cache(method, options) { send(method) }
+ end
+ end
+ alias :cached :caches
+
+ def cached?(cache_id = nil)
+ fetch_cache(cache_id).nil? ? false : true
+ end
+ alias :is_cached? :cached?
+
+ def fetch_cache(cache_id)
+ return if ActsAsCached.config[:skip_gets]
+
+ autoload_missing_constants do
+ cache_store(:get, cache_key(cache_id))
+ end
+ end
+
+ def fetch_cachable_data(cache_id = nil)
+ finder = cache_config[:finder] || :find
+ return send(finder) unless cache_id
+
+ args = [cache_id]
+ args << cache_options.dup unless cache_options.blank?
+ send(finder, *args)
+ end
+
+ def cache_namespace
+ cache_store(:namespace)
+ end
+
+ # Memcache-client automatically prepends the namespace, plus a colon, onto keys, so we take that into account for the max key length.
+ # Rob Sanheim
+ def max_key_length
+ unless @max_key_length
+ key_size = cache_config[:key_size] || 250
+ @max_key_length = cache_namespace ? (key_size - cache_namespace.length - 1) : key_size
+ end
+ @max_key_length
+ end
+
+ def cache_name
+ @cache_name ||= respond_to?(:base_class) ? base_class.name : name
+ end
+
+ def cache_keys(*cache_ids)
+ cache_ids.flatten.map { |cache_id| cache_key(cache_id) }
+ end
+
+ def cache_key(cache_id)
+ [cache_name, cache_config[:version], cache_id].compact.join(':').gsub(' ', '_')[0..(max_key_length - 1)]
+ end
+
+ def cache_store(method = nil, *args)
+ return cache_config[:store] unless method
+
+ load_constants = %w( get get_multi ).include? method.to_s
+
+ swallow_or_raise_cache_errors(load_constants) do
+ cache_config[:store].send(method, *args)
+ end
+ end
+
+ def swallow_or_raise_cache_errors(load_constants = false, &block)
+ load_constants ? autoload_missing_constants(&block) : yield
+ rescue TypeError => error
+ if error.to_s.include? 'Proc'
+ raise MarshalError, "Most likely an association callback defined with a Proc is triggered, see http://ar.rubyonrails.com/classes/ActiveRecord/Associations/ClassMethods.html (Association Callbacks) for details on converting this to a method based callback"
+ else
+ raise error
+ end
+ rescue Exception => error
+ if ActsAsCached.config[:raise_errors]
+ raise error
+ else
+ RAILS_DEFAULT_LOGGER.debug "MemCache Error: #{error.message}" rescue nil
+ nil
+ end
+ end
+
+ def autoload_missing_constants
+ yield
+ rescue ArgumentError, MemCache::MemCacheError => error
+ lazy_load ||= Hash.new { |hash, hash_key| hash[hash_key] = true; false }
+ if error.to_s[/undefined class|referred/] && !lazy_load[error.to_s.split.last.constantize] then retry
+ else raise error end
+ end
+ end
+
+ module InstanceMethods
+ def self.included(base)
+ base.send :delegate, :cache_config, :to => 'self.class'
+ base.send :delegate, :cache_options, :to => 'self.class'
+ end
+
+ def get_cache(key = nil, options = {}, &block)
+ self.class.get_cache(cache_id(key), options, &block)
+ end
+
+ def set_cache(ttl = nil)
+ self.class.set_cache(cache_id, self, ttl)
+ end
+
+ def reset_cache(key = nil)
+ self.class.reset_cache(cache_id(key))
+ end
+
+ def expire_cache(key = nil)
+ self.class.expire_cache(cache_id(key))
+ end
+ alias :clear_cache :expire_cache
+
+ def cached?(key = nil)
+ self.class.cached? cache_id(key)
+ end
+
+ def cache_key
+ self.class.cache_key(cache_id)
+ end
+
+ def cache_id(key = nil)
+ id = send(cache_config[:cache_id] || :id)
+ key.nil? ? id : "#{id}:#{key}"
+ end
+
+ def caches(method, options = {})
+ key = "#{id}:#{method}"
+ if options.keys.include?(:with)
+ with = options.delete(:with)
+ self.class.get_cache("#{key}:#{with}", options) { send(method, with) }
+ elsif withs = options.delete(:withs)
+ self.class.get_cache("#{key}:#{withs}", options) { send(method, *withs) }
+ else
+ self.class.get_cache(key, options) { send(method) }
+ end
+ end
+ alias :cached :caches
+
+ # Ryan King
+ def set_cache_with_associations
+ Array(cache_options[:include]).each do |assoc|
+ send(assoc).reload
+ end if cache_options[:include]
+ set_cache
+ end
+
+ # Lourens Naud
+ def expire_cache_with_associations(*associations_to_sweep)
+ (Array(cache_options[:include]) + associations_to_sweep).flatten.uniq.compact.each do |assoc|
+ Array(send(assoc)).compact.each { |item| item.expire_cache if item.respond_to?(:expire_cache) }
+ end
+ expire_cache
+ end
+ end
+
+ class MarshalError < StandardError; end
+end
diff --git a/src/server/vendor/plugins/cache_fu/lib/acts_as_cached/config.rb b/src/server/vendor/plugins/cache_fu/lib/acts_as_cached/config.rb
new file mode 100644
index 0000000..3af03d4
--- /dev/null
+++ b/src/server/vendor/plugins/cache_fu/lib/acts_as_cached/config.rb
@@ -0,0 +1,97 @@
+module ActsAsCached
+ module Config
+ extend self
+
+ @@class_config = {}
+ mattr_reader :class_config
+
+ def valued_keys
+ [ :store, :version, :pages, :per_page, :ttl, :finder, :cache_id, :find_by, :key_size ]
+ end
+
+ def setup(options)
+ config = options['defaults']
+
+ case options[RAILS_ENV]
+ when Hash then config.update(options[RAILS_ENV])
+ when String then config[:disabled] = true
+ end
+
+ config.symbolize_keys!
+
+ setup_benchmarking! if config[:benchmarking] && !config[:disabled]
+
+ setup_cache_store! config
+ config
+ end
+
+ def setup_benchmarking!
+ Benchmarking.inject_into_logs!
+ end
+
+ def setup_cache_store!(config)
+ config[:store] =
+ if config[:store].nil?
+ setup_memcache config
+ elsif config[:store].respond_to? :constantize
+ config[:store].constantize.new
+ else
+ config[:store]
+ end
+ end
+
+ def setup_memcache(config)
+ config[:namespace] << "-#{RAILS_ENV}"
+
+ # if someone (e.g., interlock) already set up memcached, then
+ # we need to stop here
+ return CACHE if Object.const_defined?(:CACHE)
+
+ silence_warnings do
+ Object.const_set :CACHE, memcache_client(config)
+ Object.const_set :SESSION_CACHE, memcache_client(config) if config[:session_servers]
+ end
+
+ CACHE.servers = Array(config.delete(:servers))
+ SESSION_CACHE.servers = Array(config[:session_servers]) if config[:session_servers]
+
+ setup_session_store if config[:sessions]
+ setup_fragment_store! if config[:fragments]
+ setup_fast_hash! if config[:fast_hash]
+ setup_fastest_hash! if config[:fastest_hash]
+
+ CACHE
+ end
+
+ def memcache_client(config)
+ (config[:client] || "MemCache").classify.constantize.new(config)
+ end
+
+ def setup_session_store
+ ActionController::Base.session_store = :mem_cache_store
+ ActionController::CgiRequest::DEFAULT_SESSION_OPTIONS.update 'cache' => defined?(SESSION_CACHE) ? SESSION_CACHE : CACHE
+ end
+
+ def setup_fragment_store!
+ ActsAsCached::FragmentCache.setup!
+ end
+
+ # break compatiblity with non-ruby memcache clients in exchange for speedup.
+ # consistent across all platforms.
+ def setup_fast_hash!
+ def CACHE.hash_for(key)
+ (0...key.length).inject(0) do |sum, i|
+ sum + key[i]
+ end
+ end
+ end
+
+ # break compatiblity with non-ruby memcache clients in exchange for speedup.
+ # NOT consistent across all platforms. Object#hash gives different results
+ # on different architectures. only use if all your apps are running the
+ # same arch.
+ def setup_fastest_hash!
+ def CACHE.hash_for(key) key.hash end
+ end
+ end
+end
diff --git a/src/server/vendor/plugins/cache_fu/lib/acts_as_cached/disabled.rb b/src/server/vendor/plugins/cache_fu/lib/acts_as_cached/disabled.rb
new file mode 100644
index 0000000..4c72658
--- /dev/null
+++ b/src/server/vendor/plugins/cache_fu/lib/acts_as_cached/disabled.rb
@@ -0,0 +1,30 @@
+module ActsAsCached
+ module Disabled
+ def fetch_cache_with_disabled(*args)
+ nil
+ end
+
+ def set_cache_with_disabled(*args)
+ args[1]
+ end
+
+ def expire_cache_with_disabled(*args)
+ true
+ end
+
+ def self.add_to(klass)
+ return if klass.respond_to? :fetch_cache_with_disabled
+ klass.extend self
+
+ class << klass
+ alias_method_chain :fetch_cache, :disabled
+ alias_method_chain :set_cache, :disabled
+ alias_method_chain :expire_cache, :disabled
+ end
+
+ class << CACHE
+ include FragmentCache::DisabledExtensions
+ end if ActsAsCached.config[:fragments] && defined?(FragmentCache::DisabledExtensions)
+ end
+ end
+end
diff --git a/src/server/vendor/plugins/cache_fu/lib/acts_as_cached/fragment_cache.rb b/src/server/vendor/plugins/cache_fu/lib/acts_as_cached/fragment_cache.rb
new file mode 100644
index 0000000..1f1f6d1
--- /dev/null
+++ b/src/server/vendor/plugins/cache_fu/lib/acts_as_cached/fragment_cache.rb
@@ -0,0 +1,124 @@
+module ActsAsCached
+ module FragmentCache
+ def self.setup!
+ class << CACHE
+ include Extensions
+ end
+
+ setup_fragment_cache_cache
+ setup_rails_for_memcache_fragments
+ setup_rails_for_action_cache_options
+ end
+
+ # add :ttl option to cache helper and set cache store memcache object
+ def self.setup_rails_for_memcache_fragments
+ if ::ActionView.const_defined?(:Template)
+ # Rails 2.1+
+ ::ActionController::Base.cache_store = CACHE
+ else
+ # Rails < svn r8619
+ ::ActionView::Helpers::CacheHelper.class_eval do
+ def cache(name = {}, options = nil, &block)
+ @controller.cache_erb_fragment(block, name, options)
+ end
+ end
+ ::ActionController::Base.fragment_cache_store = CACHE
+ end
+ end
+
+ def self.setup_fragment_cache_cache
+ Object.const_set(:FragmentCacheCache, Class.new { acts_as_cached :store => CACHE })
+ end
+
+ # add :ttl option to caches_action on the per action level by passing in a hash instead of an array
+ #
+ # Examples:
+ # caches_action :index # will use the default ttl from your memcache.yml, or 25 minutes
+ # caches_action :index => { :ttl => 5.minutes } # cache index action with 5 minute ttl
+ # caches_action :page, :feed, :index => { :ttl => 2.hours } # cache index action with 2 hours ttl, all others use default
+ #
+ def self.setup_rails_for_action_cache_options
+ ::ActionController::Caching::Actions::ActionCacheFilter.class_eval do
+ # convert all actions into a hash keyed by action named, with a value of a ttl hash (to match other cache APIs)
+ def initialize(*actions, &block)
+ if [].respond_to?(:extract_options!)
+ #edge
+ @options = actions.extract_options!
+ @actions = actions.inject(@options.except(:cache_path)) do |hsh, action|
+ action.is_a?(Hash) ? hsh.merge(action) : hsh.merge(action => { :ttl => nil })
+ end
+ @options.slice!(:cache_path)
+ else
+ #1.2.5
+ @actions = actions.inject({}) do |hsh, action|
+ action.is_a?(Hash) ? hsh.merge(action) : hsh.merge(action => { :ttl => nil })
+ end
+ end
+ end
+
+ # override to skip caching/rendering on evaluated if option
+ def before(controller)
+ return unless @actions.include?(controller.action_name.intern)
+
+ # maintaining edge and 1.2.x compatibility with this branch
+ if @options
+ action_cache_path = ActionController::Caching::Actions::ActionCachePath.new(controller, path_options_for(controller, @options))
+ else
+ action_cache_path = ActionController::Caching::Actions::ActionCachePath.new(controller)
+ end
+
+ # should probably be like ActiveRecord::Validations.evaluate_condition. color me lazy.
+ if conditional = @actions[controller.action_name.intern][:if]
+ conditional = conditional.respond_to?(:call) ? conditional.call(controller) : controller.send(conditional)
+ end
+ @actions.delete(controller.action_name.intern) if conditional == false
+
+ cache = controller.read_fragment(action_cache_path.path)
+ if cache && (conditional || conditional.nil?)
+ controller.rendered_action_cache = true
+ if method(:set_content_type!).arity == 2
+ set_content_type!(controller, action_cache_path.extension)
+ else
+ set_content_type!(action_cache_path)
+ end
+ controller.send(:render, :text => cache)
+ false
+ else
+ # 1.2.x compatibility
+ controller.action_cache_path = action_cache_path if controller.respond_to? :action_cache_path
+ end
+ end
+
+ # override to pass along the ttl hash
+ def after(controller)
+ return if !@actions.include?(controller.action_name.intern) || controller.rendered_action_cache
+ # 1.2.x compatibility
+ path = controller.respond_to?(:action_cache_path) ? controller.action_cache_path.path : ActionController::Caching::Actions::ActionCachePath.path_for(controller)
+ controller.write_fragment(path, controller.response.body, action_ttl(controller))
+ end
+
+ private
+ def action_ttl(controller)
+ @actions[controller.action_name.intern]
+ end
+ end
+ end
+
+ module Extensions
+ def read(*args)
+ return if ActsAsCached.config[:skip_gets]
+ FragmentCacheCache.cache_store(:get, args.first)
+ end
+
+ def write(name, content, options = {})
+ ttl = (options.is_a?(Hash) ? options[:ttl] : nil) || ActsAsCached.config[:ttl] || 25.minutes
+ FragmentCacheCache.cache_store(:set, name, content, ttl)
+ end
+ end
+
+ module DisabledExtensions
+ def read(*args) nil end
+ def write(*args) "" end
+ end
+ end
+end
diff --git a/src/server/vendor/plugins/cache_fu/lib/acts_as_cached/local_cache.rb b/src/server/vendor/plugins/cache_fu/lib/acts_as_cached/local_cache.rb
new file mode 100644
index 0000000..55e24d9
--- /dev/null
+++ b/src/server/vendor/plugins/cache_fu/lib/acts_as_cached/local_cache.rb
@@ -0,0 +1,44 @@
+module ActsAsCached
+ module LocalCache
+ @@local_cache = {}
+ mattr_accessor :local_cache
+
+ def fetch_cache_with_local_cache(*args)
+ @@local_cache[cache_key(args.first)] ||= fetch_cache_without_local_cache(*args)
+ end
+
+ def set_cache_with_local_cache(*args)
+ @@local_cache[cache_key(args.first)] = set_cache_without_local_cache(*args)
+ end
+
+ def expire_cache_with_local_cache(*args)
+ @@local_cache.delete(cache_key(args.first))
+ expire_cache_without_local_cache(*args)
+ end
+ alias :clear_cache_with_local_cache :expire_cache_with_local_cache
+
+ def cached_with_local_cache?(*args)
+ !!@@local_cache[cache_key(args.first)] || cached_without_local_cache?(*args)
+ end
+
+ def self.add_to(klass)
+ return if klass.ancestors.include? self
+ klass.send :include, self
+
+ klass.class_eval do
+ %w( fetch_cache set_cache expire_cache clear_cache cached? ).each do |target|
+ alias_method_chain target, :local_cache
+ end
+ end
+ end
+ end
+end
+
+module ActionController
+ class Base
+ def local_cache_for_request
+ ActsAsCached::LocalCache.add_to ActsAsCached::ClassMethods
+ ActsAsCached::LocalCache.local_cache = {}
+ end
+ end
+end
diff --git a/src/server/vendor/plugins/cache_fu/lib/acts_as_cached/memcached_rails.rb b/src/server/vendor/plugins/cache_fu/lib/acts_as_cached/memcached_rails.rb
new file mode 100644
index 0000000..825e3de
--- /dev/null
+++ b/src/server/vendor/plugins/cache_fu/lib/acts_as_cached/memcached_rails.rb
@@ -0,0 +1,17 @@
+class Memcached
+ # A legacy compatibility wrapper for the Memcached class. It has basic compatibility with the <b>memcache-client</b> API.
+ class Rails < ::Memcached
+ def initialize(config)
+ super(config.delete(:servers), config.slice(DEFAULTS.keys))
+ end
+
+ def servers=(servers)
+
+ end
+
+ def delete(key, expiry = 0)
+ super(key)
+ rescue NotFound
+ end
+ end
+end
\ No newline at end of file
diff --git a/src/server/vendor/plugins/cache_fu/lib/acts_as_cached/recipes.rb b/src/server/vendor/plugins/cache_fu/lib/acts_as_cached/recipes.rb
new file mode 100644
index 0000000..7ef3aca
--- /dev/null
+++ b/src/server/vendor/plugins/cache_fu/lib/acts_as_cached/recipes.rb
@@ -0,0 +1,8 @@
+Capistrano.configuration(:must_exist).load do
+ %w(start stop restart kill status).each do |cmd|
+ desc "#{cmd} your memcached servers"
+ task "memcached_#{cmd}".to_sym, :roles => :app do
+ run "RAILS_ENV=production #{ruby} #{current_path}/script/memcached_ctl #{cmd}"
+ end
+ end
+end
diff --git a/src/server/vendor/plugins/cache_fu/tasks/memcached.rake b/src/server/vendor/plugins/cache_fu/tasks/memcached.rake
new file mode 100644
index 0000000..74fd270
--- /dev/null
+++ b/src/server/vendor/plugins/cache_fu/tasks/memcached.rake
@@ -0,0 +1,43 @@
+require 'yaml'
+require 'erb'
+
+namespace :memcached do
+ desc "Start memcached locally"
+ task :start do
+ memcached config_args
+ puts "memcached started"
+ end
+
+ desc "Restart memcached locally"
+ task :restart do
+ Rake::Task['memcached:stop'].invoke
+ Rake::Task['memcached:start'].invoke
+ end
+
+ desc "Stop memcached locally"
+ task :stop do
+ `killall memcached`
+ puts "memcached killed"
+ end
+end
+
+def config
+ return @config if @config
+ config = YAML.load(ERB.new(IO.read(File.dirname(__FILE__) + '/../../../../config/memcached.yml')).result)
+ @config = config['defaults'].merge(config['development'])
+end
+
+def config_args
+ args = {
+ '-p' => Array(config['servers']).first.split(':').last,
+ '-c' => config['c_threshold'],
+ '-m' => config['memory'],
+ '-d' => ''
+ }
+
+ args.to_a * ' '
+end
+
+def memcached(*args)
+ `/usr/bin/env memcached #{args * ' '}`
+end
diff --git a/src/server/vendor/plugins/cache_fu/test/benchmarking_test.rb b/src/server/vendor/plugins/cache_fu/test/benchmarking_test.rb
new file mode 100644
index 0000000..565991f
--- /dev/null
+++ b/src/server/vendor/plugins/cache_fu/test/benchmarking_test.rb
@@ -0,0 +1,36 @@
+require File.join(File.dirname(__FILE__), 'helper')
+
+ActsAsCached.config.clear
+config = YAML.load_file(File.join(File.dirname(__FILE__), '../defaults/memcached.yml.default'))
+config['test'] = config['development']
+ActsAsCached.config = config
+Story.send :acts_as_cached
+
+context "When benchmarking is enabled" do
+ specify "ActionController::Base should respond to rendering_runtime_with_memcache" do
+ ActionController::Base.new.should.respond_to :rendering_runtime_with_memcache
+ end
+
+ specify "cachable Ruby classes should be respond to :logger" do
+ Story.should.respond_to :logger
+ end
+
+ specify "a cached object should gain a fetch_cache with and without benchmarking methods" do
+ Story.should.respond_to :fetch_cache_with_benchmarking
+ Story.should.respond_to :fetch_cache_without_benchmarking
+ end
+
+ specify "cache_benchmark should yield and time any action" do
+ ActsAsCached::Benchmarking.cache_runtime.should.equal 0.0
+
+ level = Class.new { |k| def k.method_missing(*args) true end }
+ Story.stubs(:logger).returns(level)
+
+ Story.cache_benchmark("Seriously, nothing.", true) {
+ sleep 0.01
+ "Nothing."
+ }.should.equal "Nothing."
+
+ ActsAsCached::Benchmarking.cache_runtime.should.be > 0.0
+ end
+end
diff --git a/src/server/vendor/plugins/cache_fu/test/cache_test.rb b/src/server/vendor/plugins/cache_fu/test/cache_test.rb
new file mode 100644
index 0000000..83eab70
--- /dev/null
+++ b/src/server/vendor/plugins/cache_fu/test/cache_test.rb
@@ -0,0 +1,281 @@
+require File.join(File.dirname(__FILE__), 'helper')
+
+context "A Ruby class acting as cached (in general)" do
+ include StoryCacheSpecSetup
+
+ specify "should be able to retrieve a cached instance from the cache" do
+ Story.get_cache(1).should.equal Story.find(1)
+ end
+
+ specify "should set to the cache if its not already set when getting" do
+ Story.should.not.have.cached 1
+ Story.get_cache(1).should.equal Story.find(1)
+ Story.should.have.cached 1
+ end
+
+ specify "should not set to the cache if is already set when getting" do
+ Story.expects(:set_cache).never
+ Story.should.have.cached 2
+ Story.get_cache(2).should.equal Story.find(2)
+ Story.should.have.cached 2
+ end
+
+ specify "should be able to tell if a key is cached" do
+ Story.is_cached?(1).should.equal false
+ Story.should.not.have.cached 1
+ Story.should.have.cached 2
+ end
+
+ specify "should be able to cache arbitrary methods using #caches" do
+ Story.cache_store.expects(:get).returns(nil)
+ Story.cache_store.expects(:set).with('Story:something_cool', :redbull, 1500)
+ Story.caches(:something_cool).should.equal :redbull
+
+ Story.cache_store.expects(:get).returns(:redbull)
+ Story.cache_store.expects(:set).never
+ Story.caches(:something_cool).should.equal :redbull
+ end
+
+ specify "should be able to cache arbitrary methods with arguments using #caches and :with" do
+ with = :mongrel
+
+ Story.cache_store.expects(:get).returns(nil)
+ Story.cache_store.expects(:set).with("Story:block_on:#{with}", with, 1500)
+ Story.caches(:block_on, :with => with).should.equal with
+
+ Story.cache_store.expects(:get).with("Story:block_on:#{with}").returns(:okay)
+ Story.cache_store.expects(:set).never
+ Story.caches(:block_on, :with => with).should.equal :okay
+ end
+
+ specify "should be able to cache arbitrary methods with a nil argument using #caches and :with" do
+ with = nil
+
+ Story.cache_store.expects(:get).returns(nil)
+ Story.cache_store.expects(:set).with("Story:pass_through:#{with}", :_nil, 1500)
+ Story.caches(:pass_through, :with => with).should.equal with
+ end
+
+ specify "should be able to cache arbitrary methods with arguments using #caches and :withs" do
+ withs = [ :first, :second ]
+
+ cached_string = "first: #{withs.first} | second: #{withs.last}"
+
+ Story.cache_store.expects(:get).returns(nil)
+ Story.cache_store.expects(:set).with("Story:two_params:#{withs}", cached_string, 1500)
+ Story.caches(:two_params, :withs => withs).should.equal cached_string
+
+ Story.cache_store.expects(:get).with("Story:two_params:#{withs}").returns(:okay)
+ Story.cache_store.expects(:set).never
+ Story.caches(:two_params, :withs => withs).should.equal :okay
+ end
+
+ specify "should set nil when trying to set nil" do
+ Story.set_cache(3, nil).should.equal nil
+ Story.get_cache(3).should.equal nil
+ end
+
+ specify "should set false when trying to set false" do
+ Story.set_cache(3, false).should.equal false
+ Story.get_cache(3).should.equal false
+ end
+
+ specify "should be able to expire a cache key" do
+ Story.should.have.cached 2
+ Story.expire_cache(2).should.equal true
+ Story.should.not.have.cached 2
+ end
+
+ specify "should return true when trying to expire the cache" do
+ Story.should.not.have.cached 1
+ Story.expire_cache(1).should.equal true
+ Story.should.have.cached 2
+ Story.expire_cache(2).should.equal true
+ end
+
+ specify "should be able to reset a cache key, returning the cached object if successful" do
+ Story.expects(:find).with(2).returns(@story2)
+ Story.should.have.cached 2
+ Story.reset_cache(2).should.equal @story2
+ Story.should.have.cached 2
+ end
+
+ specify "should be able to cache the value of a block" do
+ Story.should.not.have.cached :block
+ Story.get_cache(:block) { "this is a block" }
+ Story.should.have.cached :block
+ Story.get_cache(:block).should.equal "this is a block"
+ end
+
+ specify "should be able to define a class level ttl" do
+ ttl = 1124
+ Story.cache_config[:ttl] = ttl
+ Story.cache_config[:store].expects(:set).with(Story.cache_key(1), @story, ttl)
+ Story.get_cache(1)
+ end
+
+ specify "should be able to define a per-key ttl" do
+ ttl = 3262
+ Story.cache_config[:store].expects(:set).with(Story.cache_key(1), @story, ttl)
+ Story.get_cache(1, :ttl => ttl)
+ end
+
+ specify "should be able to skip cache gets" do
+ Story.should.have.cached 2
+ ActsAsCached.skip_cache_gets = true
+ Story.expects(:find).at_least_once
+ Story.get_cache(2)
+ ActsAsCached.skip_cache_gets = false
+ end
+
+ specify "should be able to use an arbitrary finder method via :finder" do
+ Story.expire_cache(4)
+ Story.cache_config[:finder] = :find_live
+ Story.expects(:find_live).with(4).returns(false)
+ Story.get_cache(4)
+ end
+
+ specify "should raise an exception if no finder method is found" do
+ Story.cache_config[:finder] = :find_penguins
+ proc { Story.get_cache(1) }.should.raise(NoMethodError)
+ end
+
+ specify "should be able to use an abitrary cache_id method via :cache_id" do
+ Story.expire_cache(4)
+ Story.cache_config[:cache_id] = :title
+ story = Story.get_cache(1)
+ story.cache_id.should.equal story.title
+ end
+
+ specify "should modify its cache key to reflect a :version option" do
+ Story.cache_config[:version] = 'new'
+ Story.cache_key(1).should.equal 'Story:new:1'
+ end
+
+ specify "should truncate the key normally if we dont have a namespace" do
+ Story.stubs(:cache_namespace).returns(nil)
+ key = "a" * 260
+ Story.cache_key(key).length.should == 250
+ end
+
+ specify "should truncate key with length over 250, including namespace if set" do
+ Story.stubs(:cache_namespace).returns("37-power-moves-app" )
+ key = "a" * 260
+ (Story.cache_namespace + Story.cache_key(key)).length.should == (250 - 1)
+ end
+
+ specify "should raise an informative error message when trying to set_cache with a proc" do
+ Story.cache_config[:store].expects(:set).raises(TypeError.new("Can't marshal Proc"))
+ proc { Story.set_cache('proc:d', proc { nil }) }.should.raise(ActsAsCached::MarshalError)
+ end
+end
+
+context "Passing an array of ids to get_cache" do
+ include StoryCacheSpecSetup
+
+ setup do
+ @grab_stories = proc do
+ @stories = Story.get_cache(1, 2, 3)
+ end
+
+ @keys = 'Story:1', 'Story:2', 'Story:3'
+ @hash = {
+ 'Story:1' => nil,
+ 'Story:2' => $stories[2],
+ 'Story:3' => nil
+ }
+
+ # TODO: doh, probably need to clean this up...
+ @cache = $with_memcache ? CACHE : $cache
+
+ @cache.expects(:get_multi).with(*@keys).returns(@hash)
+ end
+
+ specify "should try to fetch those ids using get_multi" do
+ @grab_stories.call
+
+ @stories.size.should.equal 3
+ @stories.should.be.an.instance_of Hash
+ @stories.each { |id, story| story.should.be.an.instance_of Story }
+ end
+
+ specify "should pass the cache miss ids to #find" do
+ Story.expects(:find).with(%w(1 3)).returns($stories[1], $stories[3])
+ @grab_stories.call
+ end
+end
+
+context "Passing an array of ids to get_cache using a cache which doesn't support get_multi" do
+ include StoryCacheSpecSetup
+
+ setup do
+ @grab_stories = proc do
+ @stories = Story.get_cache(1, 2, 3)
+ end
+
+ # TODO: doh, probably need to clean this up...
+ @cache = $with_memcache ? CACHE : $cache
+ end
+
+ specify "should raise an exception" do
+ class << @cache; undef :get_multi end
+ proc { @grab_stories.call }.should.raise(ActsAsCached::NoGetMulti)
+ end
+end
+
+context "A Ruby object acting as cached" do
+ include StoryCacheSpecSetup
+
+ specify "should be able to retrieve a cached version of itself" do
+ Story.expects(:get_cache).with(1, {}).at_least_once
+ @story.get_cache
+ end
+
+ specify "should be able to set itself to the cache" do
+ Story.expects(:set_cache).with(1, @story, nil).at_least_once
+ @story.set_cache
+ end
+
+ specify "should cache the value of a passed block" do
+ @story.should.not.have.cached :block
+ @story.get_cache(:block) { "this is a block" }
+ @story.should.have.cached :block
+ @story.get_cache(:block).should.equal "this is a block"
+ end
+
+ specify "should allow setting custom options by passing them to get_cache" do
+ Story.expects(:set_cache).with('1:options', 'cached value', 1.hour)
+ @story.get_cache(:options, :ttl => 1.hour) { 'cached value' }
+ end
+
+ specify "should be able to expire its cache" do
+ Story.expects(:expire_cache).with(2)
+ @story2.expire_cache
+ end
+
+ specify "should be able to reset its cache" do
+ Story.expects(:reset_cache).with(2)
+ @story2.reset_cache
+ end
+
+ specify "should be able to tell if it is cached" do
+ @story.should.not.be.cached
+ @story2.should.be.cached
+ end
+
+ specify "should be able to set itself to the cache with an arbitrary ttl" do
+ ttl = 1500
+ Story.expects(:set_cache).with(1, @story, ttl)
+ @story.set_cache(ttl)
+ end
+
+ specify "should be able to cache arbitrary instance methods using caches" do
+ Story.cache_store.expects(:get).returns(nil)
+ Story.cache_store.expects(:set).with('Story:1:something_flashy', :molassy, 1500)
+ @story.caches(:something_flashy).should.equal :molassy
+
+ Story.cache_store.expects(:get).returns(:molassy)
+ Story.cache_store.expects(:set).never
+ @story.caches(:something_flashy).should.equal :molassy
+ end
+end
diff --git a/src/server/vendor/plugins/cache_fu/test/config_test.rb b/src/server/vendor/plugins/cache_fu/test/config_test.rb
new file mode 100644
index 0000000..ff11453
--- /dev/null
+++ b/src/server/vendor/plugins/cache_fu/test/config_test.rb
@@ -0,0 +1,128 @@
+require File.join(File.dirname(__FILE__), 'helper')
+
+context "The global cache configuration" do
+ # Pass in a hash to update the config.
+ # If the first arg is a symbol, an expectation will be set.
+ def setup_config(*args)
+ options = args.last.is_a?(Hash) ? args.pop : {}
+ @config[RAILS_ENV].update options.stringify_keys
+ ActsAsCached::Config.expects(args.first) if args.first.is_a? Symbol
+ ActsAsCached.config = @config
+ end
+
+ setup do
+ ActsAsCached.config.clear
+ @config = YAML.load_file('defaults/memcached.yml.default')
+ @config['test'] = @config['development'].merge('benchmarking' => false, 'disabled' => false)
+ end
+
+ specify "should be able to set itself as the session store" do
+ setup_config :setup_session_store, :sessions => true
+ end
+
+ specify "should be able to set itself as the fragment store" do
+ setup_config :setup_fragment_store!, :fragments => true
+ end
+
+ specify "should construct a namespace from the environment and a config value" do
+ setup_config
+ ActsAsCached.config[:namespace].should.equal "app-#{RAILS_ENV}"
+ end
+
+ specify "should be able to set a global default ttl" do
+ setup_config
+ Story.send :acts_as_cached
+ ActsAsCached.config[:ttl].should.not.be.nil
+ Story.cache_config[:ttl].should.equal ActsAsCached.config[:ttl]
+ end
+
+ specify "should be able to swallow errors" do
+ setup_config :raise_errors => false
+ Story.send :acts_as_cached
+ Story.stubs(:find).returns(Story.new)
+ Story.cache_config[:store].expects(:get).raises(MemCache::MemCacheError)
+ Story.cache_config[:store].expects(:set).returns(true)
+ proc { Story.get_cache(1) }.should.not.raise(MemCache::MemCacheError)
+ end
+
+ specify "should not swallow marshal errors" do
+ setup_config :raise_errors => false
+ Story.send :acts_as_cached
+ Story.stubs(:find).returns(Story.new)
+ Story.cache_config[:store].expects(:get).returns(nil)
+ Story.cache_config[:store].expects(:set).raises(TypeError.new("Some kind of Proc error"))
+ proc { Story.get_cache(1) }.should.raise(ActsAsCached::MarshalError)
+ end
+
+ specify "should be able to re-raise errors" do
+ setup_config :raise_errors => true
+ Story.send :acts_as_cached
+ Story.cache_config[:store].expects(:get).raises(MemCache::MemCacheError)
+ proc { Story.get_cache(1) }.should.raise(MemCache::MemCacheError)
+ end
+
+ specify "should be able to enable benchmarking" do
+ setup_config :benchmarking => true
+ ActsAsCached.config[:benchmarking].should.equal true
+ Story.send :acts_as_cached
+ Story.methods.should.include 'fetch_cache_with_benchmarking'
+ end
+
+ specify "should be able to disable all caching" do
+ setup_config :disabled => true
+ Story.send :acts_as_cached
+ Story.should.respond_to :fetch_cache_with_disabled
+ ActsAsCached.config[:disabled].should.equal true
+ end
+
+ specify "should be able to use a global store other than memcache" do
+ setup_config :store => 'HashStore'
+ ActsAsCached.config[:store].should.equal HashStore.new
+ Story.send :acts_as_cached
+ Story.cache_config[:store].should.be ActsAsCached.config[:store]
+ end
+
+ specify "should be able to override the memcache-client hashing algorithm" do
+ setup_config :fast_hash => true
+ ActsAsCached.config[:fast_hash].should.equal true
+ CACHE.hash_for('eatingsnotcheating').should.equal 1919
+ end
+
+ specify "should be able to override the memcache-client hashing algorithm" do
+ setup_config :fastest_hash => true
+ ActsAsCached.config[:fastest_hash].should.equal true
+ CACHE.hash_for(string = 'eatingsnotcheating').should.equal string.hash
+ end
+
+end
+
+
+context "The class configuration" do
+ # Setups up the Story class with acts_as_cached using options
+ def setup_cached(options = {})
+ Story.send :acts_as_cached, options
+ end
+
+ specify "should save unknown keys as options and not config" do
+ setup_cached :pengiuns => true
+ Story.cache_options.should.include :pengiuns
+ Story.cache_config.should.not.include :pengiuns
+ end
+
+ specify "should be able to override the default finder" do
+ setup_cached :finder => :find_by_title
+ Story.cache_config[:finder].should.equal :find_by_title
+ end
+
+ specify "should be able to override the default cache_id" do
+ setup_cached :cache_id => :title
+ Story.cache_config[:cache_id].should.equal :title
+ end
+
+ specify "should be able to override the default finder and the cache_id using find_by" do
+ setup_cached :find_by => :title
+ Story.cache_config.should.not.include :find
+ Story.cache_config[:finder].should.equal :find_by_title
+ Story.cache_config[:cache_id].should.equal :title
+ end
+end
diff --git a/src/server/vendor/plugins/cache_fu/test/disabled_test.rb b/src/server/vendor/plugins/cache_fu/test/disabled_test.rb
new file mode 100644
index 0000000..547934c
--- /dev/null
+++ b/src/server/vendor/plugins/cache_fu/test/disabled_test.rb
@@ -0,0 +1,40 @@
+require File.join(File.dirname(__FILE__), 'helper')
+
+context "When the cache is disabled" do
+ setup do
+ @story = Story.new(:id => 1, :title => "acts_as_cached 2 released!")
+ @story2 = Story.new(:id => 2, :title => "BDD is something you can use")
+ $stories = { 1 => @story, 2 => @story2 }
+
+ config = YAML.load_file('defaults/memcached.yml.default')
+ config['test'] = config['development'].merge('disabled' => true, 'benchmarking' => false)
+ ActsAsCached.config = config
+ Story.send :acts_as_cached
+ end
+
+ specify "get_cache should call through to the finder" do
+ Story.expects(:find).at_least_once.returns(@story2)
+ @story2.get_cache.should.equal @story2
+ end
+
+ specify "expire_cache should return true" do
+ $cache.expects(:delete).never
+ @story2.expire_cache.should.equal true
+ end
+
+ specify "reset_cache should return the object" do
+ $cache.expects(:set).never
+ Story.expects(:find).at_least_once.returns(@story2)
+ @story2.reset_cache.should.equal @story2
+ end
+
+ specify "set_cache should just return the object" do
+ $cache.expects(:set).never
+ @story2.set_cache.should.equal @story2
+ end
+
+ specify "cached? should return false" do
+ $cache.expects(:get).never
+ @story2.should.not.be.cached
+ end
+end
diff --git a/src/server/vendor/plugins/cache_fu/test/extensions_test.rb b/src/server/vendor/plugins/cache_fu/test/extensions_test.rb
new file mode 100644
index 0000000..b7334ba
--- /dev/null
+++ b/src/server/vendor/plugins/cache_fu/test/extensions_test.rb
@@ -0,0 +1,33 @@
+require File.join(File.dirname(__FILE__), 'helper')
+
+module ActsAsCached
+ module Extensions
+ module ClassMethods
+ def user_defined_class_method
+ true
+ end
+ end
+
+ module InstanceMethods
+ def user_defined_instance_method
+ true
+ end
+ end
+ end
+end
+
+context "When Extensions::ClassMethods exists" do
+ include StoryCacheSpecSetup
+
+ specify "caching classes should extend it" do
+ Story.singleton_methods.should.include 'user_defined_class_method'
+ end
+end
+
+context "When Extensions::InstanceMethods exists" do
+ include StoryCacheSpecSetup
+
+ specify "caching classes should include it" do
+ Story.instance_methods.should.include 'user_defined_instance_method'
+ end
+end
diff --git a/src/server/vendor/plugins/cache_fu/test/fragment_cache_test.rb b/src/server/vendor/plugins/cache_fu/test/fragment_cache_test.rb
new file mode 100644
index 0000000..fb397aa
--- /dev/null
+++ b/src/server/vendor/plugins/cache_fu/test/fragment_cache_test.rb
@@ -0,0 +1,250 @@
+require File.join(File.dirname(__FILE__), 'helper')
+require 'test/unit'
+require 'action_controller/test_process'
+
+ActionController::Routing::Routes.draw do |map|
+ map.connect ':controller/:action/:id'
+end
+
+class FooController < ActionController::Base
+ def url_for(*args)
+ "http://#{Time.now.to_i}.foo.com"
+ end
+end
+
+class BarController < ActionController::Base
+ def page
+ render :text => "give me my bongos"
+ end
+
+ def index
+ render :text => "doop!"
+ end
+
+ def edit
+ render :text => "rawk"
+ end
+
+ def trees_are_swell?
+ true
+ end
+
+ def rescue_action(e)
+ raise e
+ end
+end
+
+class FooTemplate
+ include ::ActionView::Helpers::CacheHelper
+
+ attr_reader :controller
+
+ def initialize
+ @controller = FooController.new
+ end
+end
+
+context "Fragment caching (when used with memcached)" do
+ include FragmentCacheSpecSetup
+
+ setup do
+ @view = FooTemplate.new
+ end
+
+ specify "should be able to cache with a normal, non-keyed Rails cache calls" do
+ _erbout = ""
+ content = "Caching is fun!"
+
+ ActsAsCached.config[:store].expects(:set).with(@view.controller.url_for.gsub('http://',''), content, ActsAsCached.config[:ttl])
+
+ @view.cache { _erbout << content }
+ end
+
+ specify "should be able to cache with a normal cache call when we don't have a default ttl" do
+ begin
+ _erbout = ""
+ content = "Caching is fun!"
+
+ original_ttl = ActsAsCached.config.delete(:ttl)
+ ActsAsCached.config[:store].expects(:set).with(@view.controller.url_for.gsub('http://',''), content, 25.minutes)
+
+ @view.cache { _erbout << content }
+ ensure
+ ActsAsCached.config[:ttl] = original_ttl
+ end
+ end
+
+ specify "should be able to cache with a normal, keyed Rails cache calls" do
+ _erbout = ""
+ content = "Wow, even a key?!"
+ key = "#{Time.now.to_i}_wow_key"
+
+ ActsAsCached.config[:store].expects(:set).with(key, content, ActsAsCached.config[:ttl])
+
+ @view.cache(key) { _erbout << content }
+ end
+
+ specify "should be able to cache with new time-to-live option" do
+ _erbout = ""
+ content = "Time to live? TIME TO DIE!!"
+ key = "#{Time.now.to_i}_death_key"
+
+ ActsAsCached.config[:store].expects(:set).with(key, content, 60)
+ @view.cache(key, { :ttl => 60 }) { _erbout << content }
+ end
+
+ specify "should ignore everything but time-to-live when options are present" do
+ _erbout = ""
+ content = "Don't mess around, here, sir."
+ key = "#{Time.now.to_i}_mess_key"
+
+ ActsAsCached.config[:store].expects(:set).with(key, content, 60)
+ @view.cache(key, { :other_options => "for the kids", :ttl => 60 }) { _erbout << content }
+ end
+
+ specify "should be able to skip cache gets" do
+ ActsAsCached.skip_cache_gets = true
+ ActsAsCached.config[:store].expects(:get).never
+ _erbout = ""
+ @view.cache { _erbout << "Caching is fun!" }
+ ActsAsCached.skip_cache_gets = false
+ end
+end
+
+context "Action caching (when used with memcached)" do
+ include FragmentCacheSpecSetup
+ page_content = "give me my bongos"
+ index_content = "doop!"
+ edit_content = "rawk"
+
+ setup do
+ @controller = BarController.new
+ @request = ActionController::TestRequest.new
+ @response = ActionController::TestResponse.new
+ end
+
+ teardown do # clear the filter chain between specs to avoid chaos
+ BarController.write_inheritable_attribute('filter_chain', [])
+ end
+
+ # little helper for prettier expections on the cache
+ def cache_expects(method, expected_times = 1)
+ ActsAsCached.config[:store].expects(method).times(expected_times)
+ end
+
+ specify "should cache using default ttl for a normal action cache without ttl" do
+ BarController.caches_action :page
+
+ key = 'test.host/bar/page'
+ cache_expects(:set).with(key, page_content, ActsAsCached.config[:ttl])
+ get :page
+ @response.body.should == page_content
+
+ cache_expects(:read).with(key, nil).returns(page_content)
+ get :page
+ @response.body.should == page_content
+ end
+
+ specify "should cache using defaul ttl for normal, multiple action caches" do
+ BarController.caches_action :page, :index
+
+ cache_expects(:set).with('test.host/bar/page', page_content, ActsAsCached.config[:ttl])
+ get :page
+ cache_expects(:set).with('test.host/bar', index_content, ActsAsCached.config[:ttl])
+ get :index
+ end
+
+ specify "should be able to action cache with ttl" do
+ BarController.caches_action :page => { :ttl => 2.minutes }
+
+ cache_expects(:set).with('test.host/bar/page', page_content, 2.minutes)
+ get :page
+ @response.body.should == page_content
+ end
+
+ specify "should be able to action cache multiple actions with ttls" do
+ BarController.caches_action :index, :page => { :ttl => 5.minutes }
+
+ cache_expects(:set).with('test.host/bar/page', page_content, 5.minutes)
+ cache_expects(:set).with('test.host/bar', index_content, ActsAsCached.config[:ttl])
+
+ get :page
+ @response.body.should == page_content
+
+ get :index
+ @response.body.should == index_content
+ cache_expects(:read).with('test.host/bar', nil).returns(index_content)
+
+ get :index
+ end
+
+ specify "should be able to action cache conditionally when passed something that returns true" do
+ BarController.caches_action :page => { :if => :trees_are_swell? }
+
+ cache_expects(:set).with('test.host/bar/page', page_content, ActsAsCached.config[:ttl])
+
+ get :page
+ @response.body.should == page_content
+
+ cache_expects(:read).with('test.host/bar/page', nil).returns(page_content)
+
+ get :page
+ end
+
+ #check for edginess
+ if [].respond_to?(:extract_options!)
+ specify "should not break cache_path overrides" do
+ BarController.caches_action :page, :cache_path => 'http://test.host/some/custom/path'
+ cache_expects(:set).with('test.host/some/custom/path', page_content, ActsAsCached.config[:ttl])
+ get :page
+ end
+
+ specify "should not break cache_path block overrides" do
+ BarController.caches_action :edit, :cache_path => Proc.new { |c| c.params[:id] ? "http://test.host/#{c.params[:id]}/edit" : "http://test.host/edit" }
+ cache_expects(:set).with('test.host/edit', edit_content, ActsAsCached.config[:ttl])
+ get :edit
+
+ get :index
+ cache_expects(:set).with('test.host/5/edit', edit_content, ActsAsCached.config[:ttl])
+ get :edit, :id => 5
+ end
+
+ specify "should play nice with custom ttls and cache_path overrides" do
+ BarController.caches_action :page => { :ttl => 5.days }, :cache_path => 'http://test.host/my/custom/path'
+ cache_expects(:set).with('test.host/my/custom/path', page_content, 5.days)
+ get :page
+ end
+
+ specify "should play nice with custom ttls and cache_path block overrides" do
+ BarController.caches_action :edit, :cache_path => Proc.new { |c| c.params[:id] ? "http://test.host/#{c.params[:id]}/edit" : "http://test.host/edit" }
+ cache_expects(:set).with('test.host/5/edit', edit_content, ActsAsCached.config[:ttl])
+ get :edit, :id => 5
+ end
+
+ specify "should play nice with the most complicated thing i can throw at it" do
+ BarController.caches_action :index => { :ttl => 24.hours }, :page => { :ttl => 5.seconds }, :edit => { :ttl => 5.days }, :cache_path => Proc.new { |c| c.params[:id] ? "http://test.host/#{c.params[:id]}/#{c.params[:action]}" : "http://test.host/#{c.params[:action]}" }
+ cache_expects(:set).with('test.host/index', index_content, 24.hours)
+ get :index
+ cache_expects(:set).with('test.host/5/edit', edit_content, 5.days)
+ get :edit, :id => 5
+ cache_expects(:set).with('test.host/5/page', page_content, 5.seconds)
+ get :page, :id => 5
+
+ cache_expects(:read).with('test.host/5/page', nil).returns(page_content)
+ get :page, :id => 5
+ cache_expects(:read).with('test.host/5/edit', nil).returns(edit_content)
+ get :edit, :id => 5
+ cache_expects(:read).with('test.host/index', nil).returns(index_content)
+ get :index
+ end
+ end
+
+ specify "should be able to skip action caching when passed something that returns false" do
+ BarController.caches_action :page => { :if => Proc.new {|c| !c.trees_are_swell?} }
+
+ cache_expects(:set, 0).with('test.host/bar/page', page_content, ActsAsCached.config[:ttl])
+
+ get :page
+ @response.body.should == page_content
+ end
+end
diff --git a/src/server/vendor/plugins/cache_fu/test/helper.rb b/src/server/vendor/plugins/cache_fu/test/helper.rb
new file mode 100644
index 0000000..299e514
--- /dev/null
+++ b/src/server/vendor/plugins/cache_fu/test/helper.rb
@@ -0,0 +1,215 @@
+##
+# This file exists to fake out all the Railsisms we use so we can run the
+# tests in isolation.
+$LOAD_PATH.unshift 'lib/'
+#
+
+begin
+ require 'rubygems'
+ gem 'mocha', '>= 0.4.0'
+ require 'mocha'
+ gem 'test-spec', '= 0.3.0'
+ require 'test/spec'
+ require 'multi_rails_init'
+rescue LoadError
+ puts '=> acts_as_cached tests depend on the following gems: mocha (0.4.0+), test-spec (0.3.0), multi_rails (0.0.2), and rails.'
+end
+
+begin
+ require 'redgreen'
+rescue LoadError
+ nil
+end
+
+Test::Spec::Should.send :alias_method, :have, :be
+Test::Spec::ShouldNot.send :alias_method, :have, :be
+
+##
+# real men test without mocks
+if $with_memcache = ARGV.include?('with-memcache')
+ require 'memcache'
+end
+
+##
+# init.rb hacks
+RAILS_ROOT = '.' unless defined? RAILS_ROOT
+RAILS_ENV = 'test' unless defined? RAILS_ENV
+
+##
+# get the default config using absolute path, so tests all play nice when run in isolation
+DEFAULT_CONFIG_FILE = File.expand_path(File.dirname(__FILE__) + '/../defaults/memcached.yml.default')
+
+##
+# aac
+require 'acts_as_cached'
+Object.send :include, ActsAsCached::Mixin
+
+##
+# i need you.
+module Enumerable
+ def index_by
+ inject({}) do |accum, elem|
+ accum[yield(elem)] = elem
+ accum
+ end
+ end
+end
+
+##
+# mocky.
+class HashStore < Hash
+ alias :get :[]
+
+ def get_multi(*values)
+ reject { |k,v| !values.include? k }
+ end
+
+ def set(key, value, *others)
+ self[key] = value
+ end
+
+ def namespace
+ nil
+ end
+end
+
+$cache = HashStore.new
+
+class Story
+ acts_as_cached($with_memcache ? {} : { :store => $cache })
+
+ attr_accessor :id, :title
+
+ def initialize(attributes = {})
+ attributes.each { |key, value| instance_variable_set("@#{key}", value) }
+ end
+
+ def attributes
+ { :id => id, :title => title }
+ end
+
+ def ==(other)
+ return false unless other.respond_to? :attributes
+ attributes == other.attributes
+ end
+
+ def self.find(*args)
+ options = args.last.is_a?(Hash) ? args.pop : {}
+
+ if (ids = args.flatten).size > 1
+ ids.map { |id| $stories[id.to_i] }
+ elsif (id = args.flatten.first).to_i.to_s == id.to_s
+ $stories[id.to_i]
+ end
+ end
+
+ def self.find_by_title(*args)
+ title = args.shift
+ find(args).select { |s| s.title == title }
+ end
+
+ def self.base_class
+ Story
+ end
+
+ def self.something_cool; :redbull end
+ def something_flashy; :molassy end
+
+ def self.block_on(target = nil)
+ target || :something
+ end
+
+ def self.pass_through(target)
+ target
+ end
+
+ def self.two_params(first, second)
+ "first: #{first} | second: #{second}"
+ end
+
+ def self.find_live(*args) false end
+end
+
+class Feature < Story; end
+class Interview < Story; end
+
+module ActionController
+ class Base
+ def rendering_runtime(*args) '' end
+ def self.silence; yield end
+ end
+end
+
+class MemCache
+ attr_accessor :servers
+ def initialize(*args) end
+ class MemCacheError < StandardError; end unless defined? MemCacheError
+end unless $with_memcache
+
+module StoryCacheSpecSetup
+ def self.included(base)
+ base.setup do
+ setup_cache_spec
+ Story.instance_eval { @max_key_length = nil }
+ end
+ end
+
+ def setup_cache_spec
+ @story = Story.new(:id => 1, :title => "acts_as_cached 2 released!")
+ @story2 = Story.new(:id => 2, :title => "BDD is something you can use")
+ @story3 = Story.new(:id => 3, :title => "RailsConf is overrated.")
+ $stories = { 1 => @story, 2 => @story2, 3 => @story3 }
+
+ $with_memcache ? with_memcache : with_mock
+ end
+
+ def with_memcache
+ unless $mc_setup_for_story_cache_spec
+ ActsAsCached.config.clear
+ config = YAML.load_file(DEFAULT_CONFIG_FILE)
+ config['test'] = config['development'].merge('benchmarking' => false, 'disabled' => false)
+ ActsAsCached.config = config
+ $mc_setup_for_story_cache_spec = true
+ end
+
+ Story.send :acts_as_cached
+ Story.expire_cache(1)
+ Story.expire_cache(2)
+ Story.expire_cache(3)
+ Story.expire_cache(:block)
+ Story.set_cache(2, @story2)
+ end
+
+ def with_mock
+ $cache.clear
+
+ Story.send :acts_as_cached, :store => $cache
+ $cache['Story:2'] = @story2
+ end
+end
+
+module FragmentCacheSpecSetup
+ def self.included(base)
+ base.setup { setup_fragment_spec }
+ end
+
+ def setup_fragment_spec
+ unless $mc_setup_for_fragment_cache_spec
+ ActsAsCached.config.clear
+ config = YAML.load_file(DEFAULT_CONFIG_FILE)
+
+ if $with_memcache
+ other_options = { 'fragments' => true }
+ else
+ Object.const_set(:CACHE, $cache) unless defined? CACHE
+ other_options = { 'fragments' => true, 'store' => $cache }
+ end
+
+ config['test'] = config['development'].merge other_options
+
+ ActsAsCached.config = config
+ ActsAsCached::FragmentCache.setup!
+ $mc_setup_for_fragment_cache_spec = true
+ end
+ end
+end
diff --git a/src/server/vendor/plugins/cache_fu/test/local_cache_test.rb b/src/server/vendor/plugins/cache_fu/test/local_cache_test.rb
new file mode 100644
index 0000000..82b57ce
--- /dev/null
+++ b/src/server/vendor/plugins/cache_fu/test/local_cache_test.rb
@@ -0,0 +1,43 @@
+require File.join(File.dirname(__FILE__), 'helper')
+
+context "When local_cache_for_request is called" do
+ include StoryCacheSpecSetup
+
+ setup do
+ ActionController::Base.new.local_cache_for_request
+ $cache = CACHE if $with_memcache
+ end
+
+ specify "get_cache should pull from the local cache on a second hit" do
+ $cache.expects(:get).with('Story:2').returns(@story2)
+ @story2.get_cache
+ $cache.expects(:get).never
+ @story2.get_cache
+ end
+
+ specify "set_cache should set to the local cache" do
+ $cache.expects(:set).at_least_once.returns(@story)
+ ActsAsCached::LocalCache.local_cache.expects(:[]=).with('Story:1', @story).returns(@story)
+ @story.set_cache
+ end
+
+ specify "expire_cache should clear from the local cache" do
+ @story2.get_cache
+ $cache.expects(:delete).at_least_once
+ ActsAsCached::LocalCache.local_cache.expects(:delete).with('Story:2')
+ @story2.expire_cache
+ end
+
+ specify "clear_cache should clear from the local cache" do
+ @story2.get_cache
+ $cache.expects(:delete).at_least_once
+ ActsAsCached::LocalCache.local_cache.expects(:delete).with('Story:2')
+ @story2.clear_cache
+ end
+
+ specify "cached? should check the local cache" do
+ @story2.get_cache
+ $cache.expects(:get).never
+ @story2.cached?
+ end
+end
diff --git a/src/server/vendor/plugins/cache_fu/test/sti_test.rb b/src/server/vendor/plugins/cache_fu/test/sti_test.rb
new file mode 100644
index 0000000..1736938
--- /dev/null
+++ b/src/server/vendor/plugins/cache_fu/test/sti_test.rb
@@ -0,0 +1,36 @@
+require File.join(File.dirname(__FILE__), 'helper')
+
+context "An STI subclass acting as cached" do
+ include StoryCacheSpecSetup
+
+ setup do
+ @feature = Feature.new(:id => 3, :title => 'Behind the scenes of acts_as_cached')
+ @interview = Interview.new(:id => 4, :title => 'An interview with the Arcade Fire')
+ @feature.expire_cache
+ @interview.expire_cache
+ $stories.update 3 => @feature, 4 => @interview
+ end
+
+ specify "should be just as retrievable as any other cachable Ruby object" do
+ Feature.cached?(3).should.equal false
+ Feature.get_cache(3)
+ Feature.cached?(3).should.equal true
+ end
+
+ specify "should have a key corresponding to its parent class" do
+ @feature.cache_key.should.equal "Story:3"
+ @interview.cache_key.should.equal "Story:4"
+ end
+
+ specify "should be able to get itself from the cache via its parent class" do
+ Story.get_cache(3).should.equal @feature
+ Story.get_cache(4).should.equal @interview
+ end
+
+ specify "should take on its parents cache options but be able to set its own" do
+ @feature.cache_key.should.equal "Story:3"
+ Feature.cache_config[:version] = 1
+ @feature.cache_key.should.equal "Story:1:3"
+ @story.cache_key.should.equal "Story:1"
+ end
+end
|
parabuzzle/cistern
|
9c07cdf413eb0ff5d594adacc74336ebedfe2cff
|
Fixed issue 6 for localhost in hostname bug
|
diff --git a/src/server/app/models/agent.rb b/src/server/app/models/agent.rb
index 9b23267..8c08f7d 100644
--- a/src/server/app/models/agent.rb
+++ b/src/server/app/models/agent.rb
@@ -1,37 +1,37 @@
class Agent < ActiveRecord::Base
acts_as_ferret :fields => [:hostname, :name, :port]
has_and_belongs_to_many :logtypes, :join_table => :agents_logtypes
has_many :events
#Validations
validates_presence_of :hostname, :port, :name
- validates_format_of :hostname, :with => /([A-Z0-9-]+\.)+[A-Z]{2,4}$/i
+ #validates_format_of :hostname, :with => /([A-Z0-9-]+\.)+[A-Z]{2,4}$/i
validates_uniqueness_of :name
def add_logtype(logtype)
if self.logtypes.find_by_logtype_id('logtype.id') == nil
ActiveRecord::Base.connection.execute("insert into agents_logtypes (logtype_id,agent_id)values('#{logtype.id}','#{self.id}')")
end
return logtype
end
def remove_logtype(logtype)
if self.logtypes.find_by_logtype_id('logtype.id') != nil
ActiveRecord::Base.connection.execute("delete from agents_logtypes where logtype_id = '#{logtype.id}' and agent_id = '#{self.id}'")
end
return logtype
end
def logtype_member?(logtype)
flag = 0
self.logtypes.each do |log|
if log.id == logtype.id
flag = 1
end
end
return flag
end
end
|
parabuzzle/cistern
|
999d2ff9f870643dc25656f81adc7b27c7bc3479
|
Made the view pretty and fixed up the search a bunch
|
diff --git a/src/server/app/controllers/agents_controller.rb b/src/server/app/controllers/agents_controller.rb
index 2c50a0e..84ebb4d 100644
--- a/src/server/app/controllers/agents_controller.rb
+++ b/src/server/app/controllers/agents_controller.rb
@@ -1,71 +1,85 @@
class AgentsController < ApplicationController
def index
@title = "Agents"
@agents = Agent.paginate :all, :per_page => params[:perpage], :page => params[:page]
end
def show
@agent = Agent.find(params[:id])
+ if request.post?
+ redirect_to :action => "search", :id => params[:id], :aquery => params[:search][:data]
+ end
@title = "All Events for #{@agent.name}"
if params[:logtype].nil? and params[:loglevel].nil?
@event = @agent.events.paginate :all, :per_page => params[:perpage], :page => params[:page]
elsif !params[:logtype].nil? and params[:loglevel].nil?
@event = @agent.events.paginate :all, :per_page => params[:perpage], :page => params[:page], :conditions => "logtype_id = '#{params[:logtype]}'"
elsif params[:logtype].nil? and !params[:loglevel].nil?
@event = @agent.events.paginate :all, :per_page => params[:perpage], :page => params[:page], :conditions => "loglevel_id <= '#{params[:loglevel]}'"
else
@event = @agent.events.paginate :all, :per_page => params[:perpage], :page => params[:page], :conditions => "logtype_id = '#{params[:logtype]}' and loglevel_id <= '#{params[:loglevel]}'"
end
@events = rebuildevents(@event)
end
+ def search
+ if params[:aquery].nil?
+ redirect_to :action => 'show', :id => params[:id]
+ else
+ @title = "Search Results"
+ @agent = Agent.find(params[:id])
+ @total = @agent.events.find_with_ferret(params[:aquery]).length
+ @results = @agent.events.paginate(params[:aquery], {:finder => "find_with_ferret", :total_entries => @total}.merge({:page => params[:page], :per_page => params[:per_page]}))
+ end
+ end
+
def new
if request.post?
@agent = Agent.new(params[:agent])
@agent.authkey = Digest::MD5.hexdigest(@agent.hostname + Time.now.to_s)
if @agent.save
flash[:notice] = "Agent #{@agent.name} added -- don't forget to edit your agent to add it to your logtypes"
redirect_to :action => "index"
else
flash[:error] = "There were errors creating your agent"
end
else
@title = "Create New Agent"
end
end
def edit
@agent = Agent.find(params[:id])
if request.post?
params[:agent][:logtype_ids] ||= []
@agent.update_attributes(params[:agent])
if @agent.save
flash[:notice] = "Agent #{@agent.name} updated"
redirect_to :action => "index"
else
flash[:error] = "There were errors updating your agent"
end
else
@title = "Edit #{@agent.name}"
end
end
def delete
@agent = params[:id]
if request.post?
if @agent.destroy
flash[:notice] = "Agent deleted"
redirect_to :action => "index"
else
flash[:error] = "Error trying to delete agent"
redirect_to :action => "index"
end
else
flash[:error] = "Poking around is never a good idea"
redirect_to :action => "index"
end
end
end
diff --git a/src/server/app/controllers/events_controller.rb b/src/server/app/controllers/events_controller.rb
index 984026c..f88f165 100644
--- a/src/server/app/controllers/events_controller.rb
+++ b/src/server/app/controllers/events_controller.rb
@@ -1,16 +1,20 @@
class EventsController < ApplicationController
include EventsHelper
def index
@title = "Events"
@logtypes = Logtype.all
@agents = Agent.all
end
def show
@title = "All Events"
- @event = Event.paginate :all, :per_page => params[:perpage], :page => params[:page]
+ unless params[:loglevel].nil?
+ @event = Event.paginate :all, :per_page => params[:perpage], :page => params[:page], :conditions => "loglevel_id <= '#{params[:loglevel]}'"
+ else
+ @event = Event.paginate :all, :per_page => params[:perpage], :page => params[:page]
+ end
@events = rebuildevents(@event)
end
end
diff --git a/src/server/app/controllers/logtypes_controller.rb b/src/server/app/controllers/logtypes_controller.rb
index 9212f87..0e23544 100644
--- a/src/server/app/controllers/logtypes_controller.rb
+++ b/src/server/app/controllers/logtypes_controller.rb
@@ -1,64 +1,78 @@
class LogtypesController < ApplicationController
def index
@title = "Logtypes"
@logtypes = Logtype.paginate :all, :per_page => params[:perpage], :page => params[:page]
end
def show
@logtype = Logtype.find(params[:id])
+ if request.post?
+ redirect_to :action => "search", :id => params[:id], :aquery => params[:search][:data]
+ end
@title = "All Events for #{@logtype.name}"
if params[:loglevel].nil?
@event = @logtype.events.paginate :all, :per_page => params[:perpage], :page => params[:page]
else
@event = @logtype.events.paginate :all, :per_page => params[:perpage], :page => params[:page], :conditions => "loglevel_id <= '#{params[:loglevel]}'"
end
@events = rebuildevents(@event)
end
+ def search
+ if params[:aquery].nil?
+ redirect_to :action => 'show', :id => params[:id]
+ else
+ @title = "Search Results"
+ @logtype = Logtype.find(params[:id])
+ @total = @logtype.events.find_with_ferret(params[:aquery]).length
+ @results = @logtype.events.paginate(params[:aquery], {:finder => "find_with_ferret", :total_entries => @total}.merge({:page => params[:page], :per_page => params[:per_page]}))
+ end
+ end
+
def new
if request.post?
@logtype = Logtype.new(params[:logtype])
if @logtype.save
flash[:notice] = "Logtype #{@logtype.name} added"
redirect_to :action => "index"
else
flash[:error] = "There were errors creating your logtype"
end
else
@title = "Create New Logtype"
end
end
def edit
@logtype = Logtype.find(params[:id])
if request.post?
@logtype.update_attributes(params[:logtype])
if @logtype.save
flash[:notice] = "Logtype #{@logtype.name} updated"
redirect_to :action => "index"
else
flash[:error] = "There were errors updating your logtype"
end
else
@title = "Edit #{@logtype.name}"
end
end
def delete
@logtype = params[:id]
if request.post?
if @logtype.destroy
flash[:notice] = "Logtype deleted"
redirect_to :action => "index"
else
flash[:error] = "Error trying to delete logtype"
redirect_to :action => "index"
end
else
flash[:error] = "Poking around is never a good idea"
redirect_to :action => "index"
end
end
end
diff --git a/src/server/app/controllers/search_controller.rb b/src/server/app/controllers/search_controller.rb
index a133f45..0e1f83c 100644
--- a/src/server/app/controllers/search_controller.rb
+++ b/src/server/app/controllers/search_controller.rb
@@ -1,52 +1,33 @@
class SearchController < ApplicationController
include ApplicationHelper
include SearchHelper
+
def index
@title = "Search for Events"
if request.post?
if params[:loglevel_ids] == "off"
params[:loglevel_ids] = nil
end
if params[:logtype_ids] == "off"
params[:logtype_ids] = nil
end
if params[:agent_ids] == "off"
params[:agent_ids] = nil
end
#params[:search][:data]
redirect_to :action => 'show', :query => params[:search][:data], :loglevel => params[:loglevel_ids], :logtype => params[:logtype_ids], :agent => params[:agent_ids]
end
end
def show
if params[:query].nil?
redirect_to :action => 'index'
else
@title = "Search Results"
- if !params[:loglevel].nil?
- loglevel = params[:loglevel]
- end
- if !params[:logtype].nil?
- logtype = params[:logtype]
- end
- if !params[:agent].nil?
- agent = params[:agent]
- end
- #@results = Agent.find(agent).events.find_with_ferret(params[:query])
- r = Event.find_with_ferret(params[:query])
- @results = Array.new
- if !agent.nil?
- r = filter_agent(r,agent.to_i)
- end
- if !logtype.nil?
- r = filter_logtype(r,logtype.to_i)
- end
- if !loglevel.nil?
- r = filter_loglevel(r,loglevel.to_i)
- end
- @results = r
+ @total = Event.total_hits(params[:query])
+ @results = Event.paginate(params[:query], {:finder => "find_with_ferret", :total_entries => @total}.merge({:page => params[:page], :per_page => params[:per_page]}))
end
end
end
diff --git a/src/server/app/views/agents/edit.rhtml b/src/server/app/views/agents/edit.rhtml
index 880f888..d536f15 100644
--- a/src/server/app/views/agents/edit.rhtml
+++ b/src/server/app/views/agents/edit.rhtml
@@ -1,34 +1,34 @@
<h1>Edit <%=@agent.name%></h1>
<%= error_messages_for 'agent' %>
<div id="form">
<table width="100%">
<% form_for :agent do |f|%>
<tr>
<td>Name:</td>
<td align="right"><%= f.text_field :name, :class => "fbox"%></td>
</tr>
<tr>
<td>Hostname:</td>
<td align="right"><%= f.text_field :hostname, :class => "fbox"%></td>
</tr>
<tr>
<td>Port:</td>
<td align="right"><%= f.text_field :port, :class => "fbox"%></td>
</tr>
<tr>
<td>Key:</td>
<td align="right"><%= f.text_field :authkey, :class => "fbox"%></td>
</tr>
</table>
-
+ <div class="adendem">note: changing the key is not recommended.</div>
<div class="agent">Logtypes</div>
<% for log in Logtype.find(:all) %>
<div class="agents">
<%= check_box_tag "agent[logtype_ids][]", log.id, @agent.logtypes.include?(log) %> <%= log.name %>
</div>
<%end%>
<div class="agent"><%= submit_tag "Update Agent", :class => "submitbutton" %></div>
<%end%>
</div>
\ No newline at end of file
diff --git a/src/server/app/views/agents/search.rhtml b/src/server/app/views/agents/search.rhtml
new file mode 100644
index 0000000..3e2f48b
--- /dev/null
+++ b/src/server/app/views/agents/search.rhtml
@@ -0,0 +1,16 @@
+<h1>Search Results</h1>
+<div id="totalhits">Found <%=@total%> matching results</div>
+<div id="events">
+<% for event in @results do %>
+ <div class="event">
+ <a href="#" onclick="$('.eventinfo<%=event.id%>').toggle();return false"><%= if params[:withepoch] then event.etime else Time.at(event.etime.to_f) end %></a> : <%= event.loglevel.name %> ::
+ <%=event.full_event%>
+ <div class="eventinfo<%=event.id%>" style="display:none; background:#FF9; border:1px solid #000; padding:5px; width:50%">
+ <div class="info">Agent: <%=link_to(event.agent.name, :controller => "agents", :action => "show", :id => event.agent.id)%></div>
+ <div class="info">Logtype: <%=link_to(event.staticentry.logtype.name, :controller => "logtypes", :action => "show", :id => event.staticentry.logtype.id)%></div>
+ <div class="info">Static Entry Id: <%=event.staticentry_id%></div>
+ </div>
+ </div>
+<%end%>
+</div>
+<%=will_paginate @results%>
\ No newline at end of file
diff --git a/src/server/app/views/agents/show.rhtml b/src/server/app/views/agents/show.rhtml
index 351b880..ff45d2c 100644
--- a/src/server/app/views/agents/show.rhtml
+++ b/src/server/app/views/agents/show.rhtml
@@ -1,37 +1,52 @@
+<div class="rightsearch">
+ <div>
+ <% form_for :search, :url => { :id => params[:id]} do |form| %>
+ <div>Search within Agent</div>
+ <div><%= form.text_field :data, :size => 20, :class => "minisearchbox" %> </div>
+ <%end%>
+ </div>
+</div>
+<div class="clear"></div>
<h1>All Events for <%=@agent.name%></h1>
+
<div id="filter">
<% if params[:logtype]%>
Current filter: <%= Logtype.find(params[:logtype]).name%>
<%else%>
Filter by logtype:
<% for type in @agent.logtypes.all do %>
<%= link_to( type.name, :logtype => type.id, :withepoch => params[:withepoch] )%>
<%end%>
<%end%>
<div class="adendem">
<%= link_to("Clear filter", :logtype => nil, :withepoch => params[:withepoch])%>
</div>
</div>
-<div id="eventlist">
- <ul>
- <% for event in @events do %>
- <li><%= if params[:withepoch] then event.etime else Time.at(event.etime.to_f) end %> : <%= event.loglevel.name%> <%=event.payload%></li>
- <%end%>
- </ul>
+<div id="events">
+<% for event in @events do %>
+ <div class="event">
+ <a href="#" onclick="$('.eventinfo<%=event.id%>').toggle();return false"><%= if params[:withepoch] then event.etime else Time.at(event.etime.to_f) end %></a> : <%= link_to(event.loglevel.name, :action => "show", :loglevel => event.loglevel.id, :withepoch => params[:withepoch])%> ::
+ <%=event.payload%>
+ <div class="eventinfo<%=event.id%>" style="display:none; background:#FF9; border:1px solid #000; padding:5px; width:50%">
+ <div class="info">Logtype: <%=link_to(event.staticentry.logtype.name, :controller => "logtypes", :action => "show", :id => event.staticentry.logtype.id)%></div>
+ <div class="info">Static Entry Id: <%=event.staticentry_id%></div>
+ </div>
+ </div>
+<%end%>
</div>
<div class="pagination">
<%= will_paginate @event %>
</div>
<div class="adendem">
Records per page:
<%=link_to "20", :withepoch => params[:withepoch], :page => 1, :perpage => "20" %> |
<%=link_to "50", :withepoch => params[:withepoch], :page => 1, :perpage => "50" %> |
<%=link_to "100", :withepoch => params[:withepoch], :page => 1, :perpage => "100" %> |
<%=link_to "200", :withepoch => params[:withepoch], :page => 1, :perpage => "200" %>
</div>
<%if params[:withepoch]%>
<div class="adendem"><%=link_to "show regular time", :withepoch => nil, :page => params[:page], :perpage => params[:perpage], :logtype => params[:logtype] %></div>
<%else%>
<div class="adendem"><%=link_to "show epoch time", :withepoch => 1, :page => params[:page], :perpage => params[:perpage], :logtype => params[:logtype] %></div>
<%end%>
\ No newline at end of file
diff --git a/src/server/app/views/events/show.rhtml b/src/server/app/views/events/show.rhtml
index 92b14ba..86afb20 100644
--- a/src/server/app/views/events/show.rhtml
+++ b/src/server/app/views/events/show.rhtml
@@ -1,25 +1,36 @@
<h1>All Events</h1>
-<ul>
+<%unless params[:loglevel].nil?%>
+<div class="adendem"><%=link_to("clear filters", :action => "show", :loglevel => nil)%></div>
+<%end%>
+<div id="events">
<% for event in @events do %>
- <li><%= if params[:withepoch] then event.etime else Time.at(event.etime.to_f) end %> : <%= event.loglevel.name%> <%=event.payload%></li>
+ <div class="event">
+ <a href="#" onclick="$('.eventinfo<%=event.id%>').toggle();return false"><%= if params[:withepoch] then event.etime else Time.at(event.etime.to_f) end %></a> : <%= link_to(event.loglevel.name, :action => "show", :loglevel => event.loglevel.id, :withepoch => params[:withepoch])%> ::
+ <%=event.payload%>
+ <div class="eventinfo<%=event.id%>" style="display:none; background:#FF9; border:1px solid #000; padding:5px; width:50%">
+ <div class="info">Agent: <%=link_to(event.agent.name, :controller => "agents", :action => "show", :id => event.agent.id)%></div>
+ <div class="info">Logtype: <%=link_to(event.staticentry.logtype.name, :controller => "logtypes", :action => "show", :id => event.staticentry.logtype.id)%></div>
+ <div class="info">Static Entry Id: <%=event.staticentry_id%></div>
+ </div>
+ </div>
<%end%>
-</ul>
+</div>
<div class="pagination">
<%= will_paginate @event %>
</div>
<div class="adendem">
Records per page:
- <%=link_to "20", :withepoch => params[:withepoch], :page => 1, :perpage => "20" %> |
- <%=link_to "50", :withepoch => params[:withepoch], :page => 1, :perpage => "50" %> |
- <%=link_to "100", :withepoch => params[:withepoch], :page => 1, :perpage => "100" %> |
- <%=link_to "200", :withepoch => params[:withepoch], :page => 1, :perpage => "200" %>
+ <%=link_to "20", :loglevel => params[:loglevel], :withepoch => params[:withepoch], :page => 1, :perpage => "20" %> |
+ <%=link_to "50", :loglevel => params[:loglevel], :withepoch => params[:withepoch], :page => 1, :perpage => "50" %> |
+ <%=link_to "100", :loglevel => params[:loglevel], :withepoch => params[:withepoch], :page => 1, :perpage => "100" %> |
+ <%=link_to "200", :loglevel => params[:loglevel], :withepoch => params[:withepoch], :page => 1, :perpage => "200" %>
</div>
<%if params[:withepoch]%>
- <div class="adendem"><%=link_to "show regular time", :withepoch => nil, :page => params[:page], :perpage => params[:perpage] %></div>
+ <div class="adendem"><%=link_to "show regular time", :withepoch => nil, :loglevel => params[:loglevel], :page => params[:page], :perpage => params[:perpage] %></div>
<%else%>
- <div class="adendem"><%=link_to "show epoch time", :withepoch => 1, :page => params[:page], :perpage => params[:perpage] %></div>
+ <div class="adendem"><%=link_to "show epoch time", :withepoch => 1, :loglevel => params[:loglevel], :page => params[:page], :perpage => params[:perpage] %></div>
<%end%>
<div class="adendem"><%=link_to "view by agent", :controller => 'agents', :action => "index" %> | <%=link_to "view by logtype", :controller => 'logtypes', :action => 'index' %></div>
diff --git a/src/server/app/views/logtypes/edit.rhtml b/src/server/app/views/logtypes/edit.rhtml
index 7b67d10..9136210 100644
--- a/src/server/app/views/logtypes/edit.rhtml
+++ b/src/server/app/views/logtypes/edit.rhtml
@@ -1,18 +1,22 @@
<h1>Edit <%=@logtype.name%></h1>
<%= error_messages_for 'logtype' %>
<div id="form">
<table width="100%">
<% form_for :logtype do |f|%>
<tr>
<td>Name:</td>
<td align="right"><%= f.text_field :name, :class => "fbox"%></td>
</tr>
+ <tr>
+ <td>Description:</td>
+ <td align="right"><%= f.text_field :description, :class => "fbox"%></td>
+ </tr>
<tr>
<td><%= submit_tag "Update Logtype", :class => "submitbutton" %></td>
<td></td>
</tr>
<%end%>
</table>
</div>
\ No newline at end of file
diff --git a/src/server/app/views/logtypes/index.rhtml b/src/server/app/views/logtypes/index.rhtml
index 1cc188e..abeaa4d 100644
--- a/src/server/app/views/logtypes/index.rhtml
+++ b/src/server/app/views/logtypes/index.rhtml
@@ -1,20 +1,21 @@
<h1>Logtypes</h1>
<div class="subnav"><%=link_to("Create new Logtype", :action => "new")%></div>
<div class="clear"></div>
<% for type in @logtypes do%>
<div class="agent">
<a href='#' onclick="$('.typeinfo<%=type.id%>').toggle();return false"><%=type.name%></a> : <%=link_to("View Events", :action=>"show", :id=>type.id)%>
<div class="typeinfo<%=type.id%>" style="display:none; background:#FF9; padding: 3px; border: 1px solid #000">
+ <div class="info">Description: <%=type.description%></div>
<div class="info">Total Events: <%= type.events.count %></div>
<div class="info">Total Agents: <%=type.agents.count%></div>
<div class="info"><%=link_to("edit", :action => "edit", :id => type.id)%></div>
</div>
</div>
<%end%>
<div class="pagination">
<%= will_paginate @logtypes %>
</div>
diff --git a/src/server/app/views/logtypes/new.rhtml b/src/server/app/views/logtypes/new.rhtml
index c49c5b7..5350ea2 100644
--- a/src/server/app/views/logtypes/new.rhtml
+++ b/src/server/app/views/logtypes/new.rhtml
@@ -1,18 +1,22 @@
<h1>Create a New Logtype</h1>
<%= error_messages_for 'logtype' %>
<div id="form">
<table width="100%">
<% form_for :logtype do |f|%>
<tr>
<td>Name:</td>
<td align="right"><%= f.text_field :name, :class => "fbox"%></td>
</tr>
+ <tr>
+ <td>Description:</td>
+ <td align="right"><%= f.text_field :description, :class => "fbox"%></td>
+ </tr>
<tr>
<td><%= submit_tag "Add Logtype", :class => "submitbutton" %></td>
<td></td>
</tr>
<%end%>
</table>
</div>
\ No newline at end of file
diff --git a/src/server/app/views/logtypes/search.rhtml b/src/server/app/views/logtypes/search.rhtml
new file mode 100644
index 0000000..3e2f48b
--- /dev/null
+++ b/src/server/app/views/logtypes/search.rhtml
@@ -0,0 +1,16 @@
+<h1>Search Results</h1>
+<div id="totalhits">Found <%=@total%> matching results</div>
+<div id="events">
+<% for event in @results do %>
+ <div class="event">
+ <a href="#" onclick="$('.eventinfo<%=event.id%>').toggle();return false"><%= if params[:withepoch] then event.etime else Time.at(event.etime.to_f) end %></a> : <%= event.loglevel.name %> ::
+ <%=event.full_event%>
+ <div class="eventinfo<%=event.id%>" style="display:none; background:#FF9; border:1px solid #000; padding:5px; width:50%">
+ <div class="info">Agent: <%=link_to(event.agent.name, :controller => "agents", :action => "show", :id => event.agent.id)%></div>
+ <div class="info">Logtype: <%=link_to(event.staticentry.logtype.name, :controller => "logtypes", :action => "show", :id => event.staticentry.logtype.id)%></div>
+ <div class="info">Static Entry Id: <%=event.staticentry_id%></div>
+ </div>
+ </div>
+<%end%>
+</div>
+<%=will_paginate @results%>
\ No newline at end of file
diff --git a/src/server/app/views/logtypes/show.rhtml b/src/server/app/views/logtypes/show.rhtml
index 6a8b32c..26de066 100644
--- a/src/server/app/views/logtypes/show.rhtml
+++ b/src/server/app/views/logtypes/show.rhtml
@@ -1,32 +1,46 @@
+<div class="rightsearch">
+ <div>
+ <% form_for :search, :url => { :id => params[:id]} do |form| %>
+ <div>Search within Logtype</div>
+ <div><%= form.text_field :data, :size => 20, :class => "minisearchbox" %> </div>
+ <%end%>
+ </div>
+</div>
+<div class="clear"></div>
<h1>All Events for <%=@logtype.name%></h1>
<div id="filter">
<a href='#' onclick="$('.agentinfo').toggle();return false">View by Agent</a>
<div class="agentinfo" style="display:none; background:#FF9; padding: 3px; border: 1px solid #000">
<% for agent in @logtype.agents do %>
<div class="info"><%= link_to( agent.name, :controller => 'agents', :action => 'show', :logtype => @logtype.id, :withepoch => params[:withepoch], :id => agent.id )%></div>
<%end%>
</div>
</div>
-<div id="eventlist">
- <ul>
- <% for event in @events do %>
- <li><%= event.agent.name %> : <%= if params[:withepoch] then event.etime else Time.at(event.etime.to_f) end %> : <%= event.loglevel.name %> <%=event.payload%></li>
- <%end%>
- </ul>
+<div id="events">
+<% for event in @events do %>
+ <div class="event">
+ <a href="#" onclick="$('.eventinfo<%=event.id%>').toggle();return false"><%= if params[:withepoch] then event.etime else Time.at(event.etime.to_f) end %></a> : <%= link_to(event.loglevel.name, :action => "show", :loglevel => event.loglevel.id, :withepoch => params[:withepoch])%> ::
+ <%=event.payload%>
+ <div class="eventinfo<%=event.id%>" style="display:none; background:#FF9; border:1px solid #000; padding:5px; width:50%">
+ <div class="info">Agent: <%=link_to(event.agent.name, :controller => "agents", :action => "show", :id => event.agent.id)%></div>
+ <div class="info">Static Entry Id: <%=event.staticentry_id%></div>
+ </div>
+ </div>
+<%end%>
</div>
<div class="pagination">
<%= will_paginate @event %>
</div>
<div class="adendem">
Records per page:
<%=link_to "20", :withepoch => params[:withepoch], :page => 1, :perpage => "20" %> |
<%=link_to "50", :withepoch => params[:withepoch], :page => 1, :perpage => "50" %> |
<%=link_to "100", :withepoch => params[:withepoch], :page => 1, :perpage => "100" %> |
<%=link_to "200", :withepoch => params[:withepoch], :page => 1, :perpage => "200" %>
</div>
<%if params[:withepoch]%>
<div class="adendem"><%=link_to "show regular time", :withepoch => nil, :page => params[:page], :perpage => params[:perpage] %></div>
<%else%>
<div class="adendem"><%=link_to "show epoch time", :withepoch => 1, :page => params[:page], :perpage => params[:perpage] %></div>
<%end%>
\ No newline at end of file
diff --git a/src/server/app/views/search/index.rhtml b/src/server/app/views/search/index.rhtml
index 6a1c4c3..2b06606 100644
--- a/src/server/app/views/search/index.rhtml
+++ b/src/server/app/views/search/index.rhtml
@@ -1,31 +1,31 @@
<h1>Search for Events</h1>
<div>
<% form_for :search do |form| %>
- <div><%= form.text_field :data, :size => 20, :class => "searchbox" %> <%= submit_tag "Findit!", :class => "submitbutton", :action => 'show' %></div>
- <div class="adendem"><a href='#' onclick="$('.advancedsearch').toggle();return false">advanced</a></div>
+ <div><%= form.text_field :data, :size => 20, :class => "mainsearchbox" %> <%= submit_tag "Findit!", :class => "searchsubmitbutton", :action => 'show' %></div>
+ <!--<div class="adendem"><a href='#' onclick="$('.advancedsearch').toggle();return false">advanced</a></div>
<div class="advancedsearch">
<div class="agent">Search within Logtype</div>
<div>
<%for log in Logtype.all do%>
<%= radio_button_tag "logtype_ids", log.id %> <%= log.name %>
<%end%>
<%= radio_button_tag "logtype_ids", "off"%> all
</div>
<div class="agent">Search within Agent</div>
<div>
<%for agent in Agent.all do%>
<%= radio_button_tag "agent_ids", agent.id %> <%= agent.name %>
<%end%>
<%= radio_button_tag "agent_ids", "off"%> all
</div>
<div class="agent">Show only loglevel (Will show all levels at or above your choice)</div>
<div>
<%for level in Loglevel.all do%>
<%= radio_button_tag "loglevel_ids", level.id %> <%= level.name %>
<%end%>
<%= radio_button_tag "loglevel_ids", "off"%> all
</div>
- </div>
+ </div>-->
<%end%>
</div>
\ No newline at end of file
diff --git a/src/server/app/views/search/show.rhtml b/src/server/app/views/search/show.rhtml
index c6b7e5c..3e2f48b 100644
--- a/src/server/app/views/search/show.rhtml
+++ b/src/server/app/views/search/show.rhtml
@@ -1,7 +1,16 @@
<h1>Search Results</h1>
-<div class="sresults">
- <div class="count">Found <%= @results.length %> results</div>
- <%for result in @results do%>
- <div class="result"><%=result.full_event%></div>
- <%end%>
-</div>
\ No newline at end of file
+<div id="totalhits">Found <%=@total%> matching results</div>
+<div id="events">
+<% for event in @results do %>
+ <div class="event">
+ <a href="#" onclick="$('.eventinfo<%=event.id%>').toggle();return false"><%= if params[:withepoch] then event.etime else Time.at(event.etime.to_f) end %></a> : <%= event.loglevel.name %> ::
+ <%=event.full_event%>
+ <div class="eventinfo<%=event.id%>" style="display:none; background:#FF9; border:1px solid #000; padding:5px; width:50%">
+ <div class="info">Agent: <%=link_to(event.agent.name, :controller => "agents", :action => "show", :id => event.agent.id)%></div>
+ <div class="info">Logtype: <%=link_to(event.staticentry.logtype.name, :controller => "logtypes", :action => "show", :id => event.staticentry.logtype.id)%></div>
+ <div class="info">Static Entry Id: <%=event.staticentry_id%></div>
+ </div>
+ </div>
+<%end%>
+</div>
+<%=will_paginate @results%>
\ No newline at end of file
diff --git a/src/server/config/initializers/ferret_pagination.rb b/src/server/config/initializers/ferret_pagination.rb
new file mode 100644
index 0000000..e69de29
diff --git a/src/server/db/migrate/20090721233433_create_events.rb b/src/server/db/migrate/20090721233433_create_events.rb
index ef13ca3..5377908 100644
--- a/src/server/db/migrate/20090721233433_create_events.rb
+++ b/src/server/db/migrate/20090721233433_create_events.rb
@@ -1,23 +1,22 @@
class CreateEvents < ActiveRecord::Migration
def self.up
create_table :events do |t|
t.column :payload, :string
t.column :staticentry_id, :string
t.column :agent_id, :int
t.column :loglevel_id, :int
t.column :logtype_id, :int
t.column :etime, :string
t.timestamps
end
add_index :events, :logtype_id
add_index :events, :loglevel_id
add_index :events, :etime
add_index :events, :agent_id
add_index :events, :staticentry_id
-
end
def self.down
drop_table :events
end
end
diff --git a/src/server/db/migrate/20090806184417_add_description_to_logtype.rb b/src/server/db/migrate/20090806184417_add_description_to_logtype.rb
new file mode 100644
index 0000000..2c71ca5
--- /dev/null
+++ b/src/server/db/migrate/20090806184417_add_description_to_logtype.rb
@@ -0,0 +1,9 @@
+class AddDescriptionToLogtype < ActiveRecord::Migration
+ def self.up
+ add_column :logtypes, :description, :string
+ end
+
+ def self.down
+ remove_column :logtypes, :description
+ end
+end
diff --git a/src/server/db/schema.rb b/src/server/db/schema.rb
index bc10792..e1cdc83 100644
--- a/src/server/db/schema.rb
+++ b/src/server/db/schema.rb
@@ -1,77 +1,78 @@
# This file is auto-generated from the current state of the database. Instead of editing this file,
# please use the migrations feature of Active Record to incrementally modify your database, and
# then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your database schema. If you need
# to create the application database on another system, you should be using db:schema:load, not running
# all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended to check this file into your version control system.
-ActiveRecord::Schema.define(:version => 20090804022411) do
+ActiveRecord::Schema.define(:version => 20090806184417) do
create_table "agents", :force => true do |t|
t.string "name"
t.string "hostname"
t.string "port"
t.string "authkey"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "agents", ["hostname"], :name => "index_agents_on_hostname"
add_index "agents", ["name"], :name => "index_agents_on_name"
create_table "agents_logtypes", :id => false, :force => true do |t|
t.integer "logtype_id"
t.integer "agent_id"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "agents_logtypes", ["agent_id"], :name => "index_agents_logtypes_on_agent_id"
add_index "agents_logtypes", ["logtype_id"], :name => "index_agents_logtypes_on_logtype_id"
create_table "events", :force => true do |t|
t.string "payload"
t.string "staticentry_id"
t.integer "agent_id"
t.integer "loglevel_id"
t.integer "logtype_id"
t.string "etime"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "events", ["agent_id"], :name => "index_events_on_agent_id"
add_index "events", ["etime"], :name => "index_events_on_etime"
add_index "events", ["loglevel_id"], :name => "index_events_on_loglevel_id"
add_index "events", ["logtype_id"], :name => "index_events_on_logtype_id"
add_index "events", ["staticentry_id"], :name => "index_events_on_staticentry_id"
create_table "loglevels", :force => true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "logtypes", :force => true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
+ t.string "description"
end
add_index "logtypes", ["name"], :name => "index_logtypes_on_name"
create_table "staticentries", :force => true do |t|
t.integer "logtype_id"
t.text "data"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "staticentries", ["id"], :name => "index_staticentries_on_id"
add_index "staticentries", ["logtype_id"], :name => "index_staticentries_on_logtype_id"
end
diff --git a/src/server/public/stylesheets/main.css b/src/server/public/stylesheets/main.css
index c4677aa..5becf63 100644
--- a/src/server/public/stylesheets/main.css
+++ b/src/server/public/stylesheets/main.css
@@ -1,193 +1,231 @@
body {
background: #fff;
color: #000;
margin: 0px;
padding: 0px;
color: #333;
font-weight:bold;
font-family: serif;
}
a {
text-decoration: none;
color: #660033;
}
a:hover {
background: #000033;
color: #fff;
padding: 2px;
}
#container {
padding: 0px;
margin: auto;
width: 900px;
}
#header {
width: 100%;
margin: 0px;
height: 95px;
background: #333;
border-bottom: solid 6px #000;
color:#fff;
}
#logo {
position: absolute;
padding-top: 20px;
padding-left: 45px;
font-weight:bold;
font-size: 55px;
color: #fff;
}
#search {
text-align: right;
padding-top: 20px;
padding-right: 50px;
}
.searchbox {
background: #663366;
border: 1px solid #000;
color: #fff;
font-size: 20px;
padding: 2px;
font-weight: none;
}
#eventlist {
min-height: 350px;
_height: 350px;
}
#topnav a {
background: #000;
padding: 4px;
padding-bottom: 4px;
padding-left: 6px;
padding-right: 6px;
color: #fff;
border-left: solid 2px #000033;
border-right: solid 2px #000033;
border-bottom: solid 2px #000033;
}
#topnav a:hover {
background: #666;
padding: 4px;
padding-bottom: 4px;
padding-left: 6px;
padding-right: 6px;
color: #fff;
border-left: solid 2px #000033;
border-right: solid 2px #000033;
border-bottom: solid 2px #000033;
}
.topnav {
background: #666;
padding: 2px;
padding-bottom: 4px;
padding-left: 6px;
padding-right: 6px;
color: #fff;
border-left: solid 2px #000033;
border-right: solid 2px #000033;
border-bottom: solid 2px #000033;
}
#topnav {
font-size: 20px;
padding: 2px;
padding-bottom: 4px;
padding-left: 6px;
padding-right: 6px;
color: #fff;
}
#main {
min-height: 400px;
_height: 400px; /* IE min-height hack */
}
#footer {
text-align: center;
width: 900px;
border-top: 2px solid #000;
padding-top: 15px;
}
#notice {
margin-top: 10px;
width: 100%;
background: #09F;
color: #000;
padding: 10px;
border: 1px solid #333;
}
#error {
margin-top: 10px;
width: 100%;
background: #F00;
color: #000;
padding: 10px;
border: 1px solid #333;
}
#form {
width: 350px;
margin: auto;
}
.submitbutton {
background: #660033;
color: #fff;
border: 3px solid #000;
padding: 6px;
}
.fbox {
background: #ffff55;
border: 1px solid #333;
padding: 2px;
}
.clear {
clear:both;
}
.adendem {
font-size: 14px;
font-weight: normal;
}
.in20 {
padding-left: 20px;
padding-right: 20px;
}
.errorExplanation {
width: 800px;
margin: auto;
padding: 3px;
padding-left: 10px;
padding-right: 10px;
background: #ffff55;
border: 1px solid #333;
margin-bottom: 10px;
}
.subnav {
float:right;
}
.agent {
margin-top: 10px;
padding: 2px;
}
.result {
padding: 5px;
}
.advancedsearch {
display: none;
background:#FF9;
padding: 3px;
border: 1px solid #000
+}
+
+.event {
+
+}
+.event a {
+ color:#333;
+}
+.event a:hover {
+ color:#333;
+ background: #aaa;
+}
+
+#totalhits {
+ margin-bottom: 10px;
+ font-size: 14px;
+}
+.mainsearchbox {
+ background: #FF9;
+ border: solid 1px #000;
+ font-size: 20px;
+ padding: 2px;
+ font-weight: none;
+}
+.searchsubmitbutton {
+ background: #660033;
+ color: #fff;
+ border: 1px solid #000;
+ padding: 6px;
+ height: 28px;
+}
+.rightsearch {
+ float:right;
+ text-align: right;
+}
+.minisearchbox {
+ background: #FF9;
+ border: 1px solid #000;
}
\ No newline at end of file
|
parabuzzle/cistern
|
4efc3bc56bee12f2ffeeca20b342f68e158d3fd5
|
Viewing by logtype can also view by loglevel
|
diff --git a/src/server/app/controllers/logtypes_controller.rb b/src/server/app/controllers/logtypes_controller.rb
index 1539421..9212f87 100644
--- a/src/server/app/controllers/logtypes_controller.rb
+++ b/src/server/app/controllers/logtypes_controller.rb
@@ -1,60 +1,64 @@
class LogtypesController < ApplicationController
def index
@title = "Logtypes"
@logtypes = Logtype.paginate :all, :per_page => params[:perpage], :page => params[:page]
end
def show
@logtype = Logtype.find(params[:id])
@title = "All Events for #{@logtype.name}"
- @event = @logtype.events.paginate :all, :per_page => params[:perpage], :page => params[:page]
+ if params[:loglevel].nil?
+ @event = @logtype.events.paginate :all, :per_page => params[:perpage], :page => params[:page]
+ else
+ @event = @logtype.events.paginate :all, :per_page => params[:perpage], :page => params[:page], :conditions => "loglevel_id <= '#{params[:loglevel]}'"
+ end
@events = rebuildevents(@event)
end
def new
if request.post?
@logtype = Logtype.new(params[:logtype])
if @logtype.save
flash[:notice] = "Logtype #{@logtype.name} added"
redirect_to :action => "index"
else
flash[:error] = "There were errors creating your logtype"
end
else
@title = "Create New Logtype"
end
end
def edit
@logtype = Logtype.find(params[:id])
if request.post?
@logtype.update_attributes(params[:logtype])
if @logtype.save
flash[:notice] = "Logtype #{@logtype.name} updated"
redirect_to :action => "index"
else
flash[:error] = "There were errors updating your logtype"
end
else
@title = "Edit #{@logtype.name}"
end
end
def delete
@logtype = params[:id]
if request.post?
if @logtype.destroy
flash[:notice] = "Logtype deleted"
redirect_to :action => "index"
else
flash[:error] = "Error trying to delete logtype"
redirect_to :action => "index"
end
else
flash[:error] = "Poking around is never a good idea"
redirect_to :action => "index"
end
end
end
|
parabuzzle/cistern
|
149f766906aa2a3d5fb3d8002e6e3483f6a1f198
|
Viewing by agent can also filter by loglevel
|
diff --git a/src/server/app/controllers/agents_controller.rb b/src/server/app/controllers/agents_controller.rb
index 1e9d7b5..2c50a0e 100644
--- a/src/server/app/controllers/agents_controller.rb
+++ b/src/server/app/controllers/agents_controller.rb
@@ -1,67 +1,71 @@
class AgentsController < ApplicationController
def index
@title = "Agents"
@agents = Agent.paginate :all, :per_page => params[:perpage], :page => params[:page]
end
def show
@agent = Agent.find(params[:id])
@title = "All Events for #{@agent.name}"
- if params[:logtype].nil?
+ if params[:logtype].nil? and params[:loglevel].nil?
@event = @agent.events.paginate :all, :per_page => params[:perpage], :page => params[:page]
- else
+ elsif !params[:logtype].nil? and params[:loglevel].nil?
@event = @agent.events.paginate :all, :per_page => params[:perpage], :page => params[:page], :conditions => "logtype_id = '#{params[:logtype]}'"
+ elsif params[:logtype].nil? and !params[:loglevel].nil?
+ @event = @agent.events.paginate :all, :per_page => params[:perpage], :page => params[:page], :conditions => "loglevel_id <= '#{params[:loglevel]}'"
+ else
+ @event = @agent.events.paginate :all, :per_page => params[:perpage], :page => params[:page], :conditions => "logtype_id = '#{params[:logtype]}' and loglevel_id <= '#{params[:loglevel]}'"
end
@events = rebuildevents(@event)
end
def new
if request.post?
@agent = Agent.new(params[:agent])
@agent.authkey = Digest::MD5.hexdigest(@agent.hostname + Time.now.to_s)
if @agent.save
flash[:notice] = "Agent #{@agent.name} added -- don't forget to edit your agent to add it to your logtypes"
redirect_to :action => "index"
else
flash[:error] = "There were errors creating your agent"
end
else
@title = "Create New Agent"
end
end
def edit
@agent = Agent.find(params[:id])
if request.post?
params[:agent][:logtype_ids] ||= []
@agent.update_attributes(params[:agent])
if @agent.save
flash[:notice] = "Agent #{@agent.name} updated"
redirect_to :action => "index"
else
flash[:error] = "There were errors updating your agent"
end
else
@title = "Edit #{@agent.name}"
end
end
def delete
@agent = params[:id]
if request.post?
if @agent.destroy
flash[:notice] = "Agent deleted"
redirect_to :action => "index"
else
flash[:error] = "Error trying to delete agent"
redirect_to :action => "index"
end
else
flash[:error] = "Poking around is never a good idea"
redirect_to :action => "index"
end
end
end
diff --git a/src/server/app/helpers/application_helper.rb b/src/server/app/helpers/application_helper.rb
index f5198fc..ab8f71d 100644
--- a/src/server/app/helpers/application_helper.rb
+++ b/src/server/app/helpers/application_helper.rb
@@ -1,30 +1,59 @@
# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
#Return events array with payload field populated with full event
def rebuildevents(events)
@events = Array.new
events.each do |e|
e.payload = rebuildevent(e)
@events << e
end
return @events
end
#Return a string of replaced static entry keys based on event's payload
def rebuildevent(e)
static = e.staticentry
entries = e.payload.split(',')
hash = Hash.new
entries.each do |m|
map = m.split('=')
hash.store('<<<' + map[0] + '>>>',map[1])
end
p = static.data
hash.each do |key, val|
p = p.gsub(key,val)
end
return p
end
+ def filter_agent(results,agent_id)
+ r = Array.new
+ results.each do |result|
+ if result.agent_id == agent_id
+ r << result
+ end
+ end
+ return r
+ end
+ def filter_logtype(results,logtype_id)
+ r = Array.new
+ results.each do |result|
+ if result.logtype_id == logtype_id
+ r << result
+ end
+ end
+ return r
+ end
+
+ def filter_loglevel(results,loglevel_id)
+ r = Array.new
+ results.each do |result|
+ if result.loglevel_id <= loglevel_id
+ r << result
+ end
+ end
+ return r
+ end
+
end
diff --git a/src/server/app/helpers/search_helper.rb b/src/server/app/helpers/search_helper.rb
index 47bc6a4..d95c6c7 100644
--- a/src/server/app/helpers/search_helper.rb
+++ b/src/server/app/helpers/search_helper.rb
@@ -1,32 +1,3 @@
module SearchHelper
- def filter_agent(results,agent_id)
- r = Array.new
- results.each do |result|
- if result.agent_id == agent_id
- r << result
- end
- end
- return r
- end
- def filter_logtype(results,logtype_id)
- r = Array.new
- results.each do |result|
- if result.logtype_id == logtype_id
- r << result
- end
- end
- return r
- end
-
- def filter_loglevel(results,loglevel_id)
- r = Array.new
- results.each do |result|
- if result.loglevel_id <= loglevel_id
- r << result
- end
- end
- return r
- end
-
end
diff --git a/src/server/app/views/agents/show.rhtml b/src/server/app/views/agents/show.rhtml
index f3874cc..351b880 100644
--- a/src/server/app/views/agents/show.rhtml
+++ b/src/server/app/views/agents/show.rhtml
@@ -1,37 +1,37 @@
<h1>All Events for <%=@agent.name%></h1>
<div id="filter">
<% if params[:logtype]%>
Current filter: <%= Logtype.find(params[:logtype]).name%>
<%else%>
Filter by logtype:
<% for type in @agent.logtypes.all do %>
<%= link_to( type.name, :logtype => type.id, :withepoch => params[:withepoch] )%>
<%end%>
<%end%>
<div class="adendem">
<%= link_to("Clear filter", :logtype => nil, :withepoch => params[:withepoch])%>
</div>
</div>
<div id="eventlist">
<ul>
<% for event in @events do %>
- <li><%= if params[:withepoch] then event.time else Time.at(event.time.to_f) end %> : <%= event.loglevel.name%> <%=event.payload%></li>
+ <li><%= if params[:withepoch] then event.etime else Time.at(event.etime.to_f) end %> : <%= event.loglevel.name%> <%=event.payload%></li>
<%end%>
</ul>
</div>
<div class="pagination">
<%= will_paginate @event %>
</div>
<div class="adendem">
Records per page:
<%=link_to "20", :withepoch => params[:withepoch], :page => 1, :perpage => "20" %> |
<%=link_to "50", :withepoch => params[:withepoch], :page => 1, :perpage => "50" %> |
<%=link_to "100", :withepoch => params[:withepoch], :page => 1, :perpage => "100" %> |
<%=link_to "200", :withepoch => params[:withepoch], :page => 1, :perpage => "200" %>
</div>
<%if params[:withepoch]%>
<div class="adendem"><%=link_to "show regular time", :withepoch => nil, :page => params[:page], :perpage => params[:perpage], :logtype => params[:logtype] %></div>
<%else%>
<div class="adendem"><%=link_to "show epoch time", :withepoch => 1, :page => params[:page], :perpage => params[:perpage], :logtype => params[:logtype] %></div>
<%end%>
\ No newline at end of file
diff --git a/src/server/app/views/logtypes/show.rhtml b/src/server/app/views/logtypes/show.rhtml
index c8c1d20..6a8b32c 100644
--- a/src/server/app/views/logtypes/show.rhtml
+++ b/src/server/app/views/logtypes/show.rhtml
@@ -1,32 +1,32 @@
<h1>All Events for <%=@logtype.name%></h1>
<div id="filter">
<a href='#' onclick="$('.agentinfo').toggle();return false">View by Agent</a>
<div class="agentinfo" style="display:none; background:#FF9; padding: 3px; border: 1px solid #000">
<% for agent in @logtype.agents do %>
<div class="info"><%= link_to( agent.name, :controller => 'agents', :action => 'show', :logtype => @logtype.id, :withepoch => params[:withepoch], :id => agent.id )%></div>
<%end%>
</div>
</div>
<div id="eventlist">
<ul>
<% for event in @events do %>
- <li><%= event.agent.name %> : <%= if params[:withepoch] then event.time else Time.at(event.time.to_f) end %> : <%= event.loglevel.name %> <%=event.payload%></li>
+ <li><%= event.agent.name %> : <%= if params[:withepoch] then event.etime else Time.at(event.etime.to_f) end %> : <%= event.loglevel.name %> <%=event.payload%></li>
<%end%>
</ul>
</div>
<div class="pagination">
<%= will_paginate @event %>
</div>
<div class="adendem">
Records per page:
<%=link_to "20", :withepoch => params[:withepoch], :page => 1, :perpage => "20" %> |
<%=link_to "50", :withepoch => params[:withepoch], :page => 1, :perpage => "50" %> |
<%=link_to "100", :withepoch => params[:withepoch], :page => 1, :perpage => "100" %> |
<%=link_to "200", :withepoch => params[:withepoch], :page => 1, :perpage => "200" %>
</div>
<%if params[:withepoch]%>
<div class="adendem"><%=link_to "show regular time", :withepoch => nil, :page => params[:page], :perpage => params[:perpage] %></div>
<%else%>
<div class="adendem"><%=link_to "show epoch time", :withepoch => 1, :page => params[:page], :perpage => params[:perpage] %></div>
<%end%>
\ No newline at end of file
|
parabuzzle/cistern
|
1c9011d19d40d5f926f000864d937916c0d7aecb
|
Search filter should work now
|
diff --git a/src/server/app/controllers/search_controller.rb b/src/server/app/controllers/search_controller.rb
index 5afccba..a133f45 100644
--- a/src/server/app/controllers/search_controller.rb
+++ b/src/server/app/controllers/search_controller.rb
@@ -1,21 +1,52 @@
class SearchController < ApplicationController
+ include ApplicationHelper
+ include SearchHelper
def index
@title = "Search for Events"
if request.post?
+ if params[:loglevel_ids] == "off"
+ params[:loglevel_ids] = nil
+ end
+ if params[:logtype_ids] == "off"
+ params[:logtype_ids] = nil
+ end
+ if params[:agent_ids] == "off"
+ params[:agent_ids] = nil
+ end
#params[:search][:data]
- redirect_to :action => 'show', :query => params[:search][:data]
+ redirect_to :action => 'show', :query => params[:search][:data], :loglevel => params[:loglevel_ids], :logtype => params[:logtype_ids], :agent => params[:agent_ids]
end
end
def show
- params[:query] = params[:search][:data]
if params[:query].nil?
redirect_to :action => 'index'
else
@title = "Search Results"
- @results = Event.find_with_ferret(params[:query])
+ if !params[:loglevel].nil?
+ loglevel = params[:loglevel]
+ end
+ if !params[:logtype].nil?
+ logtype = params[:logtype]
+ end
+ if !params[:agent].nil?
+ agent = params[:agent]
+ end
+ #@results = Agent.find(agent).events.find_with_ferret(params[:query])
+ r = Event.find_with_ferret(params[:query])
+ @results = Array.new
+ if !agent.nil?
+ r = filter_agent(r,agent.to_i)
+ end
+ if !logtype.nil?
+ r = filter_logtype(r,logtype.to_i)
+ end
+ if !loglevel.nil?
+ r = filter_loglevel(r,loglevel.to_i)
+ end
+ @results = r
end
end
end
diff --git a/src/server/app/helpers/search_helper.rb b/src/server/app/helpers/search_helper.rb
index b3ce20a..47bc6a4 100644
--- a/src/server/app/helpers/search_helper.rb
+++ b/src/server/app/helpers/search_helper.rb
@@ -1,2 +1,32 @@
module SearchHelper
+
+ def filter_agent(results,agent_id)
+ r = Array.new
+ results.each do |result|
+ if result.agent_id == agent_id
+ r << result
+ end
+ end
+ return r
+ end
+ def filter_logtype(results,logtype_id)
+ r = Array.new
+ results.each do |result|
+ if result.logtype_id == logtype_id
+ r << result
+ end
+ end
+ return r
+ end
+
+ def filter_loglevel(results,loglevel_id)
+ r = Array.new
+ results.each do |result|
+ if result.loglevel_id <= loglevel_id
+ r << result
+ end
+ end
+ return r
+ end
+
end
diff --git a/src/server/app/views/layouts/application.rhtml b/src/server/app/views/layouts/application.rhtml
index 9555d2c..c437a29 100644
--- a/src/server/app/views/layouts/application.rhtml
+++ b/src/server/app/views/layouts/application.rhtml
@@ -1,78 +1,82 @@
<%starttime = Time.now.to_f %>
<!DOCTYPE HTML PUBLIC "!//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Cistern :: <%= @title %></title>
<%= stylesheet_link_tag "main" %>
<%= javascript_include_tag "jquery.min"%>
<%= javascript_include_tag "application"%>
</head>
<body>
<div id="header">
<div id="logo">Cistern</div>
<div id="search">
Search all Events
- <% form_for :search do |form| %>
+ <% form_for :search, :url => { :action => "index", :controller => "search" } do |form| %>
<div><%= form.text_field :data, :size => 20, :class => "searchbox", :value => params[:query] %></div>
<!--<div class="adendem">advanced</div> -->
<%end%>
</div>
</div> <!-- header -->
<div id="container">
<div id="topnav">
- <%= link_to("Events", :controller => "events", :action => "index")%> <%= link_to("Agents", :controller => "agents", :action => "index")%> <%= link_to("Logtypes", :controller => "logtypes", :action => "index")%>
+ <%= link_to("Events", :controller => "events", :action => "index")%>
+ <%= link_to("Agents", :controller => "agents", :action => "index")%>
+ <%= link_to("Logtypes", :controller => "logtypes", :action => "index")%>
+ <%= link_to("Search", :controller => "search", :action => "index")%>
+ <!-- <%= link_to("Stats", :controller => "stats", :action => "index")%> -->
</div>
<div id="main">
<% if flash[:notice]%>
<div id="notice"><%=flash[:notice]%></div>
<%end%>
<%if flash[:error]%>
<div id="error"><%=flash[:error]%></div>
<%end%>
<%= @content_for_layout %>
</div> <!-- main -->
<div id="footer">
Copyright © 2009 Mike Heijmans
<div class="adendum">powered by <a href="http://parabuzzle.github.com/cistern">Cistern</a></div>
</div> <!-- footer -->
<% if ENV["RAILS_ENV"] == "development" #call this block if in dev mode %>
<!-- Dev stuff -->
<div id="debug">
<a href='#' onclick="$('#params_debug_info').toggle();return false">params</a> |
<a href='#' onclick="$('#session_debug_info').toggle();return false">session</a> |
<a href='#' onclick="$('#env_debug_info').toggle();return false">env</a> |
<a href='#' onclick="$('#request_debug_info').toggle();return false">request</a>
<fieldset id="params_debug_info" class="debug_info" style="display:none">
<legend>params</legend>
<%= debug(params) %>
</fieldset>
<fieldset id="session_debug_info" class="debug_info" style="display:none">
<legend>session</legend>
<%= debug(session) %>
</fieldset>
<fieldset id="env_debug_info" class="debug_info" style="display:none">
<legend>env</legend>
<%= debug(request.env) %>
</fieldset>
<fieldset id="request_debug_info" class="debug_info" style="display:none">
<legend>request</legend>
<%= debug(request) %>
</fieldset>
</div>
<!-- end Dev mode only stuff -->
<% end %>
</div> <!-- container -->
</body>
</html>
<% rtime = Time.now.to_f - starttime%>
<% if ENV["RAILS_ENV"] == "development"%>
<%= [rtime*1000].to_s.to_i %> ms
<%else%>
<!-- <%= rtime*1000 %> -->
<%end%>
\ No newline at end of file
diff --git a/src/server/app/views/search/index.rhtml b/src/server/app/views/search/index.rhtml
index 357d992..6a1c4c3 100644
--- a/src/server/app/views/search/index.rhtml
+++ b/src/server/app/views/search/index.rhtml
@@ -1,9 +1,31 @@
<h1>Search for Events</h1>
<div>
<% form_for :search do |form| %>
- <div><%= form.text_field :data, :size => 20, :class => "searchbox" %></div>
- <!--<div class="adendem">advanced</div> -->
- <div class="agent"><%= submit_tag "Findit!", :class => "submitbutton", :action => 'show' %></div>
+ <div><%= form.text_field :data, :size => 20, :class => "searchbox" %> <%= submit_tag "Findit!", :class => "submitbutton", :action => 'show' %></div>
+ <div class="adendem"><a href='#' onclick="$('.advancedsearch').toggle();return false">advanced</a></div>
+ <div class="advancedsearch">
+ <div class="agent">Search within Logtype</div>
+ <div>
+ <%for log in Logtype.all do%>
+ <%= radio_button_tag "logtype_ids", log.id %> <%= log.name %>
+ <%end%>
+ <%= radio_button_tag "logtype_ids", "off"%> all
+ </div>
+ <div class="agent">Search within Agent</div>
+ <div>
+ <%for agent in Agent.all do%>
+ <%= radio_button_tag "agent_ids", agent.id %> <%= agent.name %>
+ <%end%>
+ <%= radio_button_tag "agent_ids", "off"%> all
+ </div>
+ <div class="agent">Show only loglevel (Will show all levels at or above your choice)</div>
+ <div>
+ <%for level in Loglevel.all do%>
+ <%= radio_button_tag "loglevel_ids", level.id %> <%= level.name %>
+ <%end%>
+ <%= radio_button_tag "loglevel_ids", "off"%> all
+ </div>
+ </div>
<%end%>
</div>
\ No newline at end of file
diff --git a/src/server/app/views/search/show.rhtml b/src/server/app/views/search/show.rhtml
index d9642a7..c6b7e5c 100644
--- a/src/server/app/views/search/show.rhtml
+++ b/src/server/app/views/search/show.rhtml
@@ -1,8 +1,7 @@
<h1>Search Results</h1>
-
<div class="sresults">
<div class="count">Found <%= @results.length %> results</div>
<%for result in @results do%>
<div class="result"><%=result.full_event%></div>
<%end%>
</div>
\ No newline at end of file
diff --git a/src/server/public/stylesheets/main.css b/src/server/public/stylesheets/main.css
index 41b6b4c..c4677aa 100644
--- a/src/server/public/stylesheets/main.css
+++ b/src/server/public/stylesheets/main.css
@@ -1,186 +1,193 @@
body {
background: #fff;
color: #000;
margin: 0px;
padding: 0px;
color: #333;
font-weight:bold;
font-family: serif;
}
a {
text-decoration: none;
color: #660033;
}
a:hover {
background: #000033;
color: #fff;
padding: 2px;
}
#container {
padding: 0px;
margin: auto;
width: 900px;
}
#header {
width: 100%;
margin: 0px;
height: 95px;
background: #333;
border-bottom: solid 6px #000;
color:#fff;
}
#logo {
position: absolute;
padding-top: 20px;
padding-left: 45px;
font-weight:bold;
font-size: 55px;
color: #fff;
}
#search {
text-align: right;
padding-top: 20px;
padding-right: 50px;
}
.searchbox {
background: #663366;
border: 1px solid #000;
color: #fff;
font-size: 20px;
padding: 2px;
font-weight: none;
}
#eventlist {
min-height: 350px;
_height: 350px;
}
#topnav a {
background: #000;
padding: 4px;
padding-bottom: 4px;
padding-left: 6px;
padding-right: 6px;
color: #fff;
border-left: solid 2px #000033;
border-right: solid 2px #000033;
border-bottom: solid 2px #000033;
}
#topnav a:hover {
background: #666;
padding: 4px;
padding-bottom: 4px;
padding-left: 6px;
padding-right: 6px;
color: #fff;
border-left: solid 2px #000033;
border-right: solid 2px #000033;
border-bottom: solid 2px #000033;
}
.topnav {
background: #666;
padding: 2px;
padding-bottom: 4px;
padding-left: 6px;
padding-right: 6px;
color: #fff;
border-left: solid 2px #000033;
border-right: solid 2px #000033;
border-bottom: solid 2px #000033;
}
#topnav {
font-size: 20px;
padding: 2px;
padding-bottom: 4px;
padding-left: 6px;
padding-right: 6px;
color: #fff;
}
#main {
min-height: 400px;
_height: 400px; /* IE min-height hack */
}
#footer {
text-align: center;
width: 900px;
border-top: 2px solid #000;
padding-top: 15px;
}
#notice {
margin-top: 10px;
width: 100%;
background: #09F;
color: #000;
padding: 10px;
border: 1px solid #333;
}
#error {
margin-top: 10px;
width: 100%;
background: #F00;
color: #000;
padding: 10px;
border: 1px solid #333;
}
#form {
width: 350px;
margin: auto;
}
.submitbutton {
background: #660033;
color: #fff;
border: 3px solid #000;
padding: 6px;
}
.fbox {
background: #ffff55;
border: 1px solid #333;
padding: 2px;
}
.clear {
clear:both;
}
.adendem {
font-size: 14px;
font-weight: normal;
}
.in20 {
padding-left: 20px;
padding-right: 20px;
}
.errorExplanation {
width: 800px;
margin: auto;
padding: 3px;
padding-left: 10px;
padding-right: 10px;
background: #ffff55;
border: 1px solid #333;
margin-bottom: 10px;
}
.subnav {
float:right;
}
.agent {
margin-top: 10px;
padding: 2px;
}
.result {
padding: 5px;
+}
+
+.advancedsearch {
+ display: none;
+ background:#FF9;
+ padding: 3px;
+ border: 1px solid #000
}
\ No newline at end of file
|
parabuzzle/cistern
|
2e9590f857a3db4027f97fc42f6da4991a7ba1d0
|
Tied the search box to the search controller. Need to format events and search results now
|
diff --git a/src/server/app/controllers/search_controller.rb b/src/server/app/controllers/search_controller.rb
new file mode 100644
index 0000000..5afccba
--- /dev/null
+++ b/src/server/app/controllers/search_controller.rb
@@ -0,0 +1,21 @@
+class SearchController < ApplicationController
+
+ def index
+ @title = "Search for Events"
+ if request.post?
+ #params[:search][:data]
+ redirect_to :action => 'show', :query => params[:search][:data]
+ end
+ end
+
+ def show
+ params[:query] = params[:search][:data]
+ if params[:query].nil?
+ redirect_to :action => 'index'
+ else
+ @title = "Search Results"
+ @results = Event.find_with_ferret(params[:query])
+ end
+ end
+
+end
diff --git a/src/server/app/helpers/search_helper.rb b/src/server/app/helpers/search_helper.rb
new file mode 100644
index 0000000..b3ce20a
--- /dev/null
+++ b/src/server/app/helpers/search_helper.rb
@@ -0,0 +1,2 @@
+module SearchHelper
+end
diff --git a/src/server/app/views/layouts/application.rhtml b/src/server/app/views/layouts/application.rhtml
index becb8c7..9555d2c 100644
--- a/src/server/app/views/layouts/application.rhtml
+++ b/src/server/app/views/layouts/application.rhtml
@@ -1,78 +1,78 @@
<%starttime = Time.now.to_f %>
<!DOCTYPE HTML PUBLIC "!//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Cistern :: <%= @title %></title>
<%= stylesheet_link_tag "main" %>
<%= javascript_include_tag "jquery.min"%>
<%= javascript_include_tag "application"%>
</head>
<body>
<div id="header">
<div id="logo">Cistern</div>
- <div id="search ">
+ <div id="search">
Search all Events
<% form_for :search do |form| %>
- <div><%= form.text_field :data, :size => 20, :class => "searchbox" %></div>
- <div class="adendem">advanced</div>
+ <div><%= form.text_field :data, :size => 20, :class => "searchbox", :value => params[:query] %></div>
+ <!--<div class="adendem">advanced</div> -->
<%end%>
</div>
</div> <!-- header -->
<div id="container">
<div id="topnav">
<%= link_to("Events", :controller => "events", :action => "index")%> <%= link_to("Agents", :controller => "agents", :action => "index")%> <%= link_to("Logtypes", :controller => "logtypes", :action => "index")%>
</div>
<div id="main">
<% if flash[:notice]%>
<div id="notice"><%=flash[:notice]%></div>
<%end%>
<%if flash[:error]%>
<div id="error"><%=flash[:error]%></div>
<%end%>
<%= @content_for_layout %>
</div> <!-- main -->
<div id="footer">
Copyright © 2009 Mike Heijmans
<div class="adendum">powered by <a href="http://parabuzzle.github.com/cistern">Cistern</a></div>
</div> <!-- footer -->
<% if ENV["RAILS_ENV"] == "development" #call this block if in dev mode %>
<!-- Dev stuff -->
<div id="debug">
<a href='#' onclick="$('#params_debug_info').toggle();return false">params</a> |
<a href='#' onclick="$('#session_debug_info').toggle();return false">session</a> |
<a href='#' onclick="$('#env_debug_info').toggle();return false">env</a> |
<a href='#' onclick="$('#request_debug_info').toggle();return false">request</a>
<fieldset id="params_debug_info" class="debug_info" style="display:none">
<legend>params</legend>
<%= debug(params) %>
</fieldset>
<fieldset id="session_debug_info" class="debug_info" style="display:none">
<legend>session</legend>
<%= debug(session) %>
</fieldset>
<fieldset id="env_debug_info" class="debug_info" style="display:none">
<legend>env</legend>
<%= debug(request.env) %>
</fieldset>
<fieldset id="request_debug_info" class="debug_info" style="display:none">
<legend>request</legend>
<%= debug(request) %>
</fieldset>
</div>
<!-- end Dev mode only stuff -->
<% end %>
</div> <!-- container -->
</body>
</html>
<% rtime = Time.now.to_f - starttime%>
<% if ENV["RAILS_ENV"] == "development"%>
<%= [rtime*1000].to_s.to_i %> ms
<%else%>
<!-- <%= rtime*1000 %> -->
<%end%>
\ No newline at end of file
diff --git a/src/server/app/views/search/index.rhtml b/src/server/app/views/search/index.rhtml
new file mode 100644
index 0000000..357d992
--- /dev/null
+++ b/src/server/app/views/search/index.rhtml
@@ -0,0 +1,9 @@
+<h1>Search for Events</h1>
+
+<div>
+ <% form_for :search do |form| %>
+ <div><%= form.text_field :data, :size => 20, :class => "searchbox" %></div>
+ <!--<div class="adendem">advanced</div> -->
+ <div class="agent"><%= submit_tag "Findit!", :class => "submitbutton", :action => 'show' %></div>
+ <%end%>
+</div>
\ No newline at end of file
diff --git a/src/server/app/views/search/show.rhtml b/src/server/app/views/search/show.rhtml
new file mode 100644
index 0000000..d9642a7
--- /dev/null
+++ b/src/server/app/views/search/show.rhtml
@@ -0,0 +1,8 @@
+<h1>Search Results</h1>
+
+<div class="sresults">
+ <div class="count">Found <%= @results.length %> results</div>
+ <%for result in @results do%>
+ <div class="result"><%=result.full_event%></div>
+ <%end%>
+</div>
\ No newline at end of file
diff --git a/src/server/public/stylesheets/main.css b/src/server/public/stylesheets/main.css
index be6d785..41b6b4c 100644
--- a/src/server/public/stylesheets/main.css
+++ b/src/server/public/stylesheets/main.css
@@ -1,183 +1,186 @@
body {
background: #fff;
color: #000;
margin: 0px;
padding: 0px;
color: #333;
font-weight:bold;
font-family: serif;
}
a {
text-decoration: none;
color: #660033;
}
a:hover {
background: #000033;
color: #fff;
padding: 2px;
}
#container {
padding: 0px;
margin: auto;
width: 900px;
}
#header {
width: 100%;
margin: 0px;
height: 95px;
background: #333;
border-bottom: solid 6px #000;
color:#fff;
}
#logo {
position: absolute;
padding-top: 20px;
padding-left: 45px;
font-weight:bold;
font-size: 55px;
color: #fff;
}
#search {
text-align: right;
padding-top: 20px;
padding-right: 50px;
}
.searchbox {
background: #663366;
border: 1px solid #000;
color: #fff;
font-size: 20px;
padding: 2px;
font-weight: none;
}
#eventlist {
min-height: 350px;
_height: 350px;
}
#topnav a {
background: #000;
padding: 4px;
padding-bottom: 4px;
padding-left: 6px;
padding-right: 6px;
color: #fff;
border-left: solid 2px #000033;
border-right: solid 2px #000033;
border-bottom: solid 2px #000033;
}
#topnav a:hover {
background: #666;
padding: 4px;
padding-bottom: 4px;
padding-left: 6px;
padding-right: 6px;
color: #fff;
border-left: solid 2px #000033;
border-right: solid 2px #000033;
border-bottom: solid 2px #000033;
}
.topnav {
background: #666;
padding: 2px;
padding-bottom: 4px;
padding-left: 6px;
padding-right: 6px;
color: #fff;
border-left: solid 2px #000033;
border-right: solid 2px #000033;
border-bottom: solid 2px #000033;
}
#topnav {
font-size: 20px;
padding: 2px;
padding-bottom: 4px;
padding-left: 6px;
padding-right: 6px;
color: #fff;
}
#main {
min-height: 400px;
_height: 400px; /* IE min-height hack */
}
#footer {
text-align: center;
width: 900px;
border-top: 2px solid #000;
padding-top: 15px;
}
#notice {
margin-top: 10px;
width: 100%;
background: #09F;
color: #000;
padding: 10px;
border: 1px solid #333;
}
#error {
margin-top: 10px;
width: 100%;
background: #F00;
color: #000;
padding: 10px;
border: 1px solid #333;
}
#form {
width: 350px;
margin: auto;
}
.submitbutton {
background: #660033;
color: #fff;
border: 3px solid #000;
padding: 6px;
}
.fbox {
background: #ffff55;
border: 1px solid #333;
padding: 2px;
}
.clear {
clear:both;
}
.adendem {
font-size: 14px;
font-weight: normal;
}
.in20 {
padding-left: 20px;
padding-right: 20px;
}
.errorExplanation {
width: 800px;
margin: auto;
padding: 3px;
padding-left: 10px;
padding-right: 10px;
background: #ffff55;
border: 1px solid #333;
margin-bottom: 10px;
}
.subnav {
float:right;
}
.agent {
margin-top: 10px;
padding: 2px;
+}
+.result {
+ padding: 5px;
}
\ No newline at end of file
diff --git a/src/server/test/functional/search_controller_test.rb b/src/server/test/functional/search_controller_test.rb
new file mode 100644
index 0000000..49bb14f
--- /dev/null
+++ b/src/server/test/functional/search_controller_test.rb
@@ -0,0 +1,8 @@
+require 'test_helper'
+
+class SearchControllerTest < ActionController::TestCase
+ # Replace this with your real tests.
+ test "the truth" do
+ assert true
+ end
+end
diff --git a/src/server/test/unit/helpers/search_helper_test.rb b/src/server/test/unit/helpers/search_helper_test.rb
new file mode 100644
index 0000000..3034163
--- /dev/null
+++ b/src/server/test/unit/helpers/search_helper_test.rb
@@ -0,0 +1,4 @@
+require 'test_helper'
+
+class SearchHelperTest < ActionView::TestCase
+end
|
parabuzzle/cistern
|
00f95fa82fdcefb431aca55726de1017e24bed41
|
Frontend work to make the application more intuitive to use
|
diff --git a/src/server/app/controllers/agents_controller.rb b/src/server/app/controllers/agents_controller.rb
index 8cdb3b2..1e9d7b5 100644
--- a/src/server/app/controllers/agents_controller.rb
+++ b/src/server/app/controllers/agents_controller.rb
@@ -1,65 +1,67 @@
class AgentsController < ApplicationController
def index
@title = "Agents"
@agents = Agent.paginate :all, :per_page => params[:perpage], :page => params[:page]
end
def show
@agent = Agent.find(params[:id])
@title = "All Events for #{@agent.name}"
if params[:logtype].nil?
@event = @agent.events.paginate :all, :per_page => params[:perpage], :page => params[:page]
else
@event = @agent.events.paginate :all, :per_page => params[:perpage], :page => params[:page], :conditions => "logtype_id = '#{params[:logtype]}'"
end
@events = rebuildevents(@event)
end
def new
if request.post?
@agent = Agent.new(params[:agent])
- @agent.key = Digest::MD5.hexdigest(@agent.hostname + Time.now.to_s)
+ @agent.authkey = Digest::MD5.hexdigest(@agent.hostname + Time.now.to_s)
if @agent.save
- flash[:notice] = "Agent #{@agent.name} added"
+ flash[:notice] = "Agent #{@agent.name} added -- don't forget to edit your agent to add it to your logtypes"
redirect_to :action => "index"
else
flash[:error] = "There were errors creating your agent"
end
else
@title = "Create New Agent"
end
end
def edit
@agent = Agent.find(params[:id])
if request.post?
+ params[:agent][:logtype_ids] ||= []
@agent.update_attributes(params[:agent])
if @agent.save
flash[:notice] = "Agent #{@agent.name} updated"
redirect_to :action => "index"
else
flash[:error] = "There were errors updating your agent"
end
else
@title = "Edit #{@agent.name}"
end
end
def delete
@agent = params[:id]
if request.post?
if @agent.destroy
flash[:notice] = "Agent deleted"
redirect_to :action => "index"
else
flash[:error] = "Error trying to delete agent"
redirect_to :action => "index"
end
else
flash[:error] = "Poking around is never a good idea"
redirect_to :action => "index"
end
end
+
end
diff --git a/src/server/app/controllers/events_controller.rb b/src/server/app/controllers/events_controller.rb
index 50d0697..984026c 100644
--- a/src/server/app/controllers/events_controller.rb
+++ b/src/server/app/controllers/events_controller.rb
@@ -1,17 +1,16 @@
class EventsController < ApplicationController
include EventsHelper
def index
@title = "Events"
@logtypes = Logtype.all
@agents = Agent.all
end
def show
@title = "All Events"
- #@events = Array.new
@event = Event.paginate :all, :per_page => params[:perpage], :page => params[:page]
@events = rebuildevents(@event)
end
end
diff --git a/src/server/app/controllers/logtypes_controller.rb b/src/server/app/controllers/logtypes_controller.rb
index 4f2cacb..1539421 100644
--- a/src/server/app/controllers/logtypes_controller.rb
+++ b/src/server/app/controllers/logtypes_controller.rb
@@ -1,15 +1,60 @@
class LogtypesController < ApplicationController
def index
@title = "Logtypes"
@logtypes = Logtype.paginate :all, :per_page => params[:perpage], :page => params[:page]
end
def show
@logtype = Logtype.find(params[:id])
@title = "All Events for #{@logtype.name}"
@event = @logtype.events.paginate :all, :per_page => params[:perpage], :page => params[:page]
@events = rebuildevents(@event)
end
+ def new
+ if request.post?
+ @logtype = Logtype.new(params[:logtype])
+ if @logtype.save
+ flash[:notice] = "Logtype #{@logtype.name} added"
+ redirect_to :action => "index"
+ else
+ flash[:error] = "There were errors creating your logtype"
+ end
+ else
+ @title = "Create New Logtype"
+ end
+ end
+
+ def edit
+ @logtype = Logtype.find(params[:id])
+ if request.post?
+ @logtype.update_attributes(params[:logtype])
+ if @logtype.save
+ flash[:notice] = "Logtype #{@logtype.name} updated"
+ redirect_to :action => "index"
+ else
+ flash[:error] = "There were errors updating your logtype"
+ end
+ else
+ @title = "Edit #{@logtype.name}"
+ end
+ end
+
+ def delete
+ @logtype = params[:id]
+ if request.post?
+ if @logtype.destroy
+ flash[:notice] = "Logtype deleted"
+ redirect_to :action => "index"
+ else
+ flash[:error] = "Error trying to delete logtype"
+ redirect_to :action => "index"
+ end
+ else
+ flash[:error] = "Poking around is never a good idea"
+ redirect_to :action => "index"
+ end
+ end
+
end
diff --git a/src/server/app/models/agent.rb b/src/server/app/models/agent.rb
index 69a5d9a..9b23267 100644
--- a/src/server/app/models/agent.rb
+++ b/src/server/app/models/agent.rb
@@ -1,12 +1,37 @@
class Agent < ActiveRecord::Base
acts_as_ferret :fields => [:hostname, :name, :port]
has_and_belongs_to_many :logtypes, :join_table => :agents_logtypes
has_many :events
#Validations
validates_presence_of :hostname, :port, :name
validates_format_of :hostname, :with => /([A-Z0-9-]+\.)+[A-Z]{2,4}$/i
+ validates_uniqueness_of :name
+ def add_logtype(logtype)
+ if self.logtypes.find_by_logtype_id('logtype.id') == nil
+ ActiveRecord::Base.connection.execute("insert into agents_logtypes (logtype_id,agent_id)values('#{logtype.id}','#{self.id}')")
+ end
+ return logtype
+ end
+
+ def remove_logtype(logtype)
+ if self.logtypes.find_by_logtype_id('logtype.id') != nil
+ ActiveRecord::Base.connection.execute("delete from agents_logtypes where logtype_id = '#{logtype.id}' and agent_id = '#{self.id}'")
+ end
+ return logtype
+ end
+
+ def logtype_member?(logtype)
+ flag = 0
+ self.logtypes.each do |log|
+ if log.id == logtype.id
+ flag = 1
+ end
+ end
+ return flag
+ end
+
end
diff --git a/src/server/app/views/agents/edit.rhtml b/src/server/app/views/agents/edit.rhtml
index b065695..880f888 100644
--- a/src/server/app/views/agents/edit.rhtml
+++ b/src/server/app/views/agents/edit.rhtml
@@ -1,30 +1,34 @@
<h1>Edit <%=@agent.name%></h1>
<%= error_messages_for 'agent' %>
<div id="form">
<table width="100%">
<% form_for :agent do |f|%>
<tr>
<td>Name:</td>
<td align="right"><%= f.text_field :name, :class => "fbox"%></td>
</tr>
<tr>
<td>Hostname:</td>
<td align="right"><%= f.text_field :hostname, :class => "fbox"%></td>
</tr>
<tr>
<td>Port:</td>
<td align="right"><%= f.text_field :port, :class => "fbox"%></td>
</tr>
<tr>
<td>Key:</td>
- <td align="right"><%= f.text_field :key, :class => "fbox"%></td>
- </tr>
- <tr>
- <td><%= submit_tag "Update Agent", :class => "submitbutton" %></td>
- <td></td>
+ <td align="right"><%= f.text_field :authkey, :class => "fbox"%></td>
</tr>
+ </table>
+
+ <div class="agent">Logtypes</div>
+ <% for log in Logtype.find(:all) %>
+ <div class="agents">
+ <%= check_box_tag "agent[logtype_ids][]", log.id, @agent.logtypes.include?(log) %> <%= log.name %>
+ </div>
+ <%end%>
+ <div class="agent"><%= submit_tag "Update Agent", :class => "submitbutton" %></div>
<%end%>
- </table>
</div>
\ No newline at end of file
diff --git a/src/server/app/views/agents/index.rhtml b/src/server/app/views/agents/index.rhtml
index 852dd98..5792096 100644
--- a/src/server/app/views/agents/index.rhtml
+++ b/src/server/app/views/agents/index.rhtml
@@ -1,10 +1,29 @@
<h1>Agents</h1>
-<ul>
- <% for agent in @agents do%>
- <li><%=link_to(agent.name, :action => 'show', :id => agent.id)%> [<%=agent.hostname%>] <%=link_to("edit", :action => 'edit', :id => agent.id)%> :: <%= agent.events.count%> total events</li>
- <%end%>
-</ul>
+<div class="subnav"><%=link_to("Create new Agent #{image_tag("addserver.png", :alt => "add server", :border => "0px")}", :action => "new")%></div>
+
+<div class="clear"></div>
+
+<% for agent in @agents do%>
+<div class="agent">
+ <%=image_tag("serverup.png")%><a href='#' onclick="$('.agentinfo<%=agent.id%>').toggle();return false"><%=agent.name%></a> : <%=link_to("View Events", :action=>"show", :id=>agent.id)%>
+ <div class="agentinfo<%=agent.id%>" style="display:none; margin-left:30px; background:#FF9; padding: 3px; border: 1px solid #000">
+ <div class="subnav" style="width:200px;">
+ Logtypes
+ <% for logtype in agent.logtypes do%>
+ <div class="adendem"><%=logtype.name%></div>
+ <%end%>
+ </div>
+ <div clear></div>
+ <div class="info">Total Events: <%= agent.events.count %></div>
+ <div class="info">Hostname: <%=agent.hostname%></div>
+ <div class="info">Listenport: <%=agent.port%></div>
+ <div class="info">Key: <%=agent.authkey%></div>
+ <div class="info"><%=link_to("edit", :action => "edit", :id => agent.id)%></div>
+ </div>
+</div>
+<%end%>
+
<div class="pagination">
<%= will_paginate @event %>
</div>
\ No newline at end of file
diff --git a/src/server/app/views/events/show.rhtml b/src/server/app/views/events/show.rhtml
index dfad149..92b14ba 100644
--- a/src/server/app/views/events/show.rhtml
+++ b/src/server/app/views/events/show.rhtml
@@ -1,23 +1,25 @@
<h1>All Events</h1>
<ul>
<% for event in @events do %>
- <li><%= if params[:withepoch] then event.time else Time.at(event.time.to_f) end %> : <%= event.loglevel.name%> <%=event.payload%></li>
+ <li><%= if params[:withepoch] then event.etime else Time.at(event.etime.to_f) end %> : <%= event.loglevel.name%> <%=event.payload%></li>
<%end%>
</ul>
<div class="pagination">
<%= will_paginate @event %>
</div>
<div class="adendem">
Records per page:
<%=link_to "20", :withepoch => params[:withepoch], :page => 1, :perpage => "20" %> |
<%=link_to "50", :withepoch => params[:withepoch], :page => 1, :perpage => "50" %> |
<%=link_to "100", :withepoch => params[:withepoch], :page => 1, :perpage => "100" %> |
<%=link_to "200", :withepoch => params[:withepoch], :page => 1, :perpage => "200" %>
</div>
<%if params[:withepoch]%>
<div class="adendem"><%=link_to "show regular time", :withepoch => nil, :page => params[:page], :perpage => params[:perpage] %></div>
<%else%>
<div class="adendem"><%=link_to "show epoch time", :withepoch => 1, :page => params[:page], :perpage => params[:perpage] %></div>
<%end%>
+<div class="adendem"><%=link_to "view by agent", :controller => 'agents', :action => "index" %> | <%=link_to "view by logtype", :controller => 'logtypes', :action => 'index' %></div>
+
diff --git a/src/server/app/views/logtypes/edit.rhtml b/src/server/app/views/logtypes/edit.rhtml
new file mode 100644
index 0000000..7b67d10
--- /dev/null
+++ b/src/server/app/views/logtypes/edit.rhtml
@@ -0,0 +1,18 @@
+<h1>Edit <%=@logtype.name%></h1>
+<%= error_messages_for 'logtype' %>
+<div id="form">
+
+ <table width="100%">
+ <% form_for :logtype do |f|%>
+ <tr>
+ <td>Name:</td>
+ <td align="right"><%= f.text_field :name, :class => "fbox"%></td>
+ </tr>
+ <tr>
+ <td><%= submit_tag "Update Logtype", :class => "submitbutton" %></td>
+ <td></td>
+ </tr>
+ <%end%>
+ </table>
+
+</div>
\ No newline at end of file
diff --git a/src/server/app/views/logtypes/index.rhtml b/src/server/app/views/logtypes/index.rhtml
index 0932b43..1cc188e 100644
--- a/src/server/app/views/logtypes/index.rhtml
+++ b/src/server/app/views/logtypes/index.rhtml
@@ -1,10 +1,20 @@
<h1>Logtypes</h1>
-<ul>
- <% for type in @logtypes do%>
- <li><%=link_to(type.name, :action => 'show', :id => type.id)%> :: <%= type.events.count%> total events</li>
- <%end%>
-</ul>
+<div class="subnav"><%=link_to("Create new Logtype", :action => "new")%></div>
+
+<div class="clear"></div>
+
+<% for type in @logtypes do%>
+<div class="agent">
+ <a href='#' onclick="$('.typeinfo<%=type.id%>').toggle();return false"><%=type.name%></a> : <%=link_to("View Events", :action=>"show", :id=>type.id)%>
+ <div class="typeinfo<%=type.id%>" style="display:none; background:#FF9; padding: 3px; border: 1px solid #000">
+ <div class="info">Total Events: <%= type.events.count %></div>
+ <div class="info">Total Agents: <%=type.agents.count%></div>
+ <div class="info"><%=link_to("edit", :action => "edit", :id => type.id)%></div>
+ </div>
+</div>
+<%end%>
+
<div class="pagination">
<%= will_paginate @logtypes %>
-</div>
\ No newline at end of file
+</div>
diff --git a/src/server/app/views/logtypes/new.rhtml b/src/server/app/views/logtypes/new.rhtml
new file mode 100644
index 0000000..c49c5b7
--- /dev/null
+++ b/src/server/app/views/logtypes/new.rhtml
@@ -0,0 +1,18 @@
+<h1>Create a New Logtype</h1>
+<%= error_messages_for 'logtype' %>
+<div id="form">
+
+ <table width="100%">
+ <% form_for :logtype do |f|%>
+ <tr>
+ <td>Name:</td>
+ <td align="right"><%= f.text_field :name, :class => "fbox"%></td>
+ </tr>
+ <tr>
+ <td><%= submit_tag "Add Logtype", :class => "submitbutton" %></td>
+ <td></td>
+ </tr>
+ <%end%>
+ </table>
+
+</div>
\ No newline at end of file
diff --git a/src/server/app/views/logtypes/show.rhtml b/src/server/app/views/logtypes/show.rhtml
index b72325e..c8c1d20 100644
--- a/src/server/app/views/logtypes/show.rhtml
+++ b/src/server/app/views/logtypes/show.rhtml
@@ -1,24 +1,32 @@
<h1>All Events for <%=@logtype.name%></h1>
+<div id="filter">
+ <a href='#' onclick="$('.agentinfo').toggle();return false">View by Agent</a>
+ <div class="agentinfo" style="display:none; background:#FF9; padding: 3px; border: 1px solid #000">
+ <% for agent in @logtype.agents do %>
+ <div class="info"><%= link_to( agent.name, :controller => 'agents', :action => 'show', :logtype => @logtype.id, :withepoch => params[:withepoch], :id => agent.id )%></div>
+ <%end%>
+ </div>
+</div>
<div id="eventlist">
<ul>
<% for event in @events do %>
<li><%= event.agent.name %> : <%= if params[:withepoch] then event.time else Time.at(event.time.to_f) end %> : <%= event.loglevel.name %> <%=event.payload%></li>
<%end%>
</ul>
</div>
<div class="pagination">
<%= will_paginate @event %>
</div>
<div class="adendem">
Records per page:
<%=link_to "20", :withepoch => params[:withepoch], :page => 1, :perpage => "20" %> |
<%=link_to "50", :withepoch => params[:withepoch], :page => 1, :perpage => "50" %> |
<%=link_to "100", :withepoch => params[:withepoch], :page => 1, :perpage => "100" %> |
<%=link_to "200", :withepoch => params[:withepoch], :page => 1, :perpage => "200" %>
</div>
<%if params[:withepoch]%>
<div class="adendem"><%=link_to "show regular time", :withepoch => nil, :page => params[:page], :perpage => params[:perpage] %></div>
<%else%>
<div class="adendem"><%=link_to "show epoch time", :withepoch => 1, :page => params[:page], :perpage => params[:perpage] %></div>
<%end%>
\ No newline at end of file
diff --git a/src/server/db/migrate/20090730154024_create_agents_logtype_map.rb b/src/server/db/migrate/20090730154024_create_agents_logtype_map.rb
index 1a3a379..e144020 100644
--- a/src/server/db/migrate/20090730154024_create_agents_logtype_map.rb
+++ b/src/server/db/migrate/20090730154024_create_agents_logtype_map.rb
@@ -1,15 +1,15 @@
class CreateAgentsLogtypeMap < ActiveRecord::Migration
def self.up
- create_table :agents_logtypes do |t|
+ create_table :agents_logtypes, :id => false do |t|
t.column :logtype_id, :int
t.column :agent_id, :int
t.timestamps
end
add_index :agents_logtypes, :logtype_id
add_index :agents_logtypes, :agent_id
end
def self.down
drop_table :events
end
end
diff --git a/src/server/db/schema.rb b/src/server/db/schema.rb
index 9c6d048..bc10792 100644
--- a/src/server/db/schema.rb
+++ b/src/server/db/schema.rb
@@ -1,77 +1,77 @@
# This file is auto-generated from the current state of the database. Instead of editing this file,
# please use the migrations feature of Active Record to incrementally modify your database, and
# then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your database schema. If you need
# to create the application database on another system, you should be using db:schema:load, not running
# all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended to check this file into your version control system.
ActiveRecord::Schema.define(:version => 20090804022411) do
create_table "agents", :force => true do |t|
t.string "name"
t.string "hostname"
t.string "port"
t.string "authkey"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "agents", ["hostname"], :name => "index_agents_on_hostname"
add_index "agents", ["name"], :name => "index_agents_on_name"
- create_table "agents_logtypes", :force => true do |t|
+ create_table "agents_logtypes", :id => false, :force => true do |t|
t.integer "logtype_id"
t.integer "agent_id"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "agents_logtypes", ["agent_id"], :name => "index_agents_logtypes_on_agent_id"
add_index "agents_logtypes", ["logtype_id"], :name => "index_agents_logtypes_on_logtype_id"
create_table "events", :force => true do |t|
t.string "payload"
t.string "staticentry_id"
t.integer "agent_id"
t.integer "loglevel_id"
t.integer "logtype_id"
t.string "etime"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "events", ["agent_id"], :name => "index_events_on_agent_id"
add_index "events", ["etime"], :name => "index_events_on_etime"
add_index "events", ["loglevel_id"], :name => "index_events_on_loglevel_id"
add_index "events", ["logtype_id"], :name => "index_events_on_logtype_id"
add_index "events", ["staticentry_id"], :name => "index_events_on_staticentry_id"
create_table "loglevels", :force => true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "logtypes", :force => true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "logtypes", ["name"], :name => "index_logtypes_on_name"
create_table "staticentries", :force => true do |t|
t.integer "logtype_id"
t.text "data"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "staticentries", ["id"], :name => "index_staticentries_on_id"
add_index "staticentries", ["logtype_id"], :name => "index_staticentries_on_logtype_id"
end
diff --git a/src/server/public/images/addserver.png b/src/server/public/images/addserver.png
new file mode 100644
index 0000000..95f7ebd
Binary files /dev/null and b/src/server/public/images/addserver.png differ
diff --git a/src/server/public/images/serverdown.png b/src/server/public/images/serverdown.png
new file mode 100644
index 0000000..b702111
Binary files /dev/null and b/src/server/public/images/serverdown.png differ
diff --git a/src/server/public/images/serverup.png b/src/server/public/images/serverup.png
new file mode 100644
index 0000000..ed27a0b
Binary files /dev/null and b/src/server/public/images/serverup.png differ
diff --git a/src/server/public/stylesheets/main.css b/src/server/public/stylesheets/main.css
index 2c5ebf4..be6d785 100644
--- a/src/server/public/stylesheets/main.css
+++ b/src/server/public/stylesheets/main.css
@@ -1,175 +1,183 @@
body {
background: #fff;
color: #000;
margin: 0px;
padding: 0px;
color: #333;
font-weight:bold;
font-family: serif;
}
a {
text-decoration: none;
color: #660033;
}
a:hover {
background: #000033;
color: #fff;
padding: 2px;
}
#container {
padding: 0px;
margin: auto;
width: 900px;
}
#header {
width: 100%;
margin: 0px;
height: 95px;
background: #333;
border-bottom: solid 6px #000;
color:#fff;
}
#logo {
position: absolute;
padding-top: 20px;
padding-left: 45px;
font-weight:bold;
font-size: 55px;
color: #fff;
}
#search {
text-align: right;
padding-top: 20px;
padding-right: 50px;
}
.searchbox {
background: #663366;
border: 1px solid #000;
color: #fff;
font-size: 20px;
padding: 2px;
font-weight: none;
}
#eventlist {
min-height: 350px;
_height: 350px;
}
#topnav a {
background: #000;
padding: 4px;
padding-bottom: 4px;
padding-left: 6px;
padding-right: 6px;
color: #fff;
border-left: solid 2px #000033;
border-right: solid 2px #000033;
border-bottom: solid 2px #000033;
}
#topnav a:hover {
background: #666;
padding: 4px;
padding-bottom: 4px;
padding-left: 6px;
padding-right: 6px;
color: #fff;
border-left: solid 2px #000033;
border-right: solid 2px #000033;
border-bottom: solid 2px #000033;
}
.topnav {
background: #666;
padding: 2px;
padding-bottom: 4px;
padding-left: 6px;
padding-right: 6px;
color: #fff;
border-left: solid 2px #000033;
border-right: solid 2px #000033;
border-bottom: solid 2px #000033;
}
#topnav {
font-size: 20px;
padding: 2px;
padding-bottom: 4px;
padding-left: 6px;
padding-right: 6px;
color: #fff;
}
#main {
min-height: 400px;
_height: 400px; /* IE min-height hack */
}
#footer {
text-align: center;
width: 900px;
border-top: 2px solid #000;
padding-top: 15px;
}
#notice {
margin-top: 10px;
width: 100%;
background: #09F;
color: #000;
padding: 10px;
border: 1px solid #333;
}
#error {
margin-top: 10px;
width: 100%;
background: #F00;
color: #000;
padding: 10px;
border: 1px solid #333;
}
#form {
width: 350px;
margin: auto;
}
.submitbutton {
background: #660033;
color: #fff;
border: 3px solid #000;
padding: 6px;
}
.fbox {
background: #ffff55;
border: 1px solid #333;
padding: 2px;
}
.clear {
clear:both;
}
.adendem {
font-size: 14px;
font-weight: normal;
}
.in20 {
padding-left: 20px;
padding-right: 20px;
}
.errorExplanation {
width: 800px;
margin: auto;
padding: 3px;
padding-left: 10px;
padding-right: 10px;
background: #ffff55;
border: 1px solid #333;
margin-bottom: 10px;
}
+
+.subnav {
+ float:right;
+}
+.agent {
+ margin-top: 10px;
+ padding: 2px;
+}
\ No newline at end of file
|
parabuzzle/cistern
|
e3b2ae5999b23f4e44f2e2b2a0f7a0bf0e584166
|
Pulled in the acts_as_ferret plugin instead of relying on the gem
|
diff --git a/src/server/config/environment.rb b/src/server/config/environment.rb
index e0f5aac..99b1152 100644
--- a/src/server/config/environment.rb
+++ b/src/server/config/environment.rb
@@ -1,44 +1,44 @@
# Be sure to restart your server when you modify this file
# Specifies gem version of Rails to use when vendor/rails is not present
RAILS_GEM_VERSION = '2.3.3' unless defined? RAILS_GEM_VERSION
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
Rails::Initializer.run do |config|
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Add additional load paths for your own custom dirs
# config.load_paths += %W( #{RAILS_ROOT}/extras )
# Specify gems that this application depends on and have them installed with rake gems:install
# config.gem "bj"
# config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
# config.gem "sqlite3-ruby", :lib => "sqlite3"
# config.gem "aws-s3", :lib => "aws/s3"
config.gem "eventmachine"
config.gem "will_paginate"
- config.gem "acts_as_ferret"
+ #config.gem "acts_as_ferret"
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Skip frameworks you're not going to use. To use Rails without a database,
# you must remove the Active Record framework.
# config.frameworks -= [ :active_record, :active_resource, :action_mailer ]
# Activate observers that should always be running
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names.
config.time_zone = 'UTC'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')]
# config.i18n.default_locale = :de
end
\ No newline at end of file
diff --git a/src/server/vendor/plugins/acts_as_ferret/LICENSE b/src/server/vendor/plugins/acts_as_ferret/LICENSE
new file mode 100644
index 0000000..b07e5a5
--- /dev/null
+++ b/src/server/vendor/plugins/acts_as_ferret/LICENSE
@@ -0,0 +1,20 @@
+Copyright (c) 2006 Kasper Weibel, Jens Kraemer
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/src/server/vendor/plugins/acts_as_ferret/README b/src/server/vendor/plugins/acts_as_ferret/README
new file mode 100644
index 0000000..7c77ee1
--- /dev/null
+++ b/src/server/vendor/plugins/acts_as_ferret/README
@@ -0,0 +1,78 @@
+= acts_as_ferret
+
+This ActiveRecord mixin adds full text search capabilities to any Rails model.
+
+It is heavily based on the original acts_as_ferret plugin done by
+Kasper Weibel and a modified version done by Thomas Lockney, which
+both can be found on http://ferret.davebalmain.com/trac/wiki/FerretOnRails
+
+== Project Homepage
+
+http://rm.jkraemer.net/projects/show/aaf
+
+== Installation
+
+Aaf is available via git from rubyforge.org and github.com. Github also offers
+tarball downloads, check out http://github.com/jkraemer/acts_as_ferret/tree/master .
+
+=== Installation inside your Rails > 2.1 project via gem management
+
+Add this to your projects config/environment.rb:
+
+<tt>config.gem 'acts_as_ferret', :version => '~> 0.4.4'</tt>
+
+Or, use github:
+
+<tt>config.gem 'jkraemer-acts_as_ferret', :version => '~> 0.4.4', :lib => 'acts_as_ferret', :source => 'http://gems.github.com'"</tt>
+
+=== Installation inside your Rails project via script/plugin
+
+script/plugin install git://github.com/jkraemer/acts_as_ferret.git
+
+The rubyforge repository is located at git://rubyforge.org/actsasferret.git
+
+=== Old SVN repository
+
+In november 2008 I stopped updating the svn repository that has been the main
+repository for aaf for several years. In case you want to retrieve any of the
+older versions of the plugin, it's still there at
+
+svn://code.jkraemer.net/acts_as_ferret/
+
+=== System-wide installation with Rubygems
+
+<tt>sudo gem install acts_as_ferret</tt>
+
+To use acts_as_ferret in your project, add the following line to the end of your
+project's config/environment.rb:
+
+<tt>require 'acts_as_ferret'</tt>
+
+Call the aaf_install script that came with the gem inside your project
+directory to install the sample config file and the drb server start/stop
+script.
+
+
+== Usage
+
+include the following in your model class (specifiying the fields you want to get indexed):
+
+<tt>acts_as_ferret :fields => [ :title, :description ]</tt>
+
+now you can use ModelClass.find_with_ferret(query) to find instances of your model
+whose indexed fields match a given query. All query terms are required by default,
+but explicit OR queries are possible. This differs from the ferret default, but
+imho is the more often needed/expected behaviour (more query terms result in
+less results).
+
+Please see ActsAsFerret::ActMethods#acts_as_ferret for more information.
+
+== License
+
+Released under the MIT license.
+
+== Authors
+
+* Kasper Weibel Nielsen-Refs (original author)
+* Jens Kraemer <jk@jkraemer.net> (current maintainer)
+
diff --git a/src/server/vendor/plugins/acts_as_ferret/acts_as_ferret.gemspec b/src/server/vendor/plugins/acts_as_ferret/acts_as_ferret.gemspec
new file mode 100644
index 0000000..ce73e09
--- /dev/null
+++ b/src/server/vendor/plugins/acts_as_ferret/acts_as_ferret.gemspec
@@ -0,0 +1,260 @@
+--- !ruby/object:Gem::Specification
+name: acts_as_ferret
+version: !ruby/object:Gem::Version
+ version: 0.4.4
+platform: ruby
+authors:
+- Jens Kraemer
+autorequire: acts_as_ferret
+bindir: bin
+cert_chain: []
+
+date: 2009-05-28 00:00:00 +02:00
+default_executable: aaf_install
+dependencies: []
+
+description:
+email: jk@jkraemer.net
+executables:
+- aaf_install
+extensions: []
+
+extra_rdoc_files: []
+
+files:
+- acts_as_ferret.gemspec
+- bin
+- bin/aaf_install
+- config
+- config/ferret_server.yml
+- doc
+- doc/demo
+- doc/demo/app
+- doc/demo/app/controllers
+- doc/demo/app/controllers/admin
+- doc/demo/app/controllers/admin/backend_controller.rb
+- doc/demo/app/controllers/admin_area_controller.rb
+- doc/demo/app/controllers/application.rb
+- doc/demo/app/controllers/contents_controller.rb
+- doc/demo/app/controllers/searches_controller.rb
+- doc/demo/app/helpers
+- doc/demo/app/helpers/admin
+- doc/demo/app/helpers/admin/backend_helper.rb
+- doc/demo/app/helpers/application_helper.rb
+- doc/demo/app/helpers/content_helper.rb
+- doc/demo/app/helpers/search_helper.rb
+- doc/demo/app/models
+- doc/demo/app/models/comment.rb
+- doc/demo/app/models/content.rb
+- doc/demo/app/models/content_base.rb
+- doc/demo/app/models/search.rb
+- doc/demo/app/models/shared_index1.rb
+- doc/demo/app/models/shared_index2.rb
+- doc/demo/app/models/special_content.rb
+- doc/demo/app/models/stats.rb
+- doc/demo/app/views
+- doc/demo/app/views/admin
+- doc/demo/app/views/admin/backend
+- doc/demo/app/views/admin/backend/search.rhtml
+- doc/demo/app/views/contents
+- doc/demo/app/views/contents/_form.rhtml
+- doc/demo/app/views/contents/edit.rhtml
+- doc/demo/app/views/contents/index.rhtml
+- doc/demo/app/views/contents/new.rhtml
+- doc/demo/app/views/contents/show.rhtml
+- doc/demo/app/views/layouts
+- doc/demo/app/views/layouts/application.html.erb
+- doc/demo/app/views/searches
+- doc/demo/app/views/searches/_content.html.erb
+- doc/demo/app/views/searches/search.html.erb
+- doc/demo/config
+- doc/demo/config/boot.rb
+- doc/demo/config/database.yml
+- doc/demo/config/environment.rb
+- doc/demo/config/environments
+- doc/demo/config/environments/development.rb
+- doc/demo/config/environments/production.rb
+- doc/demo/config/environments/test.rb
+- doc/demo/config/ferret_server.yml
+- doc/demo/config/lighttpd.conf
+- doc/demo/config/routes.rb
+- doc/demo/db
+- doc/demo/db/development_structure.sql
+- doc/demo/db/migrate
+- doc/demo/db/migrate/001_initial_migration.rb
+- doc/demo/db/migrate/002_add_type_to_contents.rb
+- doc/demo/db/migrate/003_create_shared_index1s.rb
+- doc/demo/db/migrate/004_create_shared_index2s.rb
+- doc/demo/db/migrate/005_special_field.rb
+- doc/demo/db/migrate/006_create_stats.rb
+- doc/demo/db/schema.sql
+- doc/demo/doc
+- doc/demo/doc/howto.txt
+- doc/demo/doc/README_FOR_APP
+- doc/demo/log
+- doc/demo/public
+- doc/demo/public/.htaccess
+- doc/demo/public/404.html
+- doc/demo/public/500.html
+- doc/demo/public/dispatch.cgi
+- doc/demo/public/dispatch.fcgi
+- doc/demo/public/dispatch.rb
+- doc/demo/public/favicon.ico
+- doc/demo/public/images
+- doc/demo/public/images/rails.png
+- doc/demo/public/index.html
+- doc/demo/public/robots.txt
+- doc/demo/public/stylesheets
+- doc/demo/public/stylesheets/scaffold.css
+- doc/demo/Rakefile
+- doc/demo/README
+- doc/demo/README_DEMO
+- doc/demo/script
+- doc/demo/script/about
+- doc/demo/script/breakpointer
+- doc/demo/script/console
+- doc/demo/script/destroy
+- doc/demo/script/ferret_server
+- doc/demo/script/generate
+- doc/demo/script/performance
+- doc/demo/script/performance/benchmarker
+- doc/demo/script/performance/profiler
+- doc/demo/script/plugin
+- doc/demo/script/process
+- doc/demo/script/process/inspector
+- doc/demo/script/process/reaper
+- doc/demo/script/process/spawner
+- doc/demo/script/process/spinner
+- doc/demo/script/runner
+- doc/demo/script/server
+- doc/demo/test
+- doc/demo/test/fixtures
+- doc/demo/test/fixtures/comments.yml
+- doc/demo/test/fixtures/contents.yml
+- doc/demo/test/fixtures/remote_contents.yml
+- doc/demo/test/fixtures/shared_index1s.yml
+- doc/demo/test/fixtures/shared_index2s.yml
+- doc/demo/test/functional
+- doc/demo/test/functional/admin
+- doc/demo/test/functional/admin/backend_controller_test.rb
+- doc/demo/test/functional/contents_controller_test.rb
+- doc/demo/test/functional/searches_controller_test.rb
+- doc/demo/test/smoke
+- doc/demo/test/smoke/drb_smoke_test.rb
+- doc/demo/test/smoke/process_stats.rb
+- doc/demo/test/test_helper.rb
+- doc/demo/test/unit
+- doc/demo/test/unit/comment_test.rb
+- doc/demo/test/unit/content_test.rb
+- doc/demo/test/unit/ferret_result_test.rb
+- doc/demo/test/unit/multi_index_test.rb
+- doc/demo/test/unit/remote_index_test.rb
+- doc/demo/test/unit/shared_index1_test.rb
+- doc/demo/test/unit/shared_index2_test.rb
+- doc/demo/test/unit/sort_test.rb
+- doc/demo/test/unit/special_content_test.rb
+- doc/demo/vendor
+- doc/demo/vendor/plugins
+- doc/demo/vendor/plugins/will_paginate
+- doc/demo/vendor/plugins/will_paginate/init.rb
+- doc/demo/vendor/plugins/will_paginate/lib
+- doc/demo/vendor/plugins/will_paginate/lib/will_paginate
+- doc/demo/vendor/plugins/will_paginate/lib/will_paginate/collection.rb
+- doc/demo/vendor/plugins/will_paginate/lib/will_paginate/core_ext.rb
+- doc/demo/vendor/plugins/will_paginate/lib/will_paginate/finder.rb
+- doc/demo/vendor/plugins/will_paginate/lib/will_paginate/view_helpers.rb
+- doc/demo/vendor/plugins/will_paginate/LICENSE
+- doc/demo/vendor/plugins/will_paginate/Rakefile
+- doc/demo/vendor/plugins/will_paginate/README
+- doc/demo/vendor/plugins/will_paginate/test
+- doc/demo/vendor/plugins/will_paginate/test/array_pagination_test.rb
+- doc/demo/vendor/plugins/will_paginate/test/boot.rb
+- doc/demo/vendor/plugins/will_paginate/test/console
+- doc/demo/vendor/plugins/will_paginate/test/finder_test.rb
+- doc/demo/vendor/plugins/will_paginate/test/fixtures
+- doc/demo/vendor/plugins/will_paginate/test/fixtures/admin.rb
+- doc/demo/vendor/plugins/will_paginate/test/fixtures/companies.yml
+- doc/demo/vendor/plugins/will_paginate/test/fixtures/company.rb
+- doc/demo/vendor/plugins/will_paginate/test/fixtures/developer.rb
+- doc/demo/vendor/plugins/will_paginate/test/fixtures/developers_projects.yml
+- doc/demo/vendor/plugins/will_paginate/test/fixtures/project.rb
+- doc/demo/vendor/plugins/will_paginate/test/fixtures/projects.yml
+- doc/demo/vendor/plugins/will_paginate/test/fixtures/replies.yml
+- doc/demo/vendor/plugins/will_paginate/test/fixtures/reply.rb
+- doc/demo/vendor/plugins/will_paginate/test/fixtures/schema.sql
+- doc/demo/vendor/plugins/will_paginate/test/fixtures/topic.rb
+- doc/demo/vendor/plugins/will_paginate/test/fixtures/topics.yml
+- doc/demo/vendor/plugins/will_paginate/test/fixtures/user.rb
+- doc/demo/vendor/plugins/will_paginate/test/fixtures/users.yml
+- doc/demo/vendor/plugins/will_paginate/test/helper.rb
+- doc/demo/vendor/plugins/will_paginate/test/lib
+- doc/demo/vendor/plugins/will_paginate/test/lib/activerecord_test_connector.rb
+- doc/demo/vendor/plugins/will_paginate/test/lib/load_fixtures.rb
+- doc/demo/vendor/plugins/will_paginate/test/pagination_test.rb
+- doc/monit-example
+- doc/README.win32
+- init.rb
+- install.rb
+- lib
+- lib/act_methods.rb
+- lib/acts_as_ferret.rb
+- lib/ar_mysql_auto_reconnect_patch.rb
+- lib/blank_slate.rb
+- lib/bulk_indexer.rb
+- lib/class_methods.rb
+- lib/ferret_extensions.rb
+- lib/ferret_find_methods.rb
+- lib/ferret_result.rb
+- lib/ferret_server.rb
+- lib/index.rb
+- lib/instance_methods.rb
+- lib/local_index.rb
+- lib/more_like_this.rb
+- lib/multi_index.rb
+- lib/rdig_adapter.rb
+- lib/remote_functions.rb
+- lib/remote_index.rb
+- lib/remote_multi_index.rb
+- lib/search_results.rb
+- lib/server_manager.rb
+- lib/unix_daemon.rb
+- lib/without_ar.rb
+- LICENSE
+- rakefile
+- README
+- recipes
+- recipes/aaf_recipes.rb
+- script
+- script/ferret_daemon
+- script/ferret_server
+- script/ferret_service
+- tasks
+- tasks/ferret.rake
+has_rdoc: true
+homepage: http://projects.jkraemer.net/acts_as_ferret
+post_install_message:
+rdoc_options: []
+
+require_paths:
+- lib
+required_ruby_version: !ruby/object:Gem::Requirement
+ requirements:
+ - - ">="
+ - !ruby/object:Gem::Version
+ version: "0"
+ version:
+required_rubygems_version: !ruby/object:Gem::Requirement
+ requirements:
+ - - ">="
+ - !ruby/object:Gem::Version
+ version: "0"
+ version:
+requirements: []
+
+rubyforge_project:
+rubygems_version: 1.3.1
+signing_key:
+specification_version: 2
+summary: acts_as_ferret - Ferret based full text search for any ActiveRecord model
+test_files: []
+
diff --git a/src/server/vendor/plugins/acts_as_ferret/bin/aaf_install b/src/server/vendor/plugins/acts_as_ferret/bin/aaf_install
new file mode 100644
index 0000000..31ed6bb
--- /dev/null
+++ b/src/server/vendor/plugins/acts_as_ferret/bin/aaf_install
@@ -0,0 +1,23 @@
+# acts_as_ferret gem install script
+# Use inside the root of your Rails project
+require 'fileutils'
+
+@basedir = File.join(File.dirname(__FILE__), '..')
+
+def install(dir, file, executable=false)
+ puts "Installing: #{file}"
+ target = File.join('.', dir, file)
+ if File.exists?(target)
+ puts "#{target} already exists, skipping"
+ else
+ FileUtils.cp File.join(@basedir, dir, file), target
+ FileUtils.chmod 0755, target if executable
+ end
+end
+
+
+install 'script', 'ferret_server', true
+install 'config', 'ferret_server.yml'
+
+puts IO.read(File.join(@basedir, 'README'))
+
diff --git a/src/server/vendor/plugins/acts_as_ferret/config/ferret_server.yml b/src/server/vendor/plugins/acts_as_ferret/config/ferret_server.yml
new file mode 100644
index 0000000..402e54e
--- /dev/null
+++ b/src/server/vendor/plugins/acts_as_ferret/config/ferret_server.yml
@@ -0,0 +1,24 @@
+# configuration for the acts_as_ferret DRb server
+# host: where to reach the DRb server (used by application processes to contact the server)
+# port: which port the server should listen on
+# socket: where the DRb server should create the socket (absolute path), this setting overrides host:port configuration
+# pid_file: location of the server's pid file (relative to RAILS_ROOT)
+# log_file: log file (default: RAILS_ROOT/log/ferret_server.log
+# log_level: log level for the server's logger
+production:
+ host: localhost
+ port: 9010
+ pid_file: log/ferret.pid
+ log_file: log/ferret_server.log
+ log_level: warn
+
+# aaf won't try to use the DRb server in environments that are not
+# configured here.
+#development:
+# host: localhost
+# port: 9010
+# pid_file: log/ferret.pid
+#test:
+# host: localhost
+# port: 9009
+# pid_file: log/ferret.pid
diff --git a/src/server/vendor/plugins/acts_as_ferret/init.rb b/src/server/vendor/plugins/acts_as_ferret/init.rb
new file mode 100644
index 0000000..a15a3cd
--- /dev/null
+++ b/src/server/vendor/plugins/acts_as_ferret/init.rb
@@ -0,0 +1,24 @@
+# Copyright (c) 2006 Kasper Weibel Nielsen-Refs, Thomas Lockney, Jens Krämer
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in all
+# copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+# SOFTWARE.
+
+require 'acts_as_ferret'
+
+config.after_initialize { ActsAsFerret::load_config }
+config.to_prepare { ActsAsFerret::load_config }
diff --git a/src/server/vendor/plugins/acts_as_ferret/install.rb b/src/server/vendor/plugins/acts_as_ferret/install.rb
new file mode 100644
index 0000000..2a28aa6
--- /dev/null
+++ b/src/server/vendor/plugins/acts_as_ferret/install.rb
@@ -0,0 +1,18 @@
+# acts_as_ferret install script
+require 'fileutils'
+
+def install(file)
+ puts "Installing: #{file}"
+ target = File.join(File.dirname(__FILE__), '..', '..', '..', file)
+ if File.exists?(target)
+ puts "target #{target} already exists, skipping"
+ else
+ FileUtils.cp File.join(File.dirname(__FILE__), file), target
+ end
+end
+
+install File.join( 'script', 'ferret_server' )
+install File.join( 'config', 'ferret_server.yml' )
+
+puts IO.read(File.join(File.dirname(__FILE__), 'README'))
+
diff --git a/src/server/vendor/plugins/acts_as_ferret/lib/act_methods.rb b/src/server/vendor/plugins/acts_as_ferret/lib/act_methods.rb
new file mode 100644
index 0000000..b985c87
--- /dev/null
+++ b/src/server/vendor/plugins/acts_as_ferret/lib/act_methods.rb
@@ -0,0 +1,147 @@
+module ActsAsFerret #:nodoc:
+
+ # This module defines the acts_as_ferret method and is included into
+ # ActiveRecord::Base
+ module ActMethods
+
+
+ def reloadable?; false end
+
+ # declares a class as ferret-searchable.
+ #
+ # ====options:
+ # fields:: names all fields to include in the index. If not given,
+ # all attributes of the class will be indexed. You may also give
+ # symbols pointing to instance methods of your model here, i.e.
+ # to retrieve and index data from a related model.
+ #
+ # additional_fields:: names fields to include in the index, in addition
+ # to those derived from the db scheme. use if you want
+ # to add custom fields derived from methods to the db
+ # fields (which will be picked by aaf). This option will
+ # be ignored when the fields option is given, in that
+ # case additional fields get specified there.
+ #
+ # if:: Can be set to a block that will be called with the record in question
+ # to determine if it should be indexed or not.
+ #
+ # index_dir:: declares the directory where to put the index for this class.
+ # The default is RAILS_ROOT/index/RAILS_ENV/CLASSNAME.
+ # The index directory will be created if it doesn't exist.
+ #
+ # reindex_batch_size:: reindexing is done in batches of this size, default is 1000
+ # mysql_fast_batches:: set this to false to disable the faster mysql batching
+ # algorithm if this model uses a non-integer primary key named
+ # 'id' on MySQL.
+ #
+ # ferret:: Hash of Options that directly influence the way the Ferret engine works. You
+ # can use most of the options the Ferret::I class accepts here, too. Among the
+ # more useful are:
+ #
+ # or_default:: whether query terms are required by
+ # default (the default, false), or not (true)
+ #
+ # analyzer:: the analyzer to use for query parsing (default: nil,
+ # which means the ferret StandardAnalyzer gets used)
+ #
+ # default_field:: use to set one or more fields that are searched for query terms
+ # that don't have an explicit field list. This list should *not*
+ # contain any untokenized fields. If it does, you're asking
+ # for trouble (i.e. not getting results for queries having
+ # stop words in them). Aaf by default initializes the default field
+ # list to contain all tokenized fields. If you use :single_index => true,
+ # you really should set this option specifying your default field
+ # list (which should be equal in all your classes sharing the index).
+ # Otherwise you might get incorrect search results and you won't get
+ # any lazy loading of stored field data.
+ #
+ # For downwards compatibility reasons you can also specify the Ferret options in the
+ # last Hash argument.
+ def acts_as_ferret(options={})
+
+ extend ClassMethods
+
+ include InstanceMethods
+ include MoreLikeThis::InstanceMethods
+
+ if options[:rdig]
+ cattr_accessor :rdig_configuration
+ self.rdig_configuration = options[:rdig]
+ require 'rdig_adapter'
+ include ActsAsFerret::RdigAdapter
+ end
+
+ unless included_modules.include?(ActsAsFerret::WithoutAR)
+ # set up AR hooks
+ after_create :ferret_create
+ after_update :ferret_update
+ after_destroy :ferret_destroy
+ end
+
+ cattr_accessor :aaf_configuration
+
+ # apply default config for rdig based models
+ if options[:rdig]
+ options[:fields] ||= { :title => { :boost => 3, :store => :yes },
+ :content => { :store => :yes } }
+ end
+
+ # name of this index
+ index_name = options.delete(:index) || self.name.underscore
+
+ index = ActsAsFerret::register_class_with_index(self, index_name, options)
+ self.aaf_configuration = index.index_definition.dup
+ # logger.debug "configured index for class #{self.name}:\n#{aaf_configuration.inspect}"
+
+ # update our copy of the global index config with options local to this class
+ aaf_configuration[:class_name] ||= self.name
+ aaf_configuration[:if] ||= options[:if]
+
+ # add methods for retrieving field values
+ add_fields options[:fields]
+ add_fields options[:additional_fields]
+ add_fields aaf_configuration[:fields]
+ add_fields aaf_configuration[:additional_fields]
+
+ end
+
+
+ protected
+
+
+ # helper to defines a method which adds the given field to a ferret
+ # document instance
+ def define_to_field_method(field, options = {})
+ method_name = "#{field}_to_ferret"
+ return if instance_methods.include?(method_name) # already defined
+ aaf_configuration[:defined_fields] ||= {}
+ aaf_configuration[:defined_fields][field] = options
+ dynamic_boost = options[:boost] if options[:boost].is_a?(Symbol)
+ via = options[:via] || field
+ define_method(method_name.to_sym) do
+ val = begin
+ content_for_field_name(field, via, dynamic_boost)
+ rescue
+ logger.warn("Error retrieving value for field #{field}: #{$!}")
+ ''
+ end
+ logger.debug("Adding field #{field} with value '#{val}' to index")
+ val
+ end
+ end
+
+ def add_fields(field_config)
+ if field_config.is_a? Hash
+ field_config.each_pair do |field, options|
+ define_to_field_method field, options
+ end
+ elsif field_config.respond_to?(:each)
+ field_config.each do |field|
+ define_to_field_method field
+ end
+ end
+ end
+
+ end
+
+end
diff --git a/src/server/vendor/plugins/acts_as_ferret/lib/acts_as_ferret.rb b/src/server/vendor/plugins/acts_as_ferret/lib/acts_as_ferret.rb
new file mode 100644
index 0000000..c6e8f14
--- /dev/null
+++ b/src/server/vendor/plugins/acts_as_ferret/lib/acts_as_ferret.rb
@@ -0,0 +1,585 @@
+# Copyright (c) 2006 Kasper Weibel Nielsen-Refs, Thomas Lockney, Jens Krämer
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in all
+# copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+# SOFTWARE.
+
+require 'active_support'
+require 'active_record'
+require 'set'
+require 'enumerator'
+require 'ferret'
+
+require 'ferret_find_methods'
+require 'remote_functions'
+require 'blank_slate'
+require 'bulk_indexer'
+require 'ferret_extensions'
+require 'act_methods'
+require 'search_results'
+require 'class_methods'
+require 'ferret_result'
+require 'instance_methods'
+require 'without_ar'
+
+require 'multi_index'
+require 'remote_multi_index'
+require 'more_like_this'
+
+require 'index'
+require 'local_index'
+require 'remote_index'
+
+require 'ferret_server'
+
+require 'rdig_adapter'
+
+# The Rails ActiveRecord Ferret Mixin.
+#
+# This mixin adds full text search capabilities to any Rails model.
+#
+# The current version emerged from on the original acts_as_ferret plugin done by
+# Kasper Weibel and a modified version done by Thomas Lockney, which both can be
+# found on the Ferret Wiki: http://ferret.davebalmain.com/trac/wiki/FerretOnRails.
+#
+# basic usage:
+# include the following in your model class (specifiying the fields you want to get indexed):
+# acts_as_ferret :fields => [ :title, :description ]
+#
+# now you can use ModelClass.find_with_ferret(query) to find instances of your model
+# whose indexed fields match a given query. All query terms are required by default, but
+# explicit OR queries are possible. This differs from the ferret default, but imho is the more
+# often needed/expected behaviour (more query terms result in less results).
+#
+# Released under the MIT license.
+#
+# Authors:
+# Kasper Weibel Nielsen-Refs (original author)
+# Jens Kraemer <jk@jkraemer.net> (active maintainer since 2006)
+#
+#
+# == Global properties
+#
+# raise_drb_errors:: Set this to true if you want aaf to raise Exceptions
+# in case the DRb server cannot be reached (in other word - behave like
+# versions up to 0.4.3). Defaults to false so DRb exceptions
+# are logged but not raised. Be sure to set up some
+# monitoring so you still detect when your DRb server died for
+# whatever reason.
+#
+# remote:: Set this to false to force acts_as_ferret into local (non-DRb) mode even if
+# config/ferret_server.yml contains a section for the current RAILS_ENV
+# Usually you won't need to touch this option - just configure DRb for
+# production mode in ferret_server.yml.
+#
+module ActsAsFerret
+
+ class ActsAsFerretError < StandardError; end
+ class IndexNotDefined < ActsAsFerretError; end
+ class IndexAlreadyDefined < ActsAsFerretError; end
+
+ # global Hash containing all multi indexes created by all classes using the plugin
+ # key is the concatenation of alphabetically sorted names of the classes the
+ # searcher searches.
+ @@multi_indexes = Hash.new
+ def self.multi_indexes; @@multi_indexes end
+
+ # global Hash containing the ferret indexes of all classes using the plugin
+ # key is the index name.
+ @@ferret_indexes = Hash.new
+ def self.ferret_indexes; @@ferret_indexes end
+
+ # mapping from class name to index name
+ @@index_using_classes = {}
+ def self.index_using_classes; @@index_using_classes end
+
+ @@logger = Logger.new "#{RAILS_ROOT}/log/acts_as_ferret.log"
+ @@logger.level = ActiveRecord::Base.logger.level rescue Logger::DEBUG
+ mattr_accessor :logger
+
+
+ # Default ferret configuration for index fields
+ DEFAULT_FIELD_OPTIONS = {
+ :store => :no,
+ :highlight => :yes,
+ :index => :yes,
+ :term_vector => :with_positions_offsets,
+ :boost => 1.0
+ }
+
+ @@raise_drb_errors = false
+ mattr_writer :raise_drb_errors
+ def self.raise_drb_errors?; @@raise_drb_errors end
+
+ @@remote = nil
+ mattr_accessor :remote
+ def self.remote?
+ if @@remote.nil?
+ if ENV["FERRET_USE_LOCAL_INDEX"] || ActsAsFerret::Remote::Server.running
+ @@remote = false
+ else
+ @@remote = ActsAsFerret::Remote::Config.new.uri rescue false
+ end
+ if @@remote
+ logger.info "Will use remote index server which should be available at #{@@remote}"
+ else
+ logger.info "Will use local index."
+ end
+ end
+ @@remote
+ end
+ remote?
+
+
+ # Globally declares an index.
+ #
+ # This method is also used to implicitly declare an index when you use the
+ # acts_as_ferret call in your class. Returns the created index instance.
+ #
+ # === Options are:
+ #
+ # +models+:: Hash of model classes and their per-class option hashes which should
+ # use this index. Any models mentioned here will automatically use
+ # the index, there is no need to explicitly call +acts_as_ferret+ in the
+ # model class definition.
+ def self.define_index(name, options = {})
+ name = name.to_sym
+ pending_classes = nil
+ if ferret_indexes.has_key?(name)
+ # seems models have been already loaded. remove that index for now,
+ # re-register any already loaded classes later on.
+ idx = get_index(name)
+ pending_classes = idx.index_definition[:registered_models]
+ pending_classes_configs = idx.registered_models_config
+ idx.close
+ ferret_indexes.delete(name)
+ end
+
+ index_definition = {
+ :index_dir => "#{ActsAsFerret::index_dir}/#{name}",
+ :name => name,
+ :single_index => false,
+ :reindex_batch_size => 1000,
+ :ferret => {},
+ :ferret_fields => {}, # list of indexed fields that will be filled later
+ :enabled => true, # used for class-wide disabling of Ferret
+ :mysql_fast_batches => true, # turn off to disable the faster, id based batching mechanism for MySQL
+ :raise_drb_errors => false # handle DRb connection errors by default
+ }.update( options )
+
+ index_definition[:registered_models] = []
+
+ # build ferret configuration
+ index_definition[:ferret] = {
+ :or_default => false,
+ :handle_parse_errors => true,
+ :default_field => nil, # will be set later on
+ #:max_clauses => 512,
+ #:analyzer => Ferret::Analysis::StandardAnalyzer.new,
+ # :wild_card_downcase => true
+ }.update( options[:ferret] || {} )
+
+ index_definition[:user_default_field] = index_definition[:ferret][:default_field]
+
+ unless remote?
+ ActsAsFerret::ensure_directory index_definition[:index_dir]
+ index_definition[:index_base_dir] = index_definition[:index_dir]
+ index_definition[:index_dir] = find_last_index_version(index_definition[:index_dir])
+ logger.debug "using index in #{index_definition[:index_dir]}"
+ end
+
+ # these properties are somewhat vital to the plugin and shouldn't
+ # be overwritten by the user:
+ index_definition[:ferret].update(
+ :key => :key,
+ :path => index_definition[:index_dir],
+ :auto_flush => true, # slower but more secure in terms of locking problems TODO disable when running in drb mode?
+ :create_if_missing => true
+ )
+
+ # field config
+ index_definition[:ferret_fields] = build_field_config( options[:fields] )
+ index_definition[:ferret_fields].update build_field_config( options[:additional_fields] )
+
+ idx = ferret_indexes[name] = create_index_instance( index_definition )
+
+ # re-register early loaded classes
+ if pending_classes
+ pending_classes.each { |clazz| idx.register_class clazz, { :force_re_registration => true }.merge(pending_classes_configs[clazz]) }
+ end
+
+ if models = options[:models]
+ models.each do |clazz, config|
+ clazz.send :include, ActsAsFerret::WithoutAR unless clazz.respond_to?(:acts_as_ferret)
+ clazz.acts_as_ferret config.merge(:index => name)
+ end
+ end
+
+ return idx
+ end
+
+ # called internally by the acts_as_ferret method
+ #
+ # returns the index
+ def self.register_class_with_index(clazz, index_name, options = {})
+ index_name = index_name.to_sym
+ @@index_using_classes[clazz.name] = index_name
+ unless index = ferret_indexes[index_name]
+ # index definition on the fly
+ # default to all attributes of this class
+ options[:fields] ||= clazz.new.attributes.keys.map { |k| k.to_sym }
+ index = define_index index_name, options
+ end
+ index.register_class(clazz, options)
+ return index
+ end
+
+ def self.load_config
+ # using require_dependency to make the reloading in dev mode work.
+ require_dependency "#{RAILS_ROOT}/config/aaf.rb"
+ ActsAsFerret::logger.info "loaded configuration file aaf.rb"
+ rescue LoadError
+ ensure
+ @aaf_config_loaded = true
+ end
+
+ # returns the index with the given name.
+ def self.get_index(name)
+ name = name.to_sym rescue nil
+ unless ferret_indexes.has_key?(name)
+ if @aaf_config_loaded
+ raise IndexNotDefined.new(name.to_s)
+ else
+ load_config and return get_index name
+ end
+ end
+ ferret_indexes[name]
+ end
+
+ # count hits for a query
+ def self.total_hits(query, models_or_index_name, options = {})
+ options = add_models_to_options_if_necessary options, models_or_index_name
+ find_index(models_or_index_name).total_hits query, options
+ end
+
+ # find ids of records
+ def self.find_ids(query, models_or_index_name, options = {}, &block)
+ options = add_models_to_options_if_necessary options, models_or_index_name
+ find_index(models_or_index_name).find_ids query, options, &block
+ end
+
+ # returns an index instance suitable for searching/updating the named index. Will
+ # return a read only MultiIndex when multiple model classes are given that do not
+ # share the same physical index.
+ def self.find_index(models_or_index_name)
+ case models_or_index_name
+ when Symbol
+ get_index models_or_index_name
+ when String
+ get_index models_or_index_name.to_sym
+ else
+ get_index_for models_or_index_name
+ end
+ end
+
+ # models_or_index_name may be an index name as declared in config/aaf.rb,
+ # a single class or an array of classes to limit search to these classes.
+ def self.find(query, models_or_index_name, options = {}, ar_options = {})
+ models = case models_or_index_name
+ when Array
+ models_or_index_name
+ when Class
+ [ models_or_index_name ]
+ else
+ nil
+ end
+ index = find_index(models_or_index_name)
+ multi = (MultiIndexBase === index or index.shared?)
+ unless options[:per_page]
+ options[:limit] ||= ar_options.delete :limit
+ options[:offset] ||= ar_options.delete :offset
+ end
+ if options[:limit] || options[:per_page]
+ # need pagination
+ options[:page] = if options[:per_page]
+ options[:page] ? options[:page].to_i : 1
+ else
+ nil
+ end
+ limit = options[:limit] || options[:per_page]
+ offset = options[:offset] || (options[:page] ? (options[:page] - 1) * limit : 0)
+ options.delete :offset
+ options[:limit] = :all
+
+ if multi or ((ar_options[:conditions] || ar_options[:order]) && options[:sort])
+ # do pagination as the last step after everything has been fetched
+ options[:late_pagination] = { :limit => limit, :offset => offset }
+ elsif ar_options[:conditions] or ar_options[:order]
+ # late limiting in AR call
+ unless limit == :all
+ ar_options[:limit] = limit
+ ar_options[:offset] = offset
+ end
+ else
+ options[:limit] = limit
+ options[:offset] = offset
+ end
+ end
+ ActsAsFerret::logger.debug "options: #{options.inspect}\nar_options: #{ar_options.inspect}"
+ total_hits, result = index.find_records query, options.merge(:models => models), ar_options
+ ActsAsFerret::logger.debug "Query: #{query}\ntotal hits: #{total_hits}, results delivered: #{result.size}"
+ SearchResults.new(result, total_hits, options[:page], options[:per_page])
+ end
+
+ def self.filter_include_list_for_model(model, include_options)
+ filtered_include_options = []
+ include_options = Array(include_options)
+ include_options.each do |include_option|
+ filtered_include_options << include_option if model.reflections.has_key?(include_option.is_a?(Hash) ? include_option.keys[0].to_sym : include_option.to_sym)
+ end
+ return filtered_include_options
+ end
+
+ # returns the index used by the given class.
+ #
+ # If multiple classes are given, either the single index shared by these
+ # classes, or a multi index (to be used for search only) across the indexes
+ # of all models, is returned.
+ def self.get_index_for(*classes)
+ classes.flatten!
+ raise ArgumentError.new("no class specified") unless classes.any?
+ classes.map!(&:constantize) unless Class === classes.first
+ logger.debug "index_for #{classes.inspect}"
+ index = if classes.size > 1
+ indexes = classes.map { |c| get_index_for c }.uniq
+ indexes.size > 1 ? multi_index(indexes) : indexes.first
+ else
+ clazz = classes.first
+ clazz = clazz.superclass while clazz && !@@index_using_classes.has_key?(clazz.name)
+ get_index @@index_using_classes[clazz.name]
+ end
+ raise IndexNotDefined.new("no index found for class: #{classes.map(&:name).join(',')}") if index.nil?
+ return index
+ end
+
+
+ # creates a new Index instance.
+ def self.create_index_instance(definition)
+ (remote? ? RemoteIndex : LocalIndex).new(definition)
+ end
+
+ def self.rebuild_index(name)
+ get_index(name).rebuild_index
+ end
+
+ def self.change_index_dir(name, new_dir)
+ get_index(name).change_index_dir new_dir
+ end
+
+ # find the most recent version of an index
+ def self.find_last_index_version(basedir)
+ # check for versioned index
+ versions = Dir.entries(basedir).select do |f|
+ dir = File.join(basedir, f)
+ File.directory?(dir) && File.file?(File.join(dir, 'segments')) && f =~ /^\d+(_\d+)?$/
+ end
+ if versions.any?
+ # select latest version
+ versions.sort!
+ File.join basedir, versions.last
+ else
+ basedir
+ end
+ end
+
+ # returns a MultiIndex instance operating on a MultiReader
+ def self.multi_index(indexes)
+ index_names = indexes.dup
+ index_names = index_names.map(&:to_s) if Symbol === index_names.first
+ if String === index_names.first
+ indexes = index_names.map{ |name| get_index name }
+ else
+ index_names = index_names.map{ |i| i.index_name.to_s }
+ end
+ key = index_names.sort.join(",")
+ ActsAsFerret::multi_indexes[key] ||= (remote? ? ActsAsFerret::RemoteMultiIndex : ActsAsFerret::MultiIndex).new(indexes)
+ end
+
+ # check for per-model conditions and return these if provided
+ def self.conditions_for_model(model, conditions = {})
+ if Hash === conditions
+ key = model.name.underscore.to_sym
+ conditions = conditions[key]
+ end
+ return conditions
+ end
+
+ # retrieves search result records from a data structure like this:
+ # { 'Model1' => { '1' => [ rank, score ], '2' => [ rank, score ] }
+ #
+ # TODO: in case of STI AR will filter out hits from other
+ # classes for us, but this
+ # will lead to less results retrieved --> scoping of ferret query
+ # to self.class is still needed.
+ # from the ferret ML (thanks Curtis Hatter)
+ # > I created a method in my base STI class so I can scope my query. For scoping
+ # > I used something like the following line:
+ # >
+ # > query << " role:#{self.class.eql?(Contents) '*' : self.class}"
+ # >
+ # > Though you could make it more generic by simply asking
+ # > "self.descends_from_active_record?" which is how rails decides if it should
+ # > scope your "find" query for STI models. You can check out "base.rb" in
+ # > activerecord to see that.
+ # but maybe better do the scoping in find_ids_with_ferret...
+ def self.retrieve_records(id_arrays, find_options = {})
+ result = []
+ # get objects for each model
+ id_arrays.each do |model, id_array|
+ next if id_array.empty?
+ model_class = model.constantize
+
+ # merge conditions
+ conditions = conditions_for_model model_class, find_options[:conditions]
+ conditions = combine_conditions([ "#{model_class.table_name}.#{model_class.primary_key} in (?)",
+ id_array.keys ],
+ conditions)
+
+ # check for include association that might only exist on some models in case of multi_search
+ filtered_include_options = nil
+ if include_options = find_options[:include]
+ filtered_include_options = filter_include_list_for_model(model_class, include_options)
+ end
+
+ # fetch
+ tmp_result = model_class.find(:all, find_options.merge(:conditions => conditions,
+ :include => filtered_include_options))
+
+ # set scores and rank
+ tmp_result.each do |record|
+ record.ferret_rank, record.ferret_score = id_array[record.id.to_s]
+ end
+ # merge with result array
+ result += tmp_result
+ end
+
+ # order results as they were found by ferret, unless an AR :order
+ # option was given
+ result.sort! { |a, b| a.ferret_rank <=> b.ferret_rank } unless find_options[:order]
+ return result
+ end
+
+ # combine our conditions with those given by user, if any
+ def self.combine_conditions(conditions, additional_conditions = [])
+ returning conditions do
+ if additional_conditions && additional_conditions.any?
+ cust_opts = (Array === additional_conditions) ? additional_conditions.dup : [ additional_conditions ]
+ logger.debug "cust_opts: #{cust_opts.inspect}"
+ conditions.first << " and " << cust_opts.shift
+ conditions.concat(cust_opts)
+ end
+ end
+ end
+
+ def self.build_field_config(fields)
+ field_config = {}
+ case fields
+ when Array
+ fields.each { |name| field_config[name] = field_config_for name }
+ when Hash
+ fields.each { |name, options| field_config[name] = field_config_for name, options }
+ else raise InvalidArgumentError.new(":fields option must be Hash or Array")
+ end if fields
+ return field_config
+ end
+
+ def self.ensure_directory(dir)
+ FileUtils.mkdir_p dir unless (File.directory?(dir) || File.symlink?(dir))
+ end
+
+
+ # make sure the default index base dir exists. by default, all indexes are created
+ # under RAILS_ROOT/index/RAILS_ENV
+ def self.init_index_basedir
+ index_base = "#{RAILS_ROOT}/index"
+ @@index_dir = "#{index_base}/#{RAILS_ENV}"
+ end
+
+ mattr_accessor :index_dir
+ init_index_basedir
+
+ def self.append_features(base)
+ super
+ base.extend(ClassMethods)
+ end
+
+ # builds a FieldInfos instance for creation of an index
+ def self.field_infos(index_definition)
+ # default attributes for fields
+ fi = Ferret::Index::FieldInfos.new(:store => :no,
+ :index => :yes,
+ :term_vector => :no,
+ :boost => 1.0)
+ # unique key composed of classname and id
+ fi.add_field(:key, :store => :no, :index => :untokenized)
+ # primary key
+ fi.add_field(:id, :store => :yes, :index => :untokenized)
+ # class_name
+ fi.add_field(:class_name, :store => :yes, :index => :untokenized)
+
+ # other fields
+ index_definition[:ferret_fields].each_pair do |field, options|
+ options = options.dup
+ options.delete :via
+ options.delete :boost if options[:boost].is_a?(Symbol) # dynamic boost
+ fi.add_field(field, options)
+ end
+ return fi
+ end
+
+ def self.close_multi_indexes
+ # close combined index readers, just in case
+ # this seems to fix a strange test failure that seems to relate to a
+ # multi_index looking at an old version of the content_base index.
+ multi_indexes.each_pair do |key, index|
+ # puts "#{key} -- #{self.name}"
+ # TODO only close those where necessary (watch inheritance, where
+ # self.name is base class of a class where key is made from)
+ index.close #if key =~ /#{self.name}/
+ end
+ multi_indexes.clear
+ end
+
+ protected
+
+ def self.add_models_to_options_if_necessary(options, models_or_index_name)
+ return options if String === models_or_index_name or Symbol === models_or_index_name
+ options.merge(:models => models_or_index_name)
+ end
+
+ def self.field_config_for(fieldname, options = {})
+ config = DEFAULT_FIELD_OPTIONS.merge options
+ config[:via] ||= fieldname
+ config[:term_vector] = :no if config[:index] == :no
+ return config
+ end
+
+end
+
+# include acts_as_ferret method into ActiveRecord::Base
+ActiveRecord::Base.extend ActsAsFerret::ActMethods
+
diff --git a/src/server/vendor/plugins/acts_as_ferret/lib/ar_mysql_auto_reconnect_patch.rb b/src/server/vendor/plugins/acts_as_ferret/lib/ar_mysql_auto_reconnect_patch.rb
new file mode 100644
index 0000000..9f5de4a
--- /dev/null
+++ b/src/server/vendor/plugins/acts_as_ferret/lib/ar_mysql_auto_reconnect_patch.rb
@@ -0,0 +1,41 @@
+# Source: http://pastie.caboo.se/154842
+#
+# in /etc/my.cnf on the MySQL server, you can set the interactive-timeout parameter,
+# for example, 12 hours = 28800 sec
+# interactive-timeout=28800
+
+# in ActiveRecord, setting the verification_timeout to something less than
+# the interactive-timeout parameter; 14400 sec = 6 hours
+ActiveRecord::Base.verification_timeout = 14400
+ActiveRecord::Base.establish_connection
+
+# Below is a monkey patch for keeping ActiveRecord connections alive.
+# http://www.sparecycles.org/2007/7/2/saying-goodbye-to-lost-connections-in-rails
+
+module ActiveRecord
+ module ConnectionAdapters
+ class MysqlAdapter
+ def execute(sql, name = nil) #:nodoc:
+ reconnect_lost_connections = true
+ begin
+ log(sql, name) { @connection.query(sql) }
+ rescue ActiveRecord::StatementInvalid => exception
+ if reconnect_lost_connections and exception.message =~ /(Lost connection to MySQL server during query
+|MySQL server has gone away)/
+ reconnect_lost_connections = false
+ reconnect!
+ retry
+ elsif exception.message.split(":").first =~ /Packets out of order/
+ raise ActiveRecord::StatementInvalid, "'Packets out of order' error was received from the database.
+ Please update your mysql bindings (gem install mysql) and read http://dev.mysql.com/doc/mysql/en/password-hash
+ing.html for more information. If you're on Windows, use the Instant Rails installer to get the updated mysql
+bindings."
+ else
+ raise
+ end
+ end
+ end
+ end
+ end
+end
+
diff --git a/src/server/vendor/plugins/acts_as_ferret/lib/blank_slate.rb b/src/server/vendor/plugins/acts_as_ferret/lib/blank_slate.rb
new file mode 100644
index 0000000..3c305c0
--- /dev/null
+++ b/src/server/vendor/plugins/acts_as_ferret/lib/blank_slate.rb
@@ -0,0 +1,53 @@
+if defined?(BlankSlate)
+ # Rails 2.x has it already
+ module ActsAsFerret
+ class BlankSlate < ::BlankSlate
+ end
+ end
+else
+ module ActsAsFerret
+ # 'backported' for Rails pre 2.0
+ #
+ #--
+ # Copyright 2004, 2006 by Jim Weirich (jim@weirichhouse.org).
+ # All rights reserved.
+
+ # Permission is granted for use, copying, modification, distribution,
+ # and distribution of modified versions of this work as long as the
+ # above copyright notice is included.
+ #++
+
+ ######################################################################
+ # BlankSlate provides an abstract base class with no predefined
+ # methods (except for <tt>\_\_send__</tt> and <tt>\_\_id__</tt>).
+ # BlankSlate is useful as a base class when writing classes that
+ # depend upon <tt>method_missing</tt> (e.g. dynamic proxies).
+ #
+ class BlankSlate
+ class << self
+ # Hide the method named +name+ in the BlankSlate class. Don't
+ # hide +instance_eval+ or any method beginning with "__".
+ def hide(name)
+ if instance_methods.include?(name.to_s) and name !~ /^(__|instance_eval|methods)/
+ @hidden_methods ||= {}
+ @hidden_methods[name.to_sym] = instance_method(name)
+ undef_method name
+ end
+ end
+
+ # Redefine a previously hidden method so that it may be called on a blank
+ # slate object.
+ #
+ # no-op here since we don't hide the methods we reveal where this is
+ # used in this implementation
+ def reveal(name)
+ end
+ end
+
+ instance_methods.each { |m| hide(m) }
+
+ end
+ end
+
+end
+
diff --git a/src/server/vendor/plugins/acts_as_ferret/lib/bulk_indexer.rb b/src/server/vendor/plugins/acts_as_ferret/lib/bulk_indexer.rb
new file mode 100644
index 0000000..546f894
--- /dev/null
+++ b/src/server/vendor/plugins/acts_as_ferret/lib/bulk_indexer.rb
@@ -0,0 +1,38 @@
+module ActsAsFerret
+ class BulkIndexer
+ def initialize(args = {})
+ @batch_size = args[:batch_size] || 1000
+ @logger = args[:logger]
+ @model = args[:model]
+ @work_done = 0
+ @index = args[:index]
+ if args[:reindex]
+ @reindex = true
+ @model_count = @model.count.to_f
+ else
+ @model_count = args[:total]
+ end
+ end
+
+ def index_records(records, offset)
+ batch_time = measure_time {
+ docs = []
+ records.each { |rec| docs << [rec.to_doc, rec.ferret_analyzer] if rec.ferret_enabled?(true) }
+ @index.update_batch(docs)
+ # records.each { |rec| @index.add_document(rec.to_doc, rec.ferret_analyzer) if rec.ferret_enabled?(true) }
+ }.to_f
+ @work_done = offset.to_f / @model_count * 100.0 if @model_count > 0
+ remaining_time = ( batch_time / @batch_size ) * ( @model_count - offset + @batch_size )
+ @logger.info "#{@reindex ? 're' : 'bulk '}index model #{@model.name} : #{'%.2f' % @work_done}% complete : #{'%.2f' % remaining_time} secs to finish"
+
+ end
+
+ def measure_time
+ t1 = Time.now
+ yield
+ Time.now - t1
+ end
+
+ end
+
+end
diff --git a/src/server/vendor/plugins/acts_as_ferret/lib/class_methods.rb b/src/server/vendor/plugins/acts_as_ferret/lib/class_methods.rb
new file mode 100644
index 0000000..6b702bd
--- /dev/null
+++ b/src/server/vendor/plugins/acts_as_ferret/lib/class_methods.rb
@@ -0,0 +1,270 @@
+module ActsAsFerret
+
+ module ClassMethods
+
+ # Disables ferret index updates for this model. When a block is given,
+ # Ferret will be re-enabled again after executing the block.
+ def disable_ferret
+ aaf_configuration[:enabled] = false
+ if block_given?
+ yield
+ enable_ferret
+ end
+ end
+
+ def enable_ferret
+ aaf_configuration[:enabled] = true
+ end
+
+ def ferret_enabled?
+ aaf_configuration[:enabled]
+ end
+
+ # rebuild the index from all data stored for this model, and any other
+ # model classes associated with the same index.
+ # This is called automatically when no index exists yet.
+ #
+ def rebuild_index
+ aaf_index.rebuild_index
+ end
+
+ # re-index a number records specified by the given ids. Use for large
+ # indexing jobs i.e. after modifying a lot of records with Ferret disabled.
+ # Please note that the state of Ferret (enabled or disabled at class or
+ # record level) is not checked by this method, so if you need to do so
+ # (e.g. because of a custom ferret_enabled? implementation), you have to do
+ # so yourself.
+ def bulk_index(*ids)
+ options = Hash === ids.last ? ids.pop : {}
+ ids = ids.first if ids.size == 1 && ids.first.is_a?(Enumerable)
+ aaf_index.bulk_index(self.name, ids, options)
+ end
+
+ # true if our db and table appear to be suitable for the mysql fast batch
+ # hack (see
+ # http://weblog.jamisbuck.org/2007/4/6/faking-cursors-in-activerecord)
+ def use_fast_batches?
+ if connection.class.name =~ /Mysql/ && primary_key == 'id' && aaf_configuration[:mysql_fast_batches]
+ logger.info "using mysql specific batched find :all. Turn off with :mysql_fast_batches => false if you encounter problems (i.e. because of non-integer UUIDs in the id column)"
+ true
+ end
+ end
+
+ # Returns all records modified or created after the specified time.
+ # Used by the rake rebuild task to find models that need to be updated in
+ # the index after the rebuild finished because they changed while the
+ # rebuild was running.
+ # Override if your models don't stick to the created_at/updated_at
+ # convention.
+ def records_modified_since(time)
+ condition = []
+ %w(updated_at created_at).each do |col|
+ condition << "#{col} >= ?" if column_names.include? col
+ end
+ if condition.empty?
+ logger.warn "#{self.name}: Override records_modified_since(time) to keep the index up to date with records changed during rebuild."
+ []
+ else
+ find :all, :conditions => [ condition.join(' AND '), *([time]*condition.size) ]
+ end
+ end
+
+ # runs across all records yielding those to be indexed when the index is rebuilt
+ def records_for_rebuild(batch_size = 1000)
+ transaction do
+ if use_fast_batches?
+ offset = 0
+ while (rows = find :all, :conditions => [ "#{table_name}.id > ?", offset ], :limit => batch_size).any?
+ offset = rows.last.id
+ yield rows, offset
+ end
+ else
+ order = "#{primary_key} ASC" # fixes #212
+ 0.step(self.count, batch_size) do |offset|
+ yield find( :all, :limit => batch_size, :offset => offset, :order => order ), offset
+ end
+ end
+ end
+ end
+
+ # yields the records with the given ids, in batches of batch_size
+ def records_for_bulk_index(ids, batch_size = 1000)
+ transaction do
+ offset = 0
+ ids.each_slice(batch_size) do |id_slice|
+ records = find( :all, :conditions => ["id in (?)", id_slice] )
+ #yield records, offset
+ yield find( :all, :conditions => ["id in (?)", id_slice] ), offset
+ offset += batch_size
+ end
+ end
+ end
+
+ # Retrieve the index instance for this model class. This can either be a
+ # LocalIndex, or a RemoteIndex instance.
+ #
+ def aaf_index
+ @index ||= ActsAsFerret::get_index(aaf_configuration[:name])
+ end
+
+ # Finds instances by searching the Ferret index. Terms are ANDed by default, use
+ # OR between terms for ORed queries. Or specify +:or_default => true+ in the
+ # +:ferret+ options hash of acts_as_ferret.
+ #
+ # You may either use the +offset+ and +limit+ options to implement your own
+ # pagination logic, or use the +page+ and +per_page+ options to use the
+ # built in pagination support which is compatible with will_paginate's view
+ # helpers. If +page+ and +per_page+ are given, +offset+ and +limit+ will be
+ # ignored.
+ #
+ # == options:
+ # page:: page of search results to retrieve
+ # per_page:: number of search results that are displayed per page
+ # offset:: first hit to retrieve (useful for paging)
+ # limit:: number of hits to retrieve, or :all to retrieve
+ # all results
+ # lazy:: Array of field names whose contents should be read directly
+ # from the index. Those fields have to be marked
+ # +:store => :yes+ in their field options. Give true to get all
+ # stored fields. Note that if you have a shared index, you have
+ # to explicitly state the fields you want to fetch, true won't
+ # work here)
+ #
+ # +find_options+ is a hash passed on to active_record's find when
+ # retrieving the data from db, useful to i.e. prefetch relationships with
+ # :include or to specify additional filter criteria with :conditions.
+ #
+ # This method returns a +SearchResults+ instance, which really is an Array that has
+ # been decorated with a total_hits attribute holding the total number of hits.
+ # Additionally, SearchResults is compatible with the pagination helper
+ # methods of the will_paginate plugin.
+ #
+ # Please keep in mind that the number of results delivered might be less than
+ # +limit+ if you specify any active record conditions that further limit
+ # the result. Use +limit+ and +offset+ as AR find_options instead.
+ # +page+ and +per_page+ are supposed to work regardless of any
+ # +conitions+ present in +find_options+.
+ def find_with_ferret(q, options = {}, find_options = {})
+ if respond_to?(:scope) && scope(:find, :conditions)
+ if find_options[:conditions]
+ find_options[:conditions] = "(#{find_options[:conditions]}) AND (#{scope(:find, :conditions)})"
+ else
+ find_options[:conditions] = scope(:find, :conditions)
+ end
+ end
+ return ActsAsFerret::find q, self, options, find_options
+ end
+
+
+ # Returns the total number of hits for the given query
+ #
+ # Note that since we don't query the database here, this method won't deliver
+ # the expected results when used on an AR association.
+ #
+ def total_hits(q, options={})
+ aaf_index.total_hits(q, options)
+ end
+
+ # Finds instance model name, ids and scores by contents.
+ # Useful e.g. if you want to search across models or do not want to fetch
+ # all result records (yet).
+ #
+ # Options are the same as for find_with_ferret
+ #
+ # A block can be given too, it will be executed with every result:
+ # find_ids_with_ferret(q, options) do |model, id, score|
+ # id_array << id
+ # scores_by_id[id] = score
+ # end
+ # NOTE: in case a block is given, only the total_hits value will be returned
+ # instead of the [total_hits, results] array!
+ #
+ def find_ids_with_ferret(q, options = {}, &block)
+ aaf_index.find_ids(q, options, &block)
+ end
+
+
+ protected
+
+# def find_records_lazy_or_not(q, options = {}, find_options = {})
+# if options[:lazy]
+# logger.warn "find_options #{find_options} are ignored because :lazy => true" unless find_options.empty?
+# lazy_find_by_contents q, options
+# else
+# ar_find_by_contents q, options, find_options
+# end
+# end
+#
+# def ar_find_by_contents(q, options = {}, find_options = {})
+# result_ids = {}
+# total_hits = find_ids_with_ferret(q, options) do |model, id, score, data|
+# # stores ids, index and score of each hit for later ordering of
+# # results
+# result_ids[id] = [ result_ids.size + 1, score ]
+# end
+#
+# result = ActsAsFerret::retrieve_records( { self.name => result_ids }, find_options )
+#
+# # count total_hits via sql when using conditions or when we're called
+# # from an ActiveRecord association.
+# if find_options[:conditions] or caller.find{ |call| call =~ %r{active_record/associations} }
+# # chances are the ferret result count is not our total_hits value, so
+# # we correct this here.
+# if options[:limit] != :all || options[:page] || options[:offset] || find_options[:limit] || find_options[:offset]
+# # our ferret result has been limited, so we need to re-run that
+# # search to get the full result set from ferret.
+# result_ids = {}
+# find_ids_with_ferret(q, options.update(:limit => :all, :offset => 0)) do |model, id, score, data|
+# result_ids[id] = [ result_ids.size + 1, score ]
+# end
+# # Now ask the database for the total size of the final result set.
+# total_hits = count_records( { self.name => result_ids }, find_options )
+# else
+# # what we got from the database is our full result set, so take
+# # it's size
+# total_hits = result.length
+# end
+# end
+#
+# [ total_hits, result ]
+# end
+#
+# def lazy_find_by_contents(q, options = {})
+# logger.debug "lazy_find_by_contents: #{q}"
+# result = []
+# rank = 0
+# total_hits = find_ids_with_ferret(q, options) do |model, id, score, data|
+# logger.debug "model: #{model}, id: #{id}, data: #{data}"
+# result << FerretResult.new(model, id, score, rank += 1, data)
+# end
+# [ total_hits, result ]
+# end
+
+
+ def model_find(model, id, find_options = {})
+ model.constantize.find(id, find_options)
+ end
+
+
+# def count_records(id_arrays, find_options = {})
+# count_options = find_options.dup
+# count_options.delete :limit
+# count_options.delete :offset
+# count = 0
+# id_arrays.each do |model, id_array|
+# next if id_array.empty?
+# model = model.constantize
+# # merge conditions
+# conditions = ActsAsFerret::combine_conditions([ "#{model.table_name}.#{model.primary_key} in (?)", id_array.keys ],
+# find_options[:conditions])
+# opts = find_options.merge :conditions => conditions
+# opts.delete :limit; opts.delete :offset
+# count += model.count opts
+# end
+# count
+# end
+
+ end
+
+end
+
diff --git a/src/server/vendor/plugins/acts_as_ferret/lib/ferret_extensions.rb b/src/server/vendor/plugins/acts_as_ferret/lib/ferret_extensions.rb
new file mode 100644
index 0000000..8212753
--- /dev/null
+++ b/src/server/vendor/plugins/acts_as_ferret/lib/ferret_extensions.rb
@@ -0,0 +1,188 @@
+module Ferret
+
+ module Analysis
+
+ # = PerFieldAnalyzer
+ #
+ # This PerFieldAnalyzer is a workaround to a memory leak in
+ # ferret 0.11.4. It does basically do the same as the original
+ # Ferret::Analysis::PerFieldAnalyzer, but without the leak :)
+ #
+ # http://ferret.davebalmain.com/api/classes/Ferret/Analysis/PerFieldAnalyzer.html
+ #
+ # Thanks to Ben from omdb.org for tracking this down and creating this
+ # workaround.
+ # You can read more about the issue there:
+ # http://blog.omdb-beta.org/2007/7/29/tracking-down-a-memory-leak-in-ferret-0-11-4
+ class PerFieldAnalyzer < ::Ferret::Analysis::Analyzer
+ def initialize( default_analyzer = StandardAnalyzer.new )
+ @analyzers = {}
+ @default_analyzer = default_analyzer
+ end
+
+ def add_field( field, analyzer )
+ @analyzers[field] = analyzer
+ end
+ alias []= add_field
+
+ def token_stream(field, string)
+ @analyzers.has_key?(field) ? @analyzers[field].token_stream(field, string) :
+ @default_analyzer.token_stream(field, string)
+ end
+ end
+ end
+
+ class Index::Index
+ attr_accessor :batch_size, :logger
+
+ def index_models(models)
+ models.each { |model| index_model model }
+ flush
+ optimize
+ close
+ ActsAsFerret::close_multi_indexes
+ end
+
+ def index_model(model)
+ bulk_indexer = ActsAsFerret::BulkIndexer.new(:batch_size => @batch_size, :logger => logger,
+ :model => model, :index => self, :reindex => true)
+ logger.info "reindexing model #{model.name}"
+
+ model.records_for_rebuild(@batch_size) do |records, offset|
+ bulk_indexer.index_records(records, offset)
+ end
+ end
+
+ def bulk_index(model, ids, options = {})
+ options.reverse_merge! :optimize => true
+ orig_flush = @auto_flush
+ @auto_flush = false
+ bulk_indexer = ActsAsFerret::BulkIndexer.new(:batch_size => @batch_size, :logger => logger,
+ :model => model, :index => self, :total => ids.size)
+ model.records_for_bulk_index(ids, @batch_size) do |records, offset|
+ logger.debug "#{model} bulk indexing #{records.size} at #{offset}"
+ bulk_indexer.index_records(records, offset)
+ end
+ logger.info 'finishing bulk index...'
+ flush
+ if options[:optimize]
+ logger.info 'optimizing...'
+ optimize
+ end
+ @auto_flush = orig_flush
+ end
+
+
+ # bulk-inserts a number of ferret documents.
+ # The argument has to be an array of two-element arrays each holding the document data and the analyzer to
+ # use for this document (which may be nil).
+ def update_batch(document_analyzer_pairs)
+ ids = document_analyzer_pairs.collect {|da| da.first[@id_field] }
+ @dir.synchrolock do
+ batch_delete(ids)
+ ensure_writer_open()
+ document_analyzer_pairs.each do |doc, analyzer|
+ if analyzer
+ old_analyzer = @writer.analyzer
+ @writer.analyzer = analyzer
+ @writer.add_document(doc)
+ @writer.analyzer = old_analyzer
+ else
+ @writer.add_document(doc)
+ end
+ end
+ flush()
+ end
+ end
+
+ # If +docs+ is a Hash or an Array then a batch delete will be performed.
+ # If +docs+ is an Array then it will be considered an array of +id+'s. If
+ # it is a Hash, then its keys will be used instead as the Array of
+ # document +id+'s. If the +id+ is an Integers then it is considered a
+ # Ferret document number and the corresponding document will be deleted.
+ # If the +id+ is a String or a Symbol then the +id+ will be considered a
+ # term and the documents that contain that term in the +:id_field+ will
+ # be deleted.
+ #
+ # docs:: An Array of docs to be deleted, or a Hash (in which case the keys
+ # are used)
+ #
+ # ripped from Ferret trunk.
+ def batch_delete(docs)
+ docs = docs.keys if docs.is_a?(Hash)
+ raise ArgumentError, "must pass Array or Hash" unless docs.is_a? Array
+ ids = []
+ terms = []
+ docs.each do |doc|
+ case doc
+ when String then terms << doc
+ when Symbol then terms << doc.to_s
+ when Integer then ids << doc
+ else
+ raise ArgumentError, "Cannot delete for arg of type #{id.class}"
+ end
+ end
+ if ids.size > 0
+ ensure_reader_open
+ ids.each {|id| @reader.delete(id)}
+ end
+ if terms.size > 0
+ ensure_writer_open()
+ terms.each { |t| @writer.delete(@id_field, t) }
+ # TODO with Ferret trunk this would work:
+ # @writer.delete(@id_field, terms)
+ end
+ return self
+ end
+
+ # search for the first document with +arg+ in the +id+ field and return it's internal document number.
+ # The +id+ field is either :id or whatever you set
+ # :id_field parameter to when you create the Index object.
+ def doc_number(id)
+ @dir.synchronize do
+ ensure_reader_open()
+ term_doc_enum = @reader.term_docs_for(@id_field, id.to_s)
+ return term_doc_enum.next? ? term_doc_enum.doc : nil
+ end
+ end
+ end
+
+ # add marshalling support to SortFields
+ class Search::SortField
+ def _dump(depth)
+ to_s
+ end
+
+ def self._load(string)
+ case string
+ when /<DOC(_ID)?>!/ then Ferret::Search::SortField::DOC_ID_REV
+ when /<DOC(_ID)?>/ then Ferret::Search::SortField::DOC_ID
+ when '<SCORE>!' then Ferret::Search::SortField::SCORE_REV
+ when '<SCORE>' then Ferret::Search::SortField::SCORE
+ when /^(\w+):<(\w+)>(!)?$/ then new($1.to_sym, :type => $2.to_sym, :reverse => !$3.nil?)
+ else raise "invalid value: #{string}"
+ end
+ end
+ end
+
+ # add marshalling support to Sort
+ class Search::Sort
+ def _dump(depth)
+ to_s
+ end
+
+ def self._load(string)
+ # we exclude the last <DOC> sorting as it is appended by new anyway
+ if string =~ /^Sort\[(.*?)(<DOC>(!)?)?\]$/
+ sort_fields = $1.split(',').map do |value|
+ value.strip!
+ Ferret::Search::SortField._load value unless value.blank?
+ end
+ new sort_fields.compact
+ else
+ raise "invalid value: #{string}"
+ end
+ end
+ end
+
+end
diff --git a/src/server/vendor/plugins/acts_as_ferret/lib/ferret_find_methods.rb b/src/server/vendor/plugins/acts_as_ferret/lib/ferret_find_methods.rb
new file mode 100644
index 0000000..3b379bc
--- /dev/null
+++ b/src/server/vendor/plugins/acts_as_ferret/lib/ferret_find_methods.rb
@@ -0,0 +1,142 @@
+module ActsAsFerret
+ # Ferret search logic common to single-class indexes, shared indexes and
+ # multi indexes.
+ module FerretFindMethods
+
+ def find_records(q, options = {}, ar_options = {})
+ late_pagination = options.delete :late_pagination
+ total_hits, result = if options[:lazy]
+ logger.warn "find_options #{ar_options} are ignored because :lazy => true" unless ar_options.empty?
+ lazy_find q, options
+ else
+ ar_find q, options, ar_options
+ end
+ if late_pagination
+ limit = late_pagination[:limit]
+ offset = late_pagination[:offset] || 0
+ end_index = limit == :all ? -1 : limit+offset-1
+ # puts "late pagination: #{offset} : #{end_index}"
+ result = result[offset..end_index]
+ end
+ return [total_hits, result]
+ end
+
+ def lazy_find(q, options = {})
+ logger.debug "lazy_find: #{q}"
+ result = []
+ rank = 0
+ total_hits = find_ids(q, options) do |model, id, score, data|
+ logger.debug "model: #{model}, id: #{id}, data: #{data}"
+ result << FerretResult.new(model, id, score, rank += 1, data)
+ end
+ [ total_hits, result ]
+ end
+
+ def ar_find(q, options = {}, ar_options = {})
+ ferret_options = options.dup
+ if ar_options[:conditions] or ar_options[:order]
+ ferret_options[:limit] = :all
+ ferret_options.delete :offset
+ end
+ total_hits, id_arrays = find_id_model_arrays q, ferret_options
+ logger.debug "now retrieving records from AR with options: #{ar_options.inspect}"
+ result = ActsAsFerret::retrieve_records(id_arrays, ar_options)
+ logger.debug "#{result.size} results from AR: #{result.inspect}"
+
+ # count total_hits via sql when using conditions, multiple models, or when we're called
+ # from an ActiveRecord association.
+ if id_arrays.size > 1 or ar_options[:conditions]
+ # chances are the ferret result count is not our total_hits value, so
+ # we correct this here.
+ if options[:limit] != :all || options[:page] || options[:offset] || ar_options[:limit] || ar_options[:offset]
+ # our ferret result has been limited, so we need to re-run that
+ # search to get the full result set from ferret.
+ new_th, id_arrays = find_id_model_arrays( q, options.merge(:limit => :all, :offset => 0) )
+ # Now ask the database for the total size of the final result set.
+ total_hits = count_records( id_arrays, ar_options )
+ else
+ # what we got from the database is our full result set, so take
+ # it's size
+ total_hits = result.length
+ end
+ end
+ [ total_hits, result ]
+ end
+
+ def count_records(id_arrays, ar_options = {})
+ count_options = ar_options.dup
+ count_options.delete :limit
+ count_options.delete :offset
+ count_options.delete :order
+ count_options.delete :select
+ count = 0
+ id_arrays.each do |model, id_array|
+ next if id_array.empty?
+ model = model.constantize
+ # merge conditions
+ conditions = ActsAsFerret::conditions_for_model model, ar_options[:conditions]
+ count_options[:conditions] = ActsAsFerret::combine_conditions([ "#{model.table_name}.#{model.primary_key} in (?)", id_array.keys ], conditions)
+ count_options[:include] = ActsAsFerret::filter_include_list_for_model(model, ar_options[:include]) if ar_options[:include]
+ cnt = model.count count_options
+ if cnt.is_a?(ActiveSupport::OrderedHash) # fixes #227
+ count += cnt.size
+ else
+ count += cnt
+ end
+ end
+ count
+ end
+
+ def find_id_model_arrays(q, options)
+ id_arrays = {}
+ rank = 0
+ total_hits = find_ids(q, options) do |model, id, score, data|
+ id_arrays[model] ||= {}
+ id_arrays[model][id] = [ rank += 1, score ]
+ end
+ [total_hits, id_arrays]
+ end
+
+ # Queries the Ferret index to retrieve model class, id, score and the
+ # values of any fields stored in the index for each hit.
+ # If a block is given, these are yielded and the number of total hits is
+ # returned. Otherwise [total_hits, result_array] is returned.
+ def find_ids(query, options = {})
+
+ result = []
+ stored_fields = determine_stored_fields options
+
+ q = process_query(query, options)
+ q = scope_query_to_models q, options[:models] #if shared?
+ logger.debug "query: #{query}\n-->#{q}"
+ s = searcher
+ total_hits = s.search_each(q, options) do |hit, score|
+ doc = s[hit]
+ model = doc[:class_name]
+ # fetch stored fields if lazy loading
+ data = extract_stored_fields(doc, stored_fields)
+ if block_given?
+ yield model, doc[:id], score, data
+ else
+ result << { :model => model, :id => doc[:id], :score => score, :data => data }
+ end
+ end
+ #logger.debug "id_score_model array: #{result.inspect}"
+ return block_given? ? total_hits : [total_hits, result]
+ end
+
+ def scope_query_to_models(query, models)
+ return query if models.nil? or models == :all
+ models = [ models ] if Class === models
+ q = Ferret::Search::BooleanQuery.new
+ q.add_query(query, :must)
+ model_query = Ferret::Search::BooleanQuery.new
+ models.each do |model|
+ model_query.add_query(Ferret::Search::TermQuery.new(:class_name, model.name), :should)
+ end
+ q.add_query(model_query, :must)
+ return q
+ end
+
+ end
+end
diff --git a/src/server/vendor/plugins/acts_as_ferret/lib/ferret_result.rb b/src/server/vendor/plugins/acts_as_ferret/lib/ferret_result.rb
new file mode 100644
index 0000000..76ab421
--- /dev/null
+++ b/src/server/vendor/plugins/acts_as_ferret/lib/ferret_result.rb
@@ -0,0 +1,53 @@
+module ActsAsFerret
+
+ # mixed into the FerretResult and AR classes calling acts_as_ferret
+ module ResultAttributes
+ # holds the score this record had when it was found via
+ # acts_as_ferret
+ attr_accessor :ferret_score
+
+ attr_accessor :ferret_rank
+ end
+
+ class FerretResult < ActsAsFerret::BlankSlate
+ include ResultAttributes
+ attr_accessor :id
+ reveal :methods
+
+ def initialize(model, id, score, rank, data = {})
+ @model = model.constantize
+ @id = id
+ @ferret_score = score
+ @ferret_rank = rank
+ @data = data
+ @use_record = false
+ end
+
+ def inspect
+ "#<FerretResult wrapper for #{@model} with id #{@id}"
+ end
+
+ def method_missing(method, *args, &block)
+ if (@ar_record && @use_record) || !@data.has_key?(method)
+ to_record.send method, *args, &block
+ else
+ @data[method]
+ end
+ end
+
+ def respond_to?(name)
+ methods.include?(name.to_s) || @data.has_key?(name.to_sym) || to_record.respond_to?(name)
+ end
+
+ def to_record
+ unless @ar_record
+ @ar_record = @model.find(id)
+ @ar_record.ferret_rank = ferret_rank
+ @ar_record.ferret_score = ferret_score
+ # don't try to fetch attributes from RDig based records
+ @use_record = !@ar_record.class.included_modules.include?(ActsAsFerret::RdigAdapter)
+ end
+ @ar_record
+ end
+ end
+end
diff --git a/src/server/vendor/plugins/acts_as_ferret/lib/ferret_server.rb b/src/server/vendor/plugins/acts_as_ferret/lib/ferret_server.rb
new file mode 100644
index 0000000..23a12d8
--- /dev/null
+++ b/src/server/vendor/plugins/acts_as_ferret/lib/ferret_server.rb
@@ -0,0 +1,238 @@
+require 'drb'
+require 'thread'
+require 'yaml'
+require 'erb'
+
+################################################################################
+module ActsAsFerret
+ module Remote
+
+ ################################################################################
+ class Config
+
+ ################################################################################
+ DEFAULTS = {
+ 'host' => 'localhost',
+ 'port' => '9009',
+ 'cf' => "#{RAILS_ROOT}/config/ferret_server.yml",
+ 'pid_file' => "#{RAILS_ROOT}/log/ferret_server.pid",
+ 'log_file' => "#{RAILS_ROOT}/log/ferret_server.log",
+ 'log_level' => 'debug',
+ 'socket' => nil,
+ 'script' => nil
+ }
+
+ ################################################################################
+ # load the configuration file and apply default settings
+ def initialize (file=DEFAULTS['cf'])
+ @everything = YAML.load(ERB.new(IO.read(file)).result)
+ raise "malformed ferret server config" unless @everything.is_a?(Hash)
+ @config = DEFAULTS.merge(@everything[RAILS_ENV] || {})
+ if @everything[RAILS_ENV]
+ @config['uri'] = socket.nil? ? "druby://#{host}:#{port}" : "drbunix:#{socket}"
+ end
+ end
+
+ ################################################################################
+ # treat the keys of the config data as methods
+ def method_missing (name, *args)
+ @config.has_key?(name.to_s) ? @config[name.to_s] : super
+ end
+
+ end
+
+ #################################################################################
+ # This class acts as a drb server listening for indexing and
+ # search requests from models declared to 'acts_as_ferret :remote => true'
+ #
+ # Usage:
+ # - modify RAILS_ROOT/config/ferret_server.yml to suit your needs.
+ # - environments for which no section in the config file exists will use
+ # the index locally (good for unit tests/development mode)
+ # - run script/ferret_server to start the server:
+ # script/ferret_server -e production start
+ # - to stop the server run
+ # script/ferret_server -e production stop
+ #
+ class Server
+
+ #################################################################################
+ # FIXME include detection of OS and include the correct file
+ require 'unix_daemon'
+ include(ActsAsFerret::Remote::UnixDaemon)
+
+
+ ################################################################################
+ cattr_accessor :running
+
+ ################################################################################
+ def initialize
+ ActiveRecord::Base.allow_concurrency = true
+ require 'ar_mysql_auto_reconnect_patch'
+ @cfg = ActsAsFerret::Remote::Config.new
+ ActiveRecord::Base.logger = @logger = Logger.new(@cfg.log_file)
+ ActiveRecord::Base.logger.level = Logger.const_get(@cfg.log_level.upcase) rescue Logger::DEBUG
+ if @cfg.script
+ path = File.join(RAILS_ROOT, @cfg.script)
+ load path
+ @logger.info "loaded custom startup script from #{path}"
+ end
+ end
+
+ ################################################################################
+ # start the server as a daemon process
+ def start
+ raise "ferret_server not configured for #{RAILS_ENV}" unless (@cfg.uri rescue nil)
+ platform_daemon { run_drb_service }
+ end
+
+ ################################################################################
+ # run the server and block until it exits
+ def run
+ raise "ferret_server not configured for #{RAILS_ENV}" unless (@cfg.uri rescue nil)
+ run_drb_service
+ end
+
+ def run_drb_service
+ $stdout.puts("starting ferret server...")
+ self.class.running = true
+ DRb.start_service(@cfg.uri, self)
+ DRb.thread.join
+ rescue Exception => e
+ @logger.error(e.to_s)
+ raise
+ end
+
+ #################################################################################
+ # handles all incoming method calls, and sends them on to the correct local index
+ # instance.
+ #
+ # Calls are not queued, so this will block until the call returned.
+ #
+ def method_missing(name, *args)
+ @logger.debug "\#method_missing(#{name.inspect}, #{args.inspect})"
+
+
+ index_name = args.shift
+ index = if name.to_s =~ /^multi_(.+)/
+ name = $1
+ ActsAsFerret::multi_index(index_name)
+ else
+ ActsAsFerret::get_index(index_name)
+ end
+
+ if index.nil?
+ @logger.error "\#index with name #{index_name} not found in call to #{name} with args #{args.inspect}"
+ raise ActsAsFerret::IndexNotDefined.new(index_name)
+ end
+
+
+ # TODO find another way to implement the reconnection logic (maybe in
+ # local_index or class_methods)
+ # reconnect_when_needed(clazz) do
+
+ # using respond_to? here so we not have to catch NoMethodError
+ # which would silently catch those from deep inside the indexing
+ # code, too...
+
+ if index.respond_to?(name)
+ index.send name, *args
+ # TODO check where we need this:
+ #elsif clazz.respond_to?(name)
+ # @logger.debug "no luck, trying to call class method instead"
+ # clazz.send name, *args
+ else
+ raise NoMethodError.new("method #{name} not supported by DRb server")
+ end
+ rescue => e
+ @logger.error "ferret server error #{$!}\n#{$!.backtrace.join "\n"}"
+ raise e
+ end
+
+ def register_class(class_name)
+ @logger.debug "############ registerclass #{class_name}"
+ class_name.constantize
+ @logger.debug "index for class #{class_name}: #{ActsAsFerret::ferret_indexes[class_name.underscore.to_sym]}"
+
+ end
+
+ # make sure we have a versioned index in place, building one if necessary
+ def ensure_index_exists(index_name)
+ @logger.debug "DRb server: ensure_index_exists for index #{index_name}"
+ definition = ActsAsFerret::get_index(index_name).index_definition
+ dir = definition[:index_dir]
+ unless File.directory?(dir) && File.file?(File.join(dir, 'segments')) && dir =~ %r{/\d+(_\d+)?$}
+ rebuild_index(index_name)
+ end
+ end
+
+ # disconnects the db connection for the class specified by class_name
+ # used only in unit tests to check the automatic reconnection feature
+ def db_disconnect!(class_name)
+ with_class class_name do |clazz|
+ clazz.connection.disconnect!
+ end
+ end
+
+ # hides LocalIndex#rebuild_index to implement index versioning
+ def rebuild_index(index_name)
+ definition = ActsAsFerret::get_index(index_name).index_definition.dup
+ models = definition[:registered_models]
+ index = new_index_for(definition)
+ # TODO fix reconnection stuff
+ # reconnect_when_needed(clazz) do
+ # @logger.debug "DRb server: rebuild index for class(es) #{models.inspect} in #{index.options[:path]}"
+ index.index_models models
+ # end
+ new_version = File.join definition[:index_base_dir], Time.now.utc.strftime('%Y%m%d%H%M%S')
+ # create a unique directory name (needed for unit tests where
+ # multiple rebuilds per second may occur)
+ if File.exists?(new_version)
+ i = 0
+ i+=1 while File.exists?("#{new_version}_#{i}")
+ new_version << "_#{i}"
+ end
+
+ File.rename index.options[:path], new_version
+ ActsAsFerret::change_index_dir index_name, new_version
+ end
+
+
+ protected
+
+ def reconnect_when_needed(clazz)
+ retried = false
+ begin
+ yield
+ rescue ActiveRecord::StatementInvalid => e
+ if e.message =~ /MySQL server has gone away/
+ if retried
+ raise e
+ else
+ @logger.info "StatementInvalid caught, trying to reconnect..."
+ clazz.connection.reconnect!
+ retried = true
+ retry
+ end
+ else
+ @logger.error "StatementInvalid caught, but unsure what to do with it: #{e}"
+ raise e
+ end
+ end
+ end
+
+ def new_index_for(index_definition)
+ ferret_cfg = index_definition[:ferret].dup
+ ferret_cfg.update :auto_flush => false,
+ :create => true,
+ :field_infos => ActsAsFerret::field_infos(index_definition),
+ :path => File.join(index_definition[:index_base_dir], 'rebuild')
+ returning Ferret::Index::Index.new(ferret_cfg) do |i|
+ i.batch_size = index_definition[:reindex_batch_size]
+ i.logger = @logger
+ end
+ end
+
+ end
+ end
+end
diff --git a/src/server/vendor/plugins/acts_as_ferret/lib/index.rb b/src/server/vendor/plugins/acts_as_ferret/lib/index.rb
new file mode 100644
index 0000000..a779bf1
--- /dev/null
+++ b/src/server/vendor/plugins/acts_as_ferret/lib/index.rb
@@ -0,0 +1,99 @@
+module ActsAsFerret
+
+ class IndexLogger
+ def initialize(logger, name)
+ @logger = logger
+ @index_name = name
+ end
+ %w(debug info warn error).each do |m|
+ define_method(m) do |message|
+ @logger.send m, "[#{@index_name}] #{message}"
+ end
+ question = :"#{m}?"
+ define_method(question) do
+ @logger.send question
+ end
+ end
+ end
+
+ # base class for local and remote indexes
+ class AbstractIndex
+ include FerretFindMethods
+
+ attr_reader :logger, :index_name, :index_definition, :registered_models_config
+ def initialize(index_definition)
+ @index_definition = index_definition
+ @registered_models_config = {}
+ @index_name = index_definition[:name]
+ @logger = IndexLogger.new(ActsAsFerret::logger, @index_name)
+ end
+
+ # TODO allow for per-class field configuration (i.e. different via, boosts
+ # for the same field among different models)
+ def register_class(clazz, options = {})
+ logger.info "register class #{clazz} with index #{index_name}"
+
+ if force = options.delete(:force_re_registration)
+ index_definition[:registered_models].delete(clazz)
+ end
+
+ if index_definition[:registered_models].map(&:name).include?(clazz.name)
+ logger.info("refusing re-registration of class #{clazz}")
+ else
+ index_definition[:registered_models] << clazz
+ @registered_models_config[clazz] = options
+
+ # merge fields from this acts_as_ferret call with predefined fields
+ already_defined_fields = index_definition[:ferret_fields]
+ field_config = ActsAsFerret::build_field_config options[:fields]
+ field_config.update ActsAsFerret::build_field_config( options[:additional_fields] )
+ field_config.each do |field, config|
+ if already_defined_fields.has_key?(field)
+ logger.info "ignoring redefinition of ferret field #{field}" if shared?
+ else
+ already_defined_fields[field] = config
+ logger.info "adding new field #{field} from class #{clazz.name} to index #{index_name}"
+ end
+ end
+
+ # update default field list to be used by the query parser, unless it
+ # was explicitly given by user.
+ #
+ # It will include all content fields *not* marked as :untokenized.
+ # This fixes the otherwise failing CommentTest#test_stopwords. Basically
+ # this means that by default only tokenized fields (which all fields are
+ # by default) will be searched. If you want to search inside the contents
+ # of an untokenized field, you'll have to explicitly specify it in your
+ # query.
+ unless index_definition[:user_default_field]
+ # grab all tokenized fields
+ ferret_fields = index_definition[:ferret_fields]
+ index_definition[:ferret][:default_field] = ferret_fields.keys.select do |field|
+ ferret_fields[field][:index] != :untokenized
+ end
+ logger.info "default field list for index #{index_name}: #{index_definition[:ferret][:default_field].inspect}"
+ end
+ end
+
+ return index_definition
+ end
+
+ # true if this index is used by more than one model class
+ def shared?
+ index_definition[:registered_models].size > 1
+ end
+
+ # Switches the index to a new index directory.
+ # Used by the DRb server when switching to a new index version.
+ def change_index_dir(new_dir)
+ logger.debug "[#{index_name}] changing index dir to #{new_dir}"
+ index_definition[:index_dir] = index_definition[:ferret][:path] = new_dir
+ reopen!
+ logger.debug "[#{index_name}] index dir is now #{new_dir}"
+ end
+
+ protected
+
+ end
+
+end
diff --git a/src/server/vendor/plugins/acts_as_ferret/lib/instance_methods.rb b/src/server/vendor/plugins/acts_as_ferret/lib/instance_methods.rb
new file mode 100644
index 0000000..c8f2fc5
--- /dev/null
+++ b/src/server/vendor/plugins/acts_as_ferret/lib/instance_methods.rb
@@ -0,0 +1,171 @@
+module ActsAsFerret #:nodoc:
+
+ module InstanceMethods
+ include ResultAttributes
+
+ # Returns an array of strings with the matches highlighted. The +query+ can
+ # either be a String or a Ferret::Search::Query object.
+ #
+ # === Options
+ #
+ # field:: field to take the content from. This field has
+ # to have it's content stored in the index
+ # (:store => :yes in your call to aaf). If not
+ # given, all stored fields are searched, and the
+ # highlighted content found in all of them is returned.
+ # set :highlight => :no in the field options to
+ # avoid highlighting of contents from a :stored field.
+ # excerpt_length:: Default: 150. Length of excerpt to show. Highlighted
+ # terms will be in the centre of the excerpt.
+ # num_excerpts:: Default: 2. Number of excerpts to return.
+ # pre_tag:: Default: "<em>". Tag to place to the left of the
+ # match.
+ # post_tag:: Default: "</em>". This tag should close the
+ # +:pre_tag+.
+ # ellipsis:: Default: "...". This is the string that is appended
+ # at the beginning and end of excerpts (unless the
+ # excerpt hits the start or end of the field. You'll
+ # probably want to change this to a Unicode elipsis
+ # character.
+ def highlight(query, options = {})
+ self.class.aaf_index.highlight(self.ferret_key, query, options)
+ end
+
+ # re-eneable ferret indexing for this instance after a call to #disable_ferret
+ def enable_ferret
+ @ferret_disabled = nil
+ end
+ alias ferret_enable enable_ferret # compatibility
+
+ # returns true if ferret indexing is enabled for this record.
+ #
+ # The optional is_bulk_index parameter will be true if the method is called
+ # by rebuild_index or bulk_index, and false otherwise.
+ #
+ # If is_bulk_index is true, the class level ferret_enabled state will be
+ # ignored by this method (per-instance ferret_enabled checks however will
+ # take place, so if you override this method to forbid indexing of certain
+ # records you're still safe).
+ def ferret_enabled?(is_bulk_index = false)
+ @ferret_disabled.nil? && (is_bulk_index || self.class.ferret_enabled?) && (aaf_configuration[:if].nil? || aaf_configuration[:if].call(self))
+ end
+
+ # Returns the analyzer to use when adding this record to the index.
+ #
+ # Override to return a specific analyzer for any record that is to be
+ # indexed, i.e. specify a different analyzer based on language. Returns nil
+ # by default so the global analyzer (specified with the acts_as_ferret
+ # call) is used.
+ def ferret_analyzer
+ nil
+ end
+
+ # Disable Ferret for this record for a specified amount of time. ::once will
+ # disable Ferret for the next call to #save (this is the default), ::always
+ # will do so for all subsequent calls.
+ #
+ # Note that this will turn off only the create and update hooks, but not the
+ # destroy hook. I think that's reasonable, if you think the opposite, please
+ # tell me.
+ #
+ # To manually trigger reindexing of a record after you're finished modifying
+ # it, you can call #ferret_update directly instead of #save (remember to
+ # enable ferret again before).
+ #
+ # When given a block, this will be executed without any ferret indexing of
+ # this object taking place. The optional argument in this case can be used
+ # to indicate if the object should be indexed after executing the block
+ # (::index_when_finished). Automatic Ferret indexing of this object will be
+ # turned on after the block has been executed. If passed ::index_when_true,
+ # the index will only be updated if the block evaluated not to false or nil.
+ #
+ def disable_ferret(option = :once)
+ if block_given?
+ @ferret_disabled = :always
+ result = yield
+ ferret_enable
+ ferret_update if option == :index_when_finished || (option == :index_when_true && result)
+ result
+ elsif [:once, :always].include?(option)
+ @ferret_disabled = option
+ else
+ raise ArgumentError.new("Invalid Argument #{option}")
+ end
+ end
+
+ # add to index
+ def ferret_create
+ if ferret_enabled?
+ logger.debug "ferret_create/update: #{self.ferret_key}"
+ self.class.aaf_index << self
+ else
+ ferret_enable if @ferret_disabled == :once
+ end
+ true # signal success to AR
+ end
+ alias :ferret_update :ferret_create
+
+
+ # remove from index
+ def ferret_destroy
+ logger.debug "ferret_destroy: #{self.ferret_key}"
+ begin
+ self.class.aaf_index.remove self.ferret_key
+ rescue
+ logger.warn("Could not find indexed value for this object: #{$!}\n#{$!.backtrace}")
+ end
+ true # signal success to AR
+ end
+
+ def ferret_key
+ "#{self.class.name}-#{self.send self.class.primary_key}" unless new_record?
+ end
+
+ # turn this instance into a ferret document (which basically is a hash of
+ # fieldname => value pairs)
+ def to_doc
+ logger.debug "creating doc for class: #{self.ferret_key}"
+ returning Ferret::Document.new do |doc|
+ # store the id and class name of each item, and the unique key used for identifying the record
+ # even in multi-class indexes.
+ doc[:key] = self.ferret_key
+ doc[:id] = self.id.to_s
+ doc[:class_name] = self.class.name
+
+ # iterate through the fields and add them to the document
+ aaf_configuration[:defined_fields].each_pair do |field, config|
+ doc[field] = self.send("#{field}_to_ferret") unless config[:ignore]
+ end
+ if aaf_configuration[:boost]
+ if self.respond_to?(aaf_configuration[:boost])
+ boost = self.send aaf_configuration[:boost]
+ doc.boost = boost.to_i if boost
+ else
+ logger.error "boost option should point to an instance method: #{aaf_configuration[:boost]}"
+ end
+ end
+ end
+ end
+
+ def document_number
+ self.class.aaf_index.document_number(self.ferret_key)
+ end
+
+ def query_for_record
+ self.class.aaf_index.query_for_record(self.ferret_key)
+ end
+
+ def content_for_field_name(field, via = field, dynamic_boost = nil)
+ field_data = (respond_to?(via) ? send(via) : instance_variable_get("@#{via}")).to_s
+ # field_data = self.send(via) || self.instance_variable_get("@#{via}")
+ if (dynamic_boost && boost_value = self.send(dynamic_boost))
+ field_data = Ferret::Field.new(field_data)
+ field_data.boost = boost_value.to_i
+ end
+ field_data
+ end
+
+
+ end
+
+end
diff --git a/src/server/vendor/plugins/acts_as_ferret/lib/local_index.rb b/src/server/vendor/plugins/acts_as_ferret/lib/local_index.rb
new file mode 100644
index 0000000..7931a4f
--- /dev/null
+++ b/src/server/vendor/plugins/acts_as_ferret/lib/local_index.rb
@@ -0,0 +1,205 @@
+module ActsAsFerret
+ class LocalIndex < AbstractIndex
+ include MoreLikeThis::IndexMethods
+
+ def initialize(index_name)
+ super
+ ensure_index_exists
+ end
+
+ def reopen!
+ logger.debug "reopening index at #{index_definition[:ferret][:path]}"
+ close
+ ferret_index
+ end
+
+ # The 'real' Ferret Index instance
+ def ferret_index
+ ensure_index_exists
+ returning @ferret_index ||= Ferret::Index::Index.new(index_definition[:ferret]) do
+ @ferret_index.batch_size = index_definition[:reindex_batch_size]
+ @ferret_index.logger = logger
+ end
+ end
+
+ # Checks for the presence of a segments file in the index directory
+ # Rebuilds the index if none exists.
+ def ensure_index_exists
+ #logger.debug "LocalIndex: ensure_index_exists at #{index_definition[:index_dir]}"
+ unless File.file? "#{index_definition[:index_dir]}/segments"
+ ActsAsFerret::ensure_directory(index_definition[:index_dir])
+ rebuild_index
+ end
+ end
+
+ # Closes the underlying index instance
+ def close
+ @ferret_index.close if @ferret_index
+ rescue StandardError
+ # is raised when index already closed
+ ensure
+ @ferret_index = nil
+ end
+
+ # rebuilds the index from all records of the model classes associated with this index
+ def rebuild_index
+ models = index_definition[:registered_models]
+ logger.debug "rebuild index with models: #{models.inspect}"
+ close
+ index = Ferret::Index::Index.new(index_definition[:ferret].dup.update(:auto_flush => false,
+ :field_infos => ActsAsFerret::field_infos(index_definition),
+ :create => true))
+ index.batch_size = index_definition[:reindex_batch_size]
+ index.logger = logger
+ index.index_models models
+ reopen!
+ end
+
+ def bulk_index(class_name, ids, options)
+ ferret_index.bulk_index(class_name.constantize, ids, options)
+ end
+
+ # Parses the given query string into a Ferret Query object.
+ def process_query(query, options = {})
+ return query unless String === query
+ ferret_index.synchronize do
+ if options[:analyzer]
+ # use per-query analyzer if present
+ qp = Ferret::QueryParser.new ferret_index.instance_variable_get('@options').merge(options)
+ reader = ferret_index.reader
+ qp.fields =
+ reader.fields unless options[:all_fields] || options[:fields]
+ qp.tokenized_fields =
+ reader.tokenized_fields unless options[:tokenized_fields]
+ return qp.parse query
+ else
+ # work around ferret bug in #process_query (doesn't ensure the
+ # reader is open)
+ ferret_index.send(:ensure_reader_open)
+ return ferret_index.process_query(query)
+ end
+ end
+ end
+
+ # Total number of hits for the given query.
+ def total_hits(query, options = {})
+ ferret_index.search(process_query(query, options), options).total_hits
+ end
+
+ def searcher
+ ferret_index
+ end
+
+
+ ######################################
+ # methods working on a single record
+ # called from instance_methods, here to simplify interfacing with the
+ # remote ferret server
+ # TODO having to pass id and class_name around like this isn't nice
+ ######################################
+
+ # add record to index
+ # record may be the full AR object, a Ferret document instance or a Hash
+ def add(record, analyzer = nil)
+ unless Hash === record || Ferret::Document === record
+ analyzer = record.ferret_analyzer
+ record = record.to_doc
+ end
+ ferret_index.add_document(record, analyzer)
+ end
+ alias << add
+
+ # delete record from index
+ def remove(key)
+ ferret_index.delete key
+ end
+
+ # highlight search terms for the record with the given id.
+ def highlight(key, query, options = {})
+ logger.debug("highlight: #{key} query: #{query}")
+ options.reverse_merge! :num_excerpts => 2, :pre_tag => '<em>', :post_tag => '</em>'
+ highlights = []
+ ferret_index.synchronize do
+ doc_num = document_number(key)
+
+ if options[:field]
+ highlights << ferret_index.highlight(query, doc_num, options)
+ else
+ query = process_query(query) # process only once
+ index_definition[:ferret_fields].each_pair do |field, config|
+ next if config[:store] == :no || config[:highlight] == :no
+ options[:field] = field
+ highlights << ferret_index.highlight(query, doc_num, options)
+ end
+ end
+ end
+ return highlights.compact.flatten[0..options[:num_excerpts]-1]
+ end
+
+ # retrieves the ferret document number of the record with the given key.
+ def document_number(key)
+ docnum = ferret_index.doc_number(key)
+ # hits = ferret_index.search query_for_record(key)
+ # return hits.hits.first.doc if hits.total_hits == 1
+ raise "cannot determine document number for record #{key}" if docnum.nil?
+ docnum
+ end
+
+ # build a ferret query matching only the record with the given id
+ # the class name only needs to be given in case of a shared index configuration
+ def query_for_record(key)
+ return Ferret::Search::TermQuery.new(:key, key.to_s)
+ # if shared?
+ # raise InvalidArgumentError.new("shared index needs class_name argument") if class_name.nil?
+ # returning bq = Ferret::Search::BooleanQuery.new do
+ # bq.add_query(Ferret::Search::TermQuery.new(:id, id.to_s), :must)
+ # bq.add_query(Ferret::Search::TermQuery.new(:class_name, class_name), :must)
+ # end
+ # else
+ # Ferret::Search::TermQuery.new(:id, id.to_s)
+ # end
+ end
+
+
+ # retrieves stored fields from index definition in case the fields to retrieve
+ # haven't been specified with the :lazy option
+ def determine_stored_fields(options = {})
+ stored_fields = options[:lazy]
+ if stored_fields && !(Array === stored_fields)
+ stored_fields = index_definition[:ferret_fields].select { |field, config| config[:store] == :yes }.map(&:first)
+ end
+ logger.debug "stored_fields: #{stored_fields.inspect}"
+ return stored_fields
+ end
+
+ # loads data for fields declared as :lazy from the Ferret document
+ def extract_stored_fields(doc, stored_fields)
+ data = {}
+ unless stored_fields.nil?
+ logger.debug "extracting stored fields #{stored_fields.inspect} from document #{doc[:class_name]} / #{doc[:id]}"
+ fields = index_definition[:ferret_fields]
+ stored_fields.each do |field|
+ if field_cfg = fields[field]
+ data[field_cfg[:via]] = doc[field]
+ end
+ end
+ logger.debug "done: #{data.inspect}"
+ end
+ return data
+ end
+
+ protected
+
+ # returns a MultiIndex instance operating on a MultiReader
+ #def multi_index(model_classes)
+ # model_classes.map!(&:constantize) if String === model_classes.first
+ # model_classes.sort! { |a, b| a.name <=> b.name }
+ # key = model_classes.inject("") { |s, clazz| s + clazz.name }
+ # multi_config = index_definition[:ferret].dup
+ # multi_config.delete :default_field # we don't want the default field list of *this* class for multi_searching
+ # ActsAsFerret::multi_indexes[key] ||= MultiIndex.new(model_classes, multi_config)
+ #end
+
+ end
+
+end
diff --git a/src/server/vendor/plugins/acts_as_ferret/lib/more_like_this.rb b/src/server/vendor/plugins/acts_as_ferret/lib/more_like_this.rb
new file mode 100644
index 0000000..28ff313
--- /dev/null
+++ b/src/server/vendor/plugins/acts_as_ferret/lib/more_like_this.rb
@@ -0,0 +1,217 @@
+module ActsAsFerret #:nodoc:
+
+ module MoreLikeThis
+
+ module InstanceMethods
+
+ # returns other instances of this class, which have similar contents
+ # like this one. Basically works like this: find out n most interesting
+ # (i.e. characteristic) terms from this document, and then build a
+ # query from those which is run against the whole index. Which terms
+ # are interesting is decided on variour criteria which can be
+ # influenced by the given options.
+ #
+ # The algorithm used here is a quite straight port of the MoreLikeThis class
+ # from Apache Lucene.
+ #
+ # options are:
+ # :field_names : Array of field names to use for similarity search (mandatory)
+ # :min_term_freq => 2, # Ignore terms with less than this frequency in the source doc.
+ # :min_doc_freq => 5, # Ignore words which do not occur in at least this many docs
+ # :min_word_length => nil, # Ignore words shorter than this length (longer words tend to
+ # be more characteristic for the document they occur in).
+ # :max_word_length => nil, # Ignore words if greater than this len.
+ # :max_query_terms => 25, # maximum number of terms in the query built
+ # :max_num_tokens => 5000, # maximum number of tokens to examine in a single field
+ # :boost => false, # when true, a boost according to the relative score of
+ # a term is applied to this Term's TermQuery.
+ # :similarity => 'DefaultAAFSimilarity' # the similarity implementation to use (the default
+ # equals Ferret's internal similarity implementation)
+ # :analyzer => 'Ferret::Analysis::StandardAnalyzer' # class name of the analyzer to use
+ # :append_to_query => nil # proc taking a query object as argument, which will be called after generating the query. can be used to further manipulate the query used to find related documents, i.e. to constrain the search to a given class in single table inheritance scenarios
+ # ferret_options : Ferret options handed over to find_with_ferret (i.e. for limits and sorting)
+ # ar_options : options handed over to find_with_ferret for AR scoping
+ def more_like_this(options = {}, ferret_options = {}, ar_options = {})
+ options = {
+ :field_names => nil, # Default field names
+ :min_term_freq => 2, # Ignore terms with less than this frequency in the source doc.
+ :min_doc_freq => 5, # Ignore words which do not occur in at least this many docs
+ :min_word_length => 0, # Ignore words if less than this len. Default is not to ignore any words.
+ :max_word_length => 0, # Ignore words if greater than this len. Default is not to ignore any words.
+ :max_query_terms => 25, # maximum number of terms in the query built
+ :max_num_tokens => 5000, # maximum number of tokens to analyze when analyzing contents
+ :boost => false,
+ :similarity => 'ActsAsFerret::MoreLikeThis::DefaultAAFSimilarity', # class name of the similarity implementation to use
+ :analyzer => 'Ferret::Analysis::StandardAnalyzer', # class name of the analyzer to use
+ :append_to_query => nil,
+ :base_class => self.class # base class to use for querying, useful in STI scenarios where BaseClass.find_with_ferret can be used to retrieve results from other classes, too
+ }.update(options)
+ #index.search_each('id:*') do |doc, score|
+ # puts "#{doc} == #{index[doc][:description]}"
+ #end
+ clazz = options[:base_class]
+ options[:base_class] = clazz.name
+ query = clazz.aaf_index.build_more_like_this_query(self.ferret_key, self.id, options)
+ options[:append_to_query].call(query) if options[:append_to_query]
+ clazz.find_with_ferret(query, ferret_options, ar_options)
+ end
+
+ end
+
+ module IndexMethods
+
+ # TODO to allow morelikethis for unsaved records, we have to give the
+ # unsaved record's data to this method. check how this will work out
+ # via drb...
+ def build_more_like_this_query(key, id, options)
+ [:similarity, :analyzer].each { |sym| options[sym] = options[sym].constantize.new }
+ ferret_index.synchronize do # avoid that concurrent writes close our reader
+ ferret_index.send(:ensure_reader_open)
+ reader = ferret_index.send(:reader)
+ term_freq_map = retrieve_terms(key, id, reader, options)
+ priority_queue = create_queue(term_freq_map, reader, options)
+ create_query(key, priority_queue, options)
+ end
+ end
+
+ protected
+
+ def create_query(key, priority_queue, options={})
+ query = Ferret::Search::BooleanQuery.new
+ qterms = 0
+ best_score = nil
+ while(cur = priority_queue.pop)
+ term_query = Ferret::Search::TermQuery.new(cur.field, cur.word)
+
+ if options[:boost]
+ # boost term according to relative score
+ # TODO untested
+ best_score ||= cur.score
+ term_query.boost = cur.score / best_score
+ end
+ begin
+ query.add_query(term_query, :should)
+ rescue Ferret::Search::BooleanQuery::TooManyClauses
+ break
+ end
+ qterms += 1
+ break if options[:max_query_terms] > 0 && qterms >= options[:max_query_terms]
+ end
+ # exclude the original record
+ query.add_query(query_for_record(key), :must_not)
+ return query
+ end
+
+
+
+ # creates a term/term_frequency map for terms from the fields
+ # given in options[:field_names]
+ def retrieve_terms(key, id, reader, options)
+ raise "more_like_this atm only works on saved records" if key.nil?
+ document_number = document_number(key) rescue nil
+ field_names = options[:field_names]
+ max_num_tokens = options[:max_num_tokens]
+ term_freq_map = Hash.new(0)
+ doc = nil
+ record = nil
+ field_names.each do |field|
+ #puts "field: #{field}"
+ term_freq_vector = reader.term_vector(document_number, field) if document_number
+ #if false
+ if term_freq_vector
+ # use stored term vector
+ # puts 'using stored term vector'
+ term_freq_vector.terms.each do |term|
+ term_freq_map[term.text] += term.positions.size unless noise_word?(term.text, options)
+ end
+ else
+ # puts 'no stored term vector'
+ # no term vector stored, but we have stored the contents in the index
+ # -> extract terms from there
+ content = nil
+ if document_number
+ doc = reader[document_number]
+ content = doc[field]
+ end
+ unless content
+ # no term vector, no stored content, so try content from this instance
+ record ||= options[:base_class].constantize.find(id)
+ content = record.content_for_field_name(field.to_s)
+ end
+ puts "have doc: #{doc[:id]} with #{field} == #{content}"
+ token_count = 0
+
+ ts = options[:analyzer].token_stream(field, content)
+ while token = ts.next
+ break if (token_count+=1) > max_num_tokens
+ next if noise_word?(token.text, options)
+ term_freq_map[token.text] += 1
+ end
+ end
+ end
+ term_freq_map
+ end
+
+ # create an ordered(by score) list of word,fieldname,score
+ # structures
+ def create_queue(term_freq_map, reader, options)
+ pq = Array.new(term_freq_map.size)
+
+ similarity = options[:similarity]
+ num_docs = reader.num_docs
+ term_freq_map.each_pair do |word, tf|
+ # filter out words that don't occur enough times in the source
+ next if options[:min_term_freq] && tf < options[:min_term_freq]
+
+ # go through all the fields and find the largest document frequency
+ top_field = options[:field_names].first
+ doc_freq = 0
+ options[:field_names].each do |field_name|
+ freq = reader.doc_freq(field_name, word)
+ if freq > doc_freq
+ top_field = field_name
+ doc_freq = freq
+ end
+ end
+ # filter out words that don't occur in enough docs
+ next if options[:min_doc_freq] && doc_freq < options[:min_doc_freq]
+ next if doc_freq == 0 # index update problem ?
+
+ idf = similarity.idf(doc_freq, num_docs)
+ score = tf * idf
+ pq << FrequencyQueueItem.new(word, top_field, score)
+ end
+ pq.compact!
+ pq.sort! { |a,b| a.score<=>b.score }
+ return pq
+ end
+
+ def noise_word?(text, options)
+ len = text.length
+ (
+ (options[:min_word_length] > 0 && len < options[:min_word_length]) ||
+ (options[:max_word_length] > 0 && len > options[:max_word_length]) ||
+ (options[:stop_words] && options.include?(text))
+ )
+ end
+
+ end
+
+ class DefaultAAFSimilarity
+ def idf(doc_freq, num_docs)
+ return 0.0 if num_docs == 0
+ return Math.log(num_docs.to_f/(doc_freq+1)) + 1.0
+ end
+ end
+
+
+ class FrequencyQueueItem
+ attr_reader :word, :field, :score
+ def initialize(word, field, score)
+ @word = word; @field = field; @score = score
+ end
+ end
+
+ end
+end
+
diff --git a/src/server/vendor/plugins/acts_as_ferret/lib/multi_index.rb b/src/server/vendor/plugins/acts_as_ferret/lib/multi_index.rb
new file mode 100644
index 0000000..26d3af4
--- /dev/null
+++ b/src/server/vendor/plugins/acts_as_ferret/lib/multi_index.rb
@@ -0,0 +1,126 @@
+module ActsAsFerret #:nodoc:
+
+ # Base class for remote and local multi-indexes
+ class MultiIndexBase
+ include FerretFindMethods
+ attr_accessor :logger
+
+ def initialize(indexes, options = {})
+ # ensure all models indexes exist
+ @indexes = indexes
+ indexes.each { |i| i.ensure_index_exists }
+ default_fields = indexes.inject([]) do |fields, idx|
+ fields + [ idx.index_definition[:ferret][:default_field] ]
+ end.flatten.uniq
+ @options = {
+ :default_field => default_fields
+ }.update(options)
+ @logger = IndexLogger.new(ActsAsFerret::logger, "multi: #{indexes.map(&:index_name).join(',')}")
+ end
+
+ def ar_find(query, options = {}, ar_options = {})
+ limit = options.delete(:limit)
+ offset = options.delete(:offset) || 0
+ options[:limit] = :all
+ total_hits, result = super query, options, ar_options
+ total_hits = result.size if ar_options[:conditions]
+ # if limit && limit != :all
+ # result = result[offset..limit+offset-1]
+ # end
+ [total_hits, result]
+ end
+
+ def determine_stored_fields(options)
+ return nil unless options.has_key?(:lazy)
+ stored_fields = []
+ @indexes.each do |index|
+ stored_fields += index.determine_stored_fields(options)
+ end
+ return stored_fields.uniq
+ end
+
+ def shared?
+ false
+ end
+
+ end
+
+ # This class can be used to search multiple physical indexes at once.
+ class MultiIndex < MultiIndexBase
+
+ def extract_stored_fields(doc, stored_fields)
+ ActsAsFerret::get_index_for(doc[:class_name]).extract_stored_fields(doc, stored_fields) unless stored_fields.blank?
+ end
+
+ def total_hits(q, options = {})
+ search(q, options).total_hits
+ end
+
+ def search(query, options={})
+ query = process_query(query, options)
+ logger.debug "parsed query: #{query.to_s}"
+ searcher.search(query, options)
+ end
+
+ def search_each(query, options = {}, &block)
+ query = process_query(query, options)
+ searcher.search_each(query, options, &block)
+ end
+
+ # checks if all our sub-searchers still are up to date
+ def latest?
+ #return false unless @reader
+ # segfaults with 0.10.4 --> TODO report as bug @reader.latest?
+ @reader and @reader.latest?
+ #@sub_readers.each do |r|
+ # return false unless r.latest?
+ #end
+ #true
+ end
+
+ def searcher
+ ensure_searcher
+ @searcher
+ end
+
+ def doc(i)
+ searcher[i]
+ end
+ alias :[] :doc
+
+ def query_parser
+ @query_parser ||= Ferret::QueryParser.new(@options)
+ end
+
+ def process_query(query, options = {})
+ query = query_parser.parse(query) if query.is_a?(String)
+ return query
+ end
+
+ def close
+ @searcher.close if @searcher
+ @reader.close if @reader
+ end
+
+ protected
+
+ def ensure_searcher
+ unless latest?
+ @sub_readers = @indexes.map { |idx|
+ begin
+ reader = Ferret::Index::IndexReader.new(idx.index_definition[:index_dir])
+ logger.debug "sub-reader opened: #{reader}"
+ reader
+ rescue Exception
+ raise "error opening reader on index for class #{clazz.inspect}: #{$!}"
+ end
+ }
+ close
+ @reader = Ferret::Index::IndexReader.new(@sub_readers)
+ @searcher = Ferret::Search::Searcher.new(@reader)
+ end
+ end
+
+ end # of class MultiIndex
+
+end
diff --git a/src/server/vendor/plugins/acts_as_ferret/lib/rdig_adapter.rb b/src/server/vendor/plugins/acts_as_ferret/lib/rdig_adapter.rb
new file mode 100644
index 0000000..075455a
--- /dev/null
+++ b/src/server/vendor/plugins/acts_as_ferret/lib/rdig_adapter.rb
@@ -0,0 +1,148 @@
+begin
+ require 'rdig'
+rescue LoadError
+end
+require 'digest/md5'
+
+module ActsAsFerret
+
+ # The RdigAdapter is automatically included into your model if you specify
+ # the +:rdig+ options hash in your call to acts_as_ferret. It overrides
+ # several methods declared by aaf to retrieve documents with the help of
+ # RDig's http crawler when you call rebuild_index.
+ module RdigAdapter
+
+ if defined?(RDig)
+
+ def self.included(target)
+ target.extend ClassMethods
+ target.send :include, InstanceMethods
+ target.alias_method_chain :ferret_key, :md5
+ end
+
+ # Indexer class to replace RDig's original indexer
+ class Indexer
+ include MonitorMixin
+ def initialize(batch_size, model_class, &block)
+ @batch_size = batch_size
+ @model_class = model_class
+ @documents = []
+ @offset = 0
+ @block = block
+ super()
+ end
+
+ def add(doc)
+ synchronize do
+ @documents << @model_class.new(doc.uri.to_s, doc)
+ process_batch if @documents.size >= @batch_size
+ end
+ end
+ alias << add
+
+ def close
+ synchronize do
+ process_batch
+ end
+ end
+
+ protected
+ def process_batch
+ ActsAsFerret::logger.info "RdigAdapter::Indexer#process_batch: #{@documents.size} docs in queue, offset #{@offset}"
+ @block.call @documents, @offset
+ @offset += @documents.size
+ @documents = []
+ end
+ end
+
+ module ClassMethods
+ # overriding aaf to return the documents fetched via RDig
+ def records_for_rebuild(batch_size = 1000, &block)
+ indexer = Indexer.new(batch_size, self, &block)
+ configure_rdig do
+ crawler = RDig::Crawler.new RDig.configuration, ActsAsFerret::logger
+ crawler.instance_variable_set '@indexer', indexer
+ ActsAsFerret::logger.debug "now crawling..."
+ crawler.crawl
+ end
+ rescue => e
+ ActsAsFerret::logger.error e
+ ActsAsFerret::logger.debug e.backtrace.join("\n")
+ ensure
+ indexer.close if indexer
+ end
+
+ # overriding aaf to skip reindexing records changed during the rebuild
+ # when rebuilding with the rake task
+ def records_modified_since(time)
+ []
+ end
+
+ # unfortunately need to modify global RDig.configuration because it's
+ # used everywhere in RDig
+ def configure_rdig
+ # back up original config
+ old_logger = RDig.logger
+ old_cfg = RDig.configuration.dup
+ RDig.logger = ActsAsFerret.logger
+ rdig_configuration[:crawler].each { |k,v| RDig.configuration.crawler.send :"#{k}=", v } if rdig_configuration[:crawler]
+ if ce_config = rdig_configuration[:content_extraction]
+ RDig.configuration.content_extraction = OpenStruct.new( :hpricot => OpenStruct.new( ce_config ) )
+ end
+ yield
+ ensure
+ # restore original config
+ RDig.configuration.crawler = old_cfg.crawler
+ RDig.configuration.content_extraction = old_cfg.content_extraction
+ RDig.logger = old_logger
+ end
+
+ # overriding aaf to enforce loading page title and content from the
+ # ferret index
+ def find_with_ferret(q, options = {}, find_options = {})
+ options[:lazy] = true
+ super
+ end
+
+ def find_for_id(id)
+ new id
+ end
+ end
+
+ module InstanceMethods
+ def initialize(uri, rdig_document = nil)
+ @id = uri
+ @rdig_document = rdig_document
+ end
+
+ # Title of the document.
+ # Use the +:title_tag_selector+ option to declare the hpricot expression
+ # that should be used for selecting the content for this field.
+ def title
+ @rdig_document.title
+ end
+
+ # Content of the document.
+ # Use the +:content_tag_selector+ option to declare the hpricot expression
+ # that should be used for selecting the content for this field.
+ def content
+ @rdig_document.body
+ end
+
+ # Url of this document.
+ def id
+ @id
+ end
+
+ def ferret_key_with_md5
+ Digest::MD5.hexdigest(ferret_key_without_md5)
+ end
+
+ def to_s
+ "Page at #{id}, title: #{title}"
+ end
+ end
+ end
+ end
+
+end
diff --git a/src/server/vendor/plugins/acts_as_ferret/lib/remote_functions.rb b/src/server/vendor/plugins/acts_as_ferret/lib/remote_functions.rb
new file mode 100644
index 0000000..c4415f8
--- /dev/null
+++ b/src/server/vendor/plugins/acts_as_ferret/lib/remote_functions.rb
@@ -0,0 +1,43 @@
+module ActsAsFerret
+ module RemoteFunctions
+
+ private
+
+ def yield_results(total_hits, results)
+ results.each do |result|
+ yield result[:model], result[:id], result[:score], result[:data]
+ end
+ total_hits
+ end
+
+
+ def handle_drb_error(return_value_in_case_of_error = false)
+ yield
+ rescue DRb::DRbConnError => e
+ logger.error "DRb connection error: #{e}"
+ logger.warn e.backtrace.join("\n")
+ raise e if ActsAsFerret::raise_drb_errors?
+ return_value_in_case_of_error
+ end
+
+ alias :old_handle_drb_error :handle_drb_error
+ def handle_drb_error(return_value_in_case_of_error = false)
+ handle_drb_restart do
+ old_handle_drb_error(return_value_in_case_of_error) { yield }
+ end
+ end
+
+ def handle_drb_restart
+ trys = 1
+ begin
+ return yield
+ rescue ActsAsFerret::IndexNotDefined
+ logger.warn "Recovering from ActsAsFerret::IndexNotDefined exception"
+ ActsAsFerret::ferret_indexes[index_name] = ActsAsFerret::create_index_instance( index_definition )
+ ActsAsFerret::ferret_indexes[index_name].register_class ActsAsFerret::index_using_classes.index(index_name).constantize, {}
+ retry if (trys -= 1) > 0
+ end
+ yield
+ end
+ end
+end
diff --git a/src/server/vendor/plugins/acts_as_ferret/lib/remote_index.rb b/src/server/vendor/plugins/acts_as_ferret/lib/remote_index.rb
new file mode 100644
index 0000000..9c5849e
--- /dev/null
+++ b/src/server/vendor/plugins/acts_as_ferret/lib/remote_index.rb
@@ -0,0 +1,54 @@
+require 'drb'
+module ActsAsFerret
+
+ # This index implementation connects to a remote ferret server instance. It
+ # basically forwards all calls to the remote server.
+ class RemoteIndex < AbstractIndex
+ include RemoteFunctions
+
+ def initialize(config)
+ super
+ @server = DRbObject.new(nil, ActsAsFerret::remote)
+ end
+
+ # Cause model classes to be loaded (and indexes get declared) on the DRb
+ # side of things.
+ def register_class(clazz, options)
+ handle_drb_error { @server.register_class clazz.name }
+ end
+
+ def method_missing(method_name, *args)
+ args.unshift index_name
+ handle_drb_error { @server.send(method_name, *args) }
+ end
+
+ # Proxy any methods that require special return values in case of errors
+ {
+ :highlight => []
+ }.each do |method_name, default_result|
+ define_method method_name do |*args|
+ args.unshift index_name
+ handle_drb_error(default_result) { @server.send method_name, *args }
+ end
+ end
+
+ def find_ids(q, options = {}, &proc)
+ total_hits, results = handle_drb_error([0, []]) { @server.find_ids(index_name, q, options) }
+ block_given? ? yield_results(total_hits, results, &proc) : [ total_hits, results ]
+ end
+
+ # add record to index
+ def add(record)
+ handle_drb_error { @server.add index_name, record.to_doc }
+ end
+ alias << add
+
+ private
+
+ #def model_class_name
+ # index_definition[:class_name]
+ #end
+
+ end
+
+end
diff --git a/src/server/vendor/plugins/acts_as_ferret/lib/remote_multi_index.rb b/src/server/vendor/plugins/acts_as_ferret/lib/remote_multi_index.rb
new file mode 100644
index 0000000..7affd43
--- /dev/null
+++ b/src/server/vendor/plugins/acts_as_ferret/lib/remote_multi_index.rb
@@ -0,0 +1,20 @@
+module ActsAsFerret
+ class RemoteMultiIndex < MultiIndexBase
+ include RemoteFunctions
+
+ def initialize(indexes, options = {})
+ @index_names = indexes.map(&:index_name)
+ @server = DRbObject.new(nil, ActsAsFerret::remote)
+ super
+ end
+
+ def find_ids(query, options, &proc)
+ total_hits, results = handle_drb_error([0, []]) { @server.multi_find_ids(@index_names, query, options) }
+ block_given? ? yield_results(total_hits, results, &proc) : [ total_hits, results ]
+ end
+
+ def method_missing(name, *args)
+ handle_drb_error { @server.send(:"multi_#{name}", @index_names, *args) }
+ end
+ end
+end
diff --git a/src/server/vendor/plugins/acts_as_ferret/lib/search_results.rb b/src/server/vendor/plugins/acts_as_ferret/lib/search_results.rb
new file mode 100644
index 0000000..e3da6a2
--- /dev/null
+++ b/src/server/vendor/plugins/acts_as_ferret/lib/search_results.rb
@@ -0,0 +1,50 @@
+module ActsAsFerret
+
+ # decorator that adds a total_hits accessor and will_paginate compatible
+ # paging support to search result arrays
+ class SearchResults < ActsAsFerret::BlankSlate
+ reveal :methods
+ attr_reader :current_page, :per_page, :total_hits, :total_pages
+ alias total_entries total_hits # will_paginate compatibility
+ alias page_count total_pages # will_paginate backwards compatibility
+
+ def initialize(results, total_hits, current_page = 1, per_page = nil)
+ @results = results
+ @total_hits = total_hits
+ @current_page = current_page
+ @per_page = (per_page || total_hits)
+ @total_pages = @per_page > 0 ? (@total_hits / @per_page.to_f).ceil : 0
+ end
+
+ def method_missing(symbol, *args, &block)
+ @results.send(symbol, *args, &block)
+ end
+
+ def respond_to?(name)
+ methods.include?(name.to_s) || @results.respond_to?(name)
+ end
+
+
+ # code from here on was directly taken from will_paginate's collection.rb
+
+ # Current offset of the paginated collection. If we're on the first page,
+ # it is always 0. If we're on the 2nd page and there are 30 entries per page,
+ # the offset is 30. This property is useful if you want to render ordinals
+ # besides your records: simply start with offset + 1.
+ #
+ def offset
+ (current_page - 1) * per_page
+ end
+
+ # current_page - 1 or nil if there is no previous page
+ def previous_page
+ current_page > 1 ? (current_page - 1) : nil
+ end
+
+ # current_page + 1 or nil if there is no next page
+ def next_page
+ current_page < total_pages ? (current_page + 1) : nil
+ end
+ end
+
+end
diff --git a/src/server/vendor/plugins/acts_as_ferret/lib/server_manager.rb b/src/server/vendor/plugins/acts_as_ferret/lib/server_manager.rb
new file mode 100644
index 0000000..a5a1687
--- /dev/null
+++ b/src/server/vendor/plugins/acts_as_ferret/lib/server_manager.rb
@@ -0,0 +1,58 @@
+################################################################################
+require 'optparse'
+
+################################################################################
+$ferret_server_options = {
+ 'environment' => nil,
+ 'debug' => nil,
+ 'root' => nil
+}
+
+################################################################################
+OptionParser.new do |optparser|
+ optparser.banner = "Usage: #{File.basename($0)} [options] {start|stop|run}"
+
+ optparser.on('-h', '--help', "This message") do
+ puts optparser
+ exit
+ end
+
+ optparser.on('-R', '--root=PATH', 'Set RAILS_ROOT to the given string') do |r|
+ $ferret_server_options['root'] = r
+ end
+
+ optparser.on('-e', '--environment=NAME', 'Set RAILS_ENV to the given string') do |e|
+ $ferret_server_options['environment'] = e
+ end
+
+ optparser.on('--debug', 'Include full stack traces on exceptions') do
+ $ferret_server_options['debug'] = true
+ end
+
+ $ferret_server_action = optparser.permute!(ARGV)
+ (puts optparser; exit(1)) unless $ferret_server_action.size == 1
+
+ $ferret_server_action = $ferret_server_action.first
+ (puts optparser; exit(1)) unless %w(start stop run).include?($ferret_server_action)
+end
+
+################################################################################
+begin
+ ENV['FERRET_USE_LOCAL_INDEX'] = 'true'
+ ENV['RAILS_ENV'] = $ferret_server_options['environment']
+
+ # determine RAILS_ROOT unless already set
+ RAILS_ROOT = $ferret_server_options['root'] || File.join(File.dirname(__FILE__), *(['..']*4)) unless defined? RAILS_ROOT
+ # check if environment.rb is present
+ rails_env_file = File.join(RAILS_ROOT, 'config', 'environment')
+ raise "Unable to find Rails environment.rb at \n#{rails_env_file}.rb\nPlease use the --root option of ferret_server to point it to your RAILS_ROOT." unless File.exists?(rails_env_file+'.rb')
+ # load it
+ require rails_env_file
+
+ require 'acts_as_ferret'
+ ActsAsFerret::Remote::Server.new.send($ferret_server_action)
+rescue Exception => e
+ $stderr.puts(e.message)
+ $stderr.puts(e.backtrace.join("\n")) if $ferret_server_options['debug']
+ exit(1)
+end
diff --git a/src/server/vendor/plugins/acts_as_ferret/lib/unix_daemon.rb b/src/server/vendor/plugins/acts_as_ferret/lib/unix_daemon.rb
new file mode 100644
index 0000000..394de0e
--- /dev/null
+++ b/src/server/vendor/plugins/acts_as_ferret/lib/unix_daemon.rb
@@ -0,0 +1,86 @@
+################################################################################
+module ActsAsFerret
+ module Remote
+
+ ################################################################################
+ # methods for becoming a daemon on Unix-like operating systems
+ module UnixDaemon
+
+ ################################################################################
+ def platform_daemon (&block)
+ safefork do
+ write_pid_file
+ trap("TERM") { exit(0) }
+ sess_id = Process.setsid
+ STDIN.reopen("/dev/null")
+ STDOUT.reopen("#{RAILS_ROOT}/log/ferret_server.out", "a")
+ STDERR.reopen(STDOUT)
+ block.call
+ end
+ end
+
+ ################################################################################
+ # stop the daemon, nicely at first, and then forcefully if necessary
+ def stop
+ pid = read_pid_file
+ raise "ferret_server doesn't appear to be running" unless pid
+ $stdout.puts("stopping ferret server...")
+ Process.kill("TERM", pid)
+ 30.times { Process.kill(0, pid); sleep(0.5) }
+ $stdout.puts("using kill -9 #{pid}")
+ Process.kill(9, pid)
+ rescue Errno::ESRCH => e
+ $stdout.puts("process #{pid} has stopped")
+ ensure
+ File.unlink(@cfg.pid_file) if File.exist?(@cfg.pid_file)
+ end
+
+ ################################################################################
+ def safefork (&block)
+ @fork_tries ||= 0
+ fork(&block)
+ rescue Errno::EWOULDBLOCK
+ raise if @fork_tries >= 20
+ @fork_tries += 1
+ sleep 5
+ retry
+ end
+
+ #################################################################################
+ # create the PID file and install an at_exit handler
+ def write_pid_file
+ ensure_stopped
+ open(@cfg.pid_file, "w") {|f| f << Process.pid << "\n"}
+ at_exit { File.unlink(@cfg.pid_file) if read_pid_file == Process.pid }
+ end
+
+ #################################################################################
+ def read_pid_file
+ File.read(@cfg.pid_file).to_i if File.exist?(@cfg.pid_file)
+ end
+
+ #################################################################################
+ def ensure_stopped
+ if pid = read_pid_file
+ if process_exists(pid)
+ raise "ferret_server may already be running, a pid file exists: #{@cfg.pid_file} and a ferret_server process exists with matching pid #{pid}"
+ else
+ $stdout.puts("removing stale pid file...")
+ File.unlink(@cfg.pid_file) if File.exist?(@cfg.pid_file)
+ end
+ end
+ end
+
+ #################################################################################
+ # Check for existence of ferret_server process with PID from pid file
+ # checked on ubuntu and OSX only
+ def process_exists(pid)
+ ps = IO.popen("ps -fp #{pid}", "r")
+ process = ps.to_a[1]
+ ps.close
+ process =~ /ferret_server/
+ end
+
+ end
+ end
+end
diff --git a/src/server/vendor/plugins/acts_as_ferret/lib/without_ar.rb b/src/server/vendor/plugins/acts_as_ferret/lib/without_ar.rb
new file mode 100644
index 0000000..eba5e69
--- /dev/null
+++ b/src/server/vendor/plugins/acts_as_ferret/lib/without_ar.rb
@@ -0,0 +1,52 @@
+module ActsAsFerret
+
+ # Include this module to use acts_as_ferret with model classes
+ # not based on ActiveRecord.
+ #
+ # Implement the find_for_id(id) class method in your model class in
+ # order to make search work.
+ module WithoutAR
+ def self.included(target)
+ target.extend ClassMethods
+ target.extend ActsAsFerret::ActMethods
+ target.send :include, InstanceMethods
+ end
+
+ module ClassMethods
+ def logger
+ RAILS_DEFAULT_LOGGER
+ end
+ def table_name
+ self.name.underscore
+ end
+ def primary_key
+ 'id'
+ end
+ def find(what, args = {})
+ case what
+ when :all
+ ids = args[:conditions][1]
+ ids.map { |id| find id }
+ else
+ find_for_id what
+ end
+ end
+ def find_for_id(id)
+ raise NotImplementedError.new("implement find_for_id in class #{self.name}")
+ end
+ def count
+ 0
+ end
+ end
+
+ module InstanceMethods
+ def logger
+ self.class.logger
+ end
+ def new_record?
+ false
+ end
+ end
+ end
+
+end
diff --git a/src/server/vendor/plugins/acts_as_ferret/rakefile b/src/server/vendor/plugins/acts_as_ferret/rakefile
new file mode 100644
index 0000000..511e3db
--- /dev/null
+++ b/src/server/vendor/plugins/acts_as_ferret/rakefile
@@ -0,0 +1,141 @@
+# rakefile for acts_as_ferret.
+# use to create a gem or generate rdoc api documentation.
+#
+# RELEASE creation:
+# rake release REL=x.y.z
+
+require 'pathname'
+require 'yaml'
+require 'rake'
+require 'rake/rdoctask'
+require 'rake/packagetask'
+require 'rake/gempackagetask'
+require 'rake/testtask'
+require 'rake/contrib/rubyforgepublisher'
+
+def announce(msg='')
+ STDERR.puts msg
+end
+
+
+PKG_NAME = 'acts_as_ferret'
+PKG_VERSION = ENV['REL']
+PKG_FILE_NAME = "#{PKG_NAME}-#{PKG_VERSION}"
+RUBYFORGE_PROJECT = 'actsasferret'
+RUBYFORGE_USER = 'jkraemer'
+
+desc 'Default: run unit tests.'
+task :default => :test
+
+desc 'Test the acts_as_ferret plugin.'
+Rake::TestTask.new(:test) do |t|
+ t.libs << 'lib'
+ t.pattern = 'test/**/*_test.rb'
+ t.verbose = true
+end
+
+desc 'Generate documentation for the acts_as_ferret plugin.'
+Rake::RDocTask.new(:rdoc) do |rdoc|
+ rdoc.rdoc_dir = 'html'
+ rdoc.title = "acts_as_ferret - Ferret based full text search for any ActiveRecord model"
+ rdoc.options << '--line-numbers' << '--inline-source'
+ rdoc.options << '--main' << 'README'
+ rdoc.rdoc_files.include('README', 'LICENSE')
+ rdoc.template = "#{ENV['template']}.rb" if ENV['template']
+ rdoc.rdoc_files.include('lib/**/*.rb')
+end
+
+desc "Publish the API documentation"
+task :pdoc => [:rdoc] do
+ Rake::RubyForgePublisher.new(RUBYFORGE_PROJECT, RUBYFORGE_USER).upload
+end
+
+if PKG_VERSION
+ spec = Gem::Specification.new do |s|
+ s.name = PKG_NAME
+ s.version = PKG_VERSION
+ s.platform = Gem::Platform::RUBY
+ s.summary = "acts_as_ferret - Ferret based full text search for any ActiveRecord model"
+ s.files = Dir.glob('**/*', File::FNM_DOTMATCH).reject do |f|
+ [ /\.$/, /sqlite$/, /\.log$/, /^pkg/, /\.svn/, /\.git/, /\.\w+\.sw.$/,
+ /^html/, /\~$/, /\/\._/, /\/#/ ].any? {|regex| f =~ regex }
+ end
+ #s.files = FileList["{lib,test}/**/*"].to_a + %w(README MIT-LICENSE CHANGELOG)
+ # s.files.delete ...
+ s.require_path = 'lib'
+ s.bindir = "bin"
+ s.executables = ["aaf_install"]
+ s.default_executable = "aaf_install"
+ s.autorequire = 'acts_as_ferret'
+ s.has_rdoc = true
+ # s.test_files = Dir['test/**/*_test.rb']
+ s.author = "Jens Kraemer"
+ s.email = "jk@jkraemer.net"
+ s.homepage = "http://projects.jkraemer.net/acts_as_ferret"
+ end
+
+ desc "Update the gemspec for GitHub's gem server"
+ task :gemspec do
+ Pathname("#{spec.name}.gemspec").open('w') {|f| f << YAML.dump(spec) }
+ end
+
+ package_task = Rake::GemPackageTask.new(spec) do |pkg|
+ pkg.need_tar = true
+ end
+
+ # Validate that everything is ready to go for a release.
+ task :prerelease do
+ announce
+ announce "**************************************************************"
+ announce "* Making RubyGem Release #{PKG_VERSION}"
+ announce "**************************************************************"
+ announce
+ # Are all source files checked in?
+ if ENV['RELTEST']
+ announce "Release Task Testing, skipping checked-in file test"
+ else
+ announce "Pulling in svn..."
+ `svk pull .`
+ announce "Checking for unchecked-in files..."
+ data = `svk st`
+ unless data =~ /^$/
+ fail "SVK status is not clean ... do you have unchecked-in files?"
+ end
+ announce "No outstanding checkins found ... OK"
+# announce "Pushing to svn..."
+# `svk push .`
+ end
+ end
+
+
+ desc "tag the new release"
+ task :tag => [ :prerelease ] do
+ reltag = "REL_#{PKG_VERSION.gsub(/\./, '_')}"
+ reltag << ENV['REUSE'].gsub(/\./, '_') if ENV['REUSE']
+ announce "Tagging with [#{PKG_VERSION}]"
+ if ENV['RELTEST']
+ announce "Release Task Testing, skipping tagging"
+ else
+ `svn copy -m 'tagging version #{PKG_VERSION}' svn://projects.jkraemer.net/acts_as_ferret/trunk/plugin svn://projects.jkraemer.net/acts_as_ferret/tags/#{PKG_VERSION}`
+ `svn del -m 'remove old stable' svn://projects.jkraemer.net/acts_as_ferret/tags/stable`
+ `svn copy -m 'tagging version #{PKG_VERSION} as stable' svn://projects.jkraemer.net/acts_as_ferret/tags/#{PKG_VERSION} svn://projects.jkraemer.net/acts_as_ferret/tags/stable`
+ end
+ end
+
+ # Upload release to rubyforge
+ desc "Upload release to rubyforge"
+ task :prel => [ :tag, :prerelease, :package ] do
+ `rubyforge login`
+ release_command = "rubyforge add_release #{RUBYFORGE_PROJECT} #{PKG_NAME} '#{PKG_VERSION}' pkg/#{PKG_NAME}-#{PKG_VERSION}.gem"
+ puts release_command
+ system(release_command)
+ `rubyforge config #{RUBYFORGE_PROJECT}`
+ release_command = "rubyforge add_file #{RUBYFORGE_PROJECT} #{PKG_NAME} '#{PKG_VERSION}' pkg/#{PKG_NAME}-#{PKG_VERSION}.tgz"
+ puts release_command
+ system(release_command)
+ end
+
+ desc 'Publish the gem and API docs'
+ task :release => [:pdoc, :prel ]
+
+end
diff --git a/src/server/vendor/plugins/acts_as_ferret/recipes/aaf_recipes.rb b/src/server/vendor/plugins/acts_as_ferret/recipes/aaf_recipes.rb
new file mode 100644
index 0000000..97df727
--- /dev/null
+++ b/src/server/vendor/plugins/acts_as_ferret/recipes/aaf_recipes.rb
@@ -0,0 +1,114 @@
+# Ferret DRb server Capistrano tasks
+#
+# Usage:
+# in your Capfile, add acts_as_ferret's recipes directory to your load path and
+# load the ferret tasks:
+#
+# load_paths << 'vendor/plugins/acts_as_ferret/recipes'
+# load 'aaf_recipes'
+#
+# This will hook aaf's DRb start/stop tasks into the standard
+# deploy:{start|restart|stop} tasks so the server will be restarted along with
+# the rest of your application.
+# Also an index directory in the shared folder will be created and symlinked
+# into current/ when you deploy.
+#
+# In order to use the ferret:index:rebuild task, declare the indexes you intend to
+# rebuild remotely in config/deploy.rb:
+#
+# set :ferret_indexes, %w( model another_model shared )
+#
+# HINT: To be very sure that your DRb server and application are always using
+# the same model and schema versions, and you never lose any index updates because
+# of the DRb server being restarted in that moment, use the following sequence
+# to update your application:
+#
+# cap deploy:stop deploy:update deploy:migrate deploy:start
+#
+# That will stop the DRb server after stopping your application, and bring it
+# up before starting the application again. Plus they'll never use different
+# versions of model classes (which might happen otherwise)
+# Downside: Your downtime is a bit longer than with the usual deploy, so be sure to
+# put up some maintenance page for the meantime. Obviously this won't work if
+# your migrations need acts_as_ferret (i.e. if you update model instances which
+# would lead to index updates). In this case bring up the DRb server before
+# running your migrations:
+#
+# cap deploy:stop deploy:update ferret:start deploy:migrate ferret:stop deploy:start
+#
+# Chances are that you're still not safe if your migrations not only modify the index,
+# but also change the structure of your models. So just don't do both things in
+# one go - I can't think of an easy way to handle this case automatically.
+# Suggestions and patches are of course very welcome :-)
+
+namespace :ferret do
+
+ desc "Stop the Ferret DRb server"
+ task :stop, :roles => :app do
+ rails_env = fetch(:rails_env, 'production')
+ run "cd #{current_path}; script/ferret_server -e #{rails_env} stop || true"
+ end
+
+ desc "Start the Ferret DRb server"
+ task :start, :roles => :app do
+ rails_env = fetch(:rails_env, 'production')
+ run "cd #{current_path}; script/ferret_server -e #{rails_env} start"
+ end
+
+ desc "Restart the Ferret DRb server"
+ task :restart, :roles => :app do
+ top.ferret.stop
+ sleep 1
+ top.ferret.start
+ end
+
+ namespace :index do
+
+ desc "Rebuild the Ferret index. See aaf_recipes.rb for instructions."
+ task :rebuild, :roles => :app do
+ rake = fetch(:rake, 'rake')
+ rails_env = fetch(:rails_env, 'production')
+ indexes = fetch(:ferret_indexes, [])
+ if indexes.any?
+ run "cd #{current_path}; RAILS_ENV=#{rails_env} INDEXES='#{indexes.join(' ')}' #{rake} ferret:rebuild"
+ end
+ end
+
+ desc "purges all indexes for the current environment"
+ task :purge, :roles => :app do
+ run "rm -fr #{shared_path}/index/#{rails_env}"
+ end
+
+ desc "symlinks index folder"
+ task :symlink, :roles => :app do
+ run "mkdir -p #{shared_path}/index && rm -rf #{release_path}/index && ln -nfs #{shared_path}/index #{release_path}/index"
+ end
+
+ desc "Clean up old index versions"
+ task :cleanup, :roles => :app do
+ indexes = fetch(:ferret_indexes, [])
+ indexes.each do |index|
+ ferret_index_path = "#{shared_path}/index/#{rails_env}/#{index}"
+ releases = capture("ls -x #{ferret_index_path}").split.sort
+ count = 2
+ if count >= releases.length
+ logger.important "no old indexes to clean up"
+ else
+ logger.info "keeping #{count} of #{releases.length} indexes"
+ directories = (releases - releases.last(count)).map { |release|
+ File.join(ferret_index_path, release) }.join(" ")
+ sudo "rm -rf #{directories}"
+ end
+ end
+ end
+ end
+
+end
+
+after "deploy:stop", "ferret:stop"
+before "deploy:start", "ferret:start"
+
+before "deploy:restart", "ferret:stop"
+after "deploy:restart", "ferret:start"
+after "deploy:symlink", "ferret:index:symlink"
+
diff --git a/src/server/vendor/plugins/acts_as_ferret/script/ferret_daemon b/src/server/vendor/plugins/acts_as_ferret/script/ferret_daemon
new file mode 100644
index 0000000..631c4b5
--- /dev/null
+++ b/src/server/vendor/plugins/acts_as_ferret/script/ferret_daemon
@@ -0,0 +1,94 @@
+# Ferret Win32 Service Daemon, called by Win 32 service,
+# created by Herryanto Siatono <herryanto@pluitsolutions.com>
+#
+# see doc/README.win32 for usage instructions
+#
+require 'optparse'
+require 'win32/service'
+include Win32
+
+# Read options
+options = {}
+ARGV.options do |opts|
+ opts.banner = 'Usage: ferret_daemon [options]'
+ opts.on("-l", "--log FILE", "Daemon log file") {|file| options[:log] = file }
+ opts.on("-c","--console","Run Ferret server on console.") {options[:console] = true}
+ opts.on_tail("-h","--help", "Show this help message") {puts opts; exit}
+ opts.on("-e", "--environment ENV ", "Rails environment") {|env|
+ options[:environment] = env
+ ENV['RAILS_ENV'] = env
+ }
+ opts.parse!
+end
+
+require File.dirname(__FILE__) + '/../config/environment'
+
+# Ferret Win32 Service Daemon, called by Win 32 service,
+# to run on the console, use -c or --console option.
+module Ferret
+ class FerretDaemon < Daemon
+ # Standard logger to redirect STDOUT and STDERR to a log file
+ class FerretStandardLogger
+ def initialize(logger)
+ @logger = logger
+ end
+
+ def write(s)
+ @logger.info s
+ end
+ end
+
+ def initialize(options={})
+ @options = options
+
+ # initialize logger
+ if options[:log]
+ @logger = Logger.new @options[:log]
+ else
+ @logger = Logger.new RAILS_ROOT + "/log/ferret_service_#{RAILS_ENV}.log"
+ end
+
+ # redirect stout and stderr to Ferret logger if running as windows service
+ $stdout = $stderr = FerretStandardLogger.new(@logger) unless @options[:console]
+
+ log "Initializing FerretDaemon..."
+ if @options[:console]
+ self.service_init
+ self.service_main
+ end
+ end
+
+ def service_main
+ log "Service main enterred..."
+
+ while running?
+ log "Listening..."
+ sleep
+ end
+
+ log "Service main exit..."
+ end
+
+ def service_init
+ log "Starting Ferret DRb server..."
+ ActsAsFerret::Remote::Server.start
+ log "FerretDaemon started."
+ end
+
+ def service_stop
+ log "Stopping service..."
+ DRb.stop_service
+ log "FerretDaemon stopped."
+ end
+
+ def log(msg)
+ @logger.info msg
+ puts msg if @options[:console]
+ end
+ end
+end
+
+if __FILE__ == $0
+ d = Ferret::FerretDaemon.new(options)
+ d.mainloop
+end
diff --git a/src/server/vendor/plugins/acts_as_ferret/script/ferret_server b/src/server/vendor/plugins/acts_as_ferret/script/ferret_server
new file mode 100644
index 0000000..f5dbf3a
--- /dev/null
+++ b/src/server/vendor/plugins/acts_as_ferret/script/ferret_server
@@ -0,0 +1,10 @@
+#!/usr/bin/env ruby
+
+begin
+ require File.join(File.dirname(__FILE__), '../vendor/plugins/acts_as_ferret/lib/server_manager')
+rescue LoadError
+ # try the gem
+ require 'rubygems'
+ gem 'acts_as_ferret'
+ require 'server_manager'
+end
diff --git a/src/server/vendor/plugins/acts_as_ferret/script/ferret_service b/src/server/vendor/plugins/acts_as_ferret/script/ferret_service
new file mode 100644
index 0000000..6c56443
--- /dev/null
+++ b/src/server/vendor/plugins/acts_as_ferret/script/ferret_service
@@ -0,0 +1,178 @@
+# Ferret Win32 Service Daemon install script
+# created by Herryanto Siatono <herryanto@pluitsolutions.com>
+#
+# see doc/README.win32 for usage instructions
+#
+require 'optparse'
+require 'win32/service'
+include Win32
+
+module Ferret
+ # Parse and validate service command and options
+ class FerretServiceCommand
+ COMMANDS = ['install', 'remove', 'start', 'stop', 'help']
+ BANNER = "Usage: ruby script/ferret_service <command> [options]"
+
+ attr_reader :options, :command
+
+ def initialize
+ @options = {}
+ end
+
+ def valid_command?
+ COMMANDS.include?@command
+ end
+
+ def valid_options?
+ @options[:name] and !@options[:name].empty?
+ end
+
+ def print_command_list
+ puts BANNER
+ puts "\nAvailable commands:\n"
+ puts COMMANDS.map {|cmd| " - #{cmd}\n"}
+ puts "\nUse option -h for each command to help."
+ exit
+ end
+
+ def validate_options
+ errors = []
+ errors << "Service name is required." unless @options[:name]
+
+ if (errors.size > 0)
+ errors << "Error found. Use: 'ruby script/ferret_service #{@command} -h' for to get help."
+ puts errors.join("\n")
+ exit
+ end
+ end
+
+ def run(args)
+ @command = args.shift
+ @command = @command.dup.downcase if @command
+
+ # validate command and options
+ print_command_list unless valid_command? or @command == 'help'
+
+ opts_parser = create_options_parser
+ begin
+ opts_parser.parse!(args)
+ rescue OptionParser::ParseError => e
+ puts e
+ puts opts_parser
+ end
+
+ # validate required options
+ validate_options
+ end
+
+ def create_options_parser
+ opts_parser = OptionParser.new
+ opts_parser.banner = BANNER
+ opts_parser.on("-n", "--name=NAME", "Service name") {|name| @options[:name] = name }
+ opts_parser.on_tail("-t", "--trace", "Display stack trace when exception thrown") { @options[:trace] = true }
+ opts_parser.on_tail("-h", "--help", "Show this help message") { puts opts_parser; exit }
+
+ if ['install'].include?@command
+ opts_parser.on("-d", "--display=NAME", "Service display name") {|name| @options[:display] = name }
+
+ opts_parser.on("-l", "--log FILE", "Service log file") {|file| @options[:log] = file }
+ opts_parser.on("-e", "--environment ENV ", "Rails environment") { |env|
+ @options[:environment] = env
+ ENV['RAILS_ENV'] = env
+ }
+ end
+ opts_parser
+ end
+ end
+
+ # Install, Remove, Start and Stop Ferret DRb server Win32 service
+ class FerretService
+ FERRET_DAEMON = 'ferret_daemon'
+
+ def initialize
+ end
+
+ def install
+ svc = Service.new
+
+ begin
+ if Service.exists?(@options[:name])
+ puts "Service name '#{@options[:name]}' already exists."
+ return
+ end
+
+ svc.create_service do |s|
+ s.service_name = @options[:name]
+ s.display_name = @options[:display]
+ s.binary_path_name = binary_path_name
+ s.dependencies = []
+ end
+
+ svc.close
+ puts "'#{@options[:name]}' service installed."
+ rescue => e
+ handle_error(e)
+ end
+ end
+
+ def remove
+ begin
+ Service.stop(@options[:name])
+ rescue
+ end
+
+ begin
+ Service.delete(@options[:name])
+ puts "'#{@options[:name]}' service removed."
+ rescue => e
+ handle_error(e)
+ end
+ end
+
+ def start
+ begin
+ Service.start(@options[:name])
+ puts "'#{@options[:name]}' successfully started."
+ rescue => e
+ handle_error(e)
+ end
+ end
+
+ def stop
+ begin
+ Service.stop(@options[:name])
+ puts "'#{@options[:name]}' successfully stopped.\n"
+ rescue => e
+ handle_error(e)
+ end
+ end
+
+ def run(args)
+ svc_cmd = FerretServiceCommand.new
+ svc_cmd.run(args)
+ @options = svc_cmd.options
+ self.send(svc_cmd.command.to_sym)
+ end
+
+ protected
+ def handle_error(e)
+ if @options[:trace]
+ raise e
+ else
+ puts e
+ end
+ end
+
+ def binary_path_name
+ path = ""
+ path << "#{ENV['RUBY_HOME']}/bin/" if ENV['RUBY_HOME']
+ path << "ruby.exe "
+ path << File.expand_path("script/" + FERRET_DAEMON)
+ path << " -e #{@options[:environment]} " if @options[:environment]
+ path << " -l #{@options[:log]} " if @options[:log]
+ path
+ end
+ end
+end
+
+Ferret::FerretService.new.run(ARGV)
diff --git a/src/server/vendor/plugins/acts_as_ferret/tasks/ferret.rake b/src/server/vendor/plugins/acts_as_ferret/tasks/ferret.rake
new file mode 100644
index 0000000..5b543ac
--- /dev/null
+++ b/src/server/vendor/plugins/acts_as_ferret/tasks/ferret.rake
@@ -0,0 +1,22 @@
+namespace :ferret do
+
+ # Rebuild index task. Declare the indexes to be rebuilt with the INDEXES
+ # environment variable:
+ #
+ # INDEXES="my_model shared" rake ferret:rebuild
+ desc "Rebuild a Ferret index. Specify what model to rebuild with the INDEXES environment variable."
+ task :rebuild => :environment do
+ indexes = ENV['INDEXES'].split
+ indexes.each do |index_name|
+ start = 1.minute.ago
+ ActsAsFerret::rebuild_index index_name
+ idx = ActsAsFerret::get_index index_name
+ # update records that have changed since the rebuild started
+ idx.index_definition[:registered_models].each do |m|
+ m.records_modified_since(start).each do |object|
+ object.ferret_update
+ end
+ end
+ end
+ end
+end
|
parabuzzle/cistern
|
0421d98884f9dbf4e5d64e2bdea4a071ed176c3e
|
Working ferret ready for frontend
|
diff --git a/src/agent/logsender.rb b/src/agent/logsender.rb
index 2351df9..7f3f8dd 100644
--- a/src/agent/logsender.rb
+++ b/src/agent/logsender.rb
@@ -1,60 +1,60 @@
require 'socket'
require 'yaml'
require 'digest/md5'
include Socket::Constants
@break = "__1_BB"
@value = "__1_VV"
@checksum = "__1_CC"
def close_tx(socket)
socket.write("__1_EE")
end
def newvalbr(socket)
socket.write("__1_BB")
end
def valbr(socket)
socket.write("__1_VV")
end
def checkbr(socket)
socket.write("__1_CC")
end
socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
sockaddr = Socket.pack_sockaddr_in( 9845, '127.0.0.1' )
socket.connect( sockaddr )
#Things you need...
#data - static data
#logtype_id - logtype
#loglevel - The log level of the event
#time - the original time of the event
#payload - The dynamic data for the event (format - NAME=value)
#agent_id - The reporting agent's id
#
#The entire sting should have a checksum or it will be thrown out
event = Hash.new
-event.store("key", "111")
+event.store("authkey", "111")
event.store("data","Error log in <<<NAME>>> module")
event.store("logtype_id", 1)
event.store("loglevel_id", 2)
-event.store("time", Time.now.to_f)
+event.store("etime", Time.now.to_f)
event.store("payload", "NAME=Biff")
event.store("agent_id", 1)
e = String.new
event.each do |key, val|
e = e + key.to_s + @value + val.to_s + @break
end
puts e
e = e + @checksum + Digest::MD5.hexdigest(e) + "__1_EE"
puts e
socket.write(e)
socket.write(e)
socket.write(e)
diff --git a/src/server/app/helpers/application_helper.rb b/src/server/app/helpers/application_helper.rb
index ba22d9c..f5198fc 100644
--- a/src/server/app/helpers/application_helper.rb
+++ b/src/server/app/helpers/application_helper.rb
@@ -1,40 +1,30 @@
# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
+ #Return events array with payload field populated with full event
def rebuildevents(events)
@events = Array.new
events.each do |e|
- static = e.staticentry
- entries = e.payload.split(',')
- hash = Hash.new
- entries.each do |m|
- map = m.split('=')
- hash.store('<<<' + map[0] + '>>>',map[1])
- end
- e.payload = static.data
- hash.each do |key, val|
- e.payload = e.payload.gsub(key,val)
- end
+ e.payload = rebuildevent(e)
@events << e
end
return @events
end
- def displaylevel(level)
- if level == 0
- level = "FATAL"
- elsif level == 1
- level = "ERROR"
- elsif level == 2
- level = "WARN"
- elsif level == 3
- level = "INFO"
- elsif level == 4
- level = "DEBUG"
- else
- level = "UNKNOWN"
+ #Return a string of replaced static entry keys based on event's payload
+ def rebuildevent(e)
+ static = e.staticentry
+ entries = e.payload.split(',')
+ hash = Hash.new
+ entries.each do |m|
+ map = m.split('=')
+ hash.store('<<<' + map[0] + '>>>',map[1])
end
- return level
+ p = static.data
+ hash.each do |key, val|
+ p = p.gsub(key,val)
+ end
+ return p
end
end
diff --git a/src/server/app/models/agent.rb b/src/server/app/models/agent.rb
index 4aa2367..69a5d9a 100644
--- a/src/server/app/models/agent.rb
+++ b/src/server/app/models/agent.rb
@@ -1,11 +1,12 @@
class Agent < ActiveRecord::Base
+ acts_as_ferret :fields => [:hostname, :name, :port]
has_and_belongs_to_many :logtypes, :join_table => :agents_logtypes
has_many :events
#Validations
validates_presence_of :hostname, :port, :name
validates_format_of :hostname, :with => /([A-Z0-9-]+\.)+[A-Z]{2,4}$/i
end
diff --git a/src/server/app/models/event.rb b/src/server/app/models/event.rb
index 68749e2..e25e713 100644
--- a/src/server/app/models/event.rb
+++ b/src/server/app/models/event.rb
@@ -1,16 +1,25 @@
class Event < ActiveRecord::Base
- acts_as_ferret
+ include ApplicationHelper
+
+ acts_as_ferret :fields => ['full_event', :etime]
belongs_to :staticentry
belongs_to :agent
belongs_to :loglevel
cattr_reader :per_page
@@per_page = 20
- default_scope :order => 'time DESC'
+ default_scope :order => 'etime DESC'
#Validations
- validates_presence_of :agent_id, :loglevel_id, :time, :logtype_id
+ validates_presence_of :agent_id, :loglevel_id, :etime, :logtype_id
+
+ def full_event
+ return rebuildevent(self)
+ end
+
+
+
end
diff --git a/src/server/app/models/staticentry.rb b/src/server/app/models/staticentry.rb
index dec8bf9..bc87734 100644
--- a/src/server/app/models/staticentry.rb
+++ b/src/server/app/models/staticentry.rb
@@ -1,15 +1,17 @@
class Staticentry < ActiveRecord::Base
+ acts_as_ferret
+
has_many :events
belongs_to :logtype
has_many :loglevels, :through => :entries
#TODO: Make the id include the logtype to prevent hash collision cross logtypes
def before_create
if Staticentry.find_by_id(Digest::MD5.hexdigest(self.data + self.logtype_id.to_s)) != nil
return false
end
self.id = Digest::MD5.hexdigest(self.data + self.logtype_id.to_s)
end
end
diff --git a/src/server/db/migrate/20090721233433_create_events.rb b/src/server/db/migrate/20090721233433_create_events.rb
index e6e43dd..ef13ca3 100644
--- a/src/server/db/migrate/20090721233433_create_events.rb
+++ b/src/server/db/migrate/20090721233433_create_events.rb
@@ -1,17 +1,23 @@
class CreateEvents < ActiveRecord::Migration
def self.up
create_table :events do |t|
t.column :payload, :string
t.column :staticentry_id, :string
t.column :agent_id, :int
t.column :loglevel_id, :int
t.column :logtype_id, :int
- t.column :time, :string
+ t.column :etime, :string
t.timestamps
end
+ add_index :events, :logtype_id
+ add_index :events, :loglevel_id
+ add_index :events, :etime
+ add_index :events, :agent_id
+ add_index :events, :staticentry_id
+
end
def self.down
drop_table :events
end
end
diff --git a/src/server/db/migrate/20090730025541_create_staticentries.rb b/src/server/db/migrate/20090730025541_create_staticentries.rb
index 224b745..4777011 100644
--- a/src/server/db/migrate/20090730025541_create_staticentries.rb
+++ b/src/server/db/migrate/20090730025541_create_staticentries.rb
@@ -1,20 +1,23 @@
class CreateStaticentries < ActiveRecord::Migration
def self.up
create_table :staticentries, :id => false do |t|
t.column :id, :string, :null => false
#t.column :hash_key, :string, :null => false
t.column :logtype_id, :int
t.column :data, :text
t.timestamps
end
+ add_index :staticentries, :logtype_id
+ add_index :staticentries, :id
+
#add_index :staticentries, :hash_key
#add_index :staticentries, :agent_id
#unless ActiveRecord::Base.configurations[ENV['RAILS_ENV']]['adapter'] != 'mysql'
# execute "ALTER TABLE staticentries ADD PRIMARY KEY (id)"
#end
end
def self.down
drop_table :staticentries
end
end
diff --git a/src/server/db/migrate/20090730025548_create_agents.rb b/src/server/db/migrate/20090730025548_create_agents.rb
index 7a1a271..7d2b606 100644
--- a/src/server/db/migrate/20090730025548_create_agents.rb
+++ b/src/server/db/migrate/20090730025548_create_agents.rb
@@ -1,15 +1,17 @@
class CreateAgents < ActiveRecord::Migration
def self.up
create_table :agents do |t|
t.column :name, :string
t.column :hostname, :string
t.column :port, :string
- t.column :key, :string
+ t.column :authkey, :string
t.timestamps
end
+ add_index :agents, :name
+ add_index :agents, :hostname
end
def self.down
drop_table :agents
end
end
diff --git a/src/server/db/migrate/20090730025618_create_logtypes.rb b/src/server/db/migrate/20090730025618_create_logtypes.rb
index 5f92c15..0fb0544 100644
--- a/src/server/db/migrate/20090730025618_create_logtypes.rb
+++ b/src/server/db/migrate/20090730025618_create_logtypes.rb
@@ -1,12 +1,13 @@
class CreateLogtypes < ActiveRecord::Migration
def self.up
create_table :logtypes do |t|
t.column :name, :string
t.timestamps
end
+ add_index :logtypes, :name
end
def self.down
drop_table :logtypes
end
end
diff --git a/src/server/db/migrate/20090730154024_create_agents_logtype_map.rb b/src/server/db/migrate/20090730154024_create_agents_logtype_map.rb
index 5194900..1a3a379 100644
--- a/src/server/db/migrate/20090730154024_create_agents_logtype_map.rb
+++ b/src/server/db/migrate/20090730154024_create_agents_logtype_map.rb
@@ -1,13 +1,15 @@
class CreateAgentsLogtypeMap < ActiveRecord::Migration
def self.up
create_table :agents_logtypes do |t|
t.column :logtype_id, :int
t.column :agent_id, :int
t.timestamps
end
+ add_index :agents_logtypes, :logtype_id
+ add_index :agents_logtypes, :agent_id
end
def self.down
drop_table :events
end
end
diff --git a/src/server/db/schema.rb b/src/server/db/schema.rb
index 262337b..9c6d048 100644
--- a/src/server/db/schema.rb
+++ b/src/server/db/schema.rb
@@ -1,60 +1,77 @@
# This file is auto-generated from the current state of the database. Instead of editing this file,
# please use the migrations feature of Active Record to incrementally modify your database, and
# then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your database schema. If you need
# to create the application database on another system, you should be using db:schema:load, not running
# all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended to check this file into your version control system.
ActiveRecord::Schema.define(:version => 20090804022411) do
create_table "agents", :force => true do |t|
t.string "name"
t.string "hostname"
t.string "port"
- t.string "key"
+ t.string "authkey"
t.datetime "created_at"
t.datetime "updated_at"
end
+ add_index "agents", ["hostname"], :name => "index_agents_on_hostname"
+ add_index "agents", ["name"], :name => "index_agents_on_name"
+
create_table "agents_logtypes", :force => true do |t|
t.integer "logtype_id"
t.integer "agent_id"
t.datetime "created_at"
t.datetime "updated_at"
end
+ add_index "agents_logtypes", ["agent_id"], :name => "index_agents_logtypes_on_agent_id"
+ add_index "agents_logtypes", ["logtype_id"], :name => "index_agents_logtypes_on_logtype_id"
+
create_table "events", :force => true do |t|
t.string "payload"
t.string "staticentry_id"
t.integer "agent_id"
t.integer "loglevel_id"
t.integer "logtype_id"
- t.string "time"
+ t.string "etime"
t.datetime "created_at"
t.datetime "updated_at"
end
+ add_index "events", ["agent_id"], :name => "index_events_on_agent_id"
+ add_index "events", ["etime"], :name => "index_events_on_etime"
+ add_index "events", ["loglevel_id"], :name => "index_events_on_loglevel_id"
+ add_index "events", ["logtype_id"], :name => "index_events_on_logtype_id"
+ add_index "events", ["staticentry_id"], :name => "index_events_on_staticentry_id"
+
create_table "loglevels", :force => true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "logtypes", :force => true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
+ add_index "logtypes", ["name"], :name => "index_logtypes_on_name"
+
create_table "staticentries", :force => true do |t|
t.integer "logtype_id"
t.text "data"
t.datetime "created_at"
t.datetime "updated_at"
end
+ add_index "staticentries", ["id"], :name => "index_staticentries_on_id"
+ add_index "staticentries", ["logtype_id"], :name => "index_staticentries_on_logtype_id"
+
end
diff --git a/src/server/lib/modules/collection_server.rb b/src/server/lib/modules/collection_server.rb
index 536ccf0..a6326b9 100644
--- a/src/server/lib/modules/collection_server.rb
+++ b/src/server/lib/modules/collection_server.rb
@@ -1,73 +1,73 @@
module CollectionServer
#TODO: Checksum check should be wrapped in to an exception and then and handled that way in receive_data
#Set buffer delimiters
@@break = '__1_BB'
@@value = '__1_VV'
@@finish = '__1_EE'
def check_key(agent, key)
- if agent.key != key
+ if agent.authkey != key
return false
else
return true
end
end
#Write a log entry
def log_entry(line)
raw = line.split(@@break)
map = Hash.new
raw.each do |keys|
parts = keys.split(@@value)
map.store(parts[0],parts[1])
end
static = Logtype.find(map['logtype_id']).staticentries.new
static.data = map['data']
static.save
static = Staticentry.find_by_id(Digest::MD5.hexdigest(map['data'] + map['logtype_id'].to_s))
event = static.events.new
- event.time = map['time']
+ event.etime = map['etime']
event.loglevel_id = map['loglevel_id']
event.payload = map['payload']
event.logtype_id = map['logtype_id']
event.agent_id = map['agent_id']
- if check_key(Agent.find(map['agent_id']), map['key'])
+ if check_key(Agent.find(map['agent_id']), map['authkey'])
event.save
else
- ActiveRecord::Base.logger.debug "Event dropped -- invalid agent key sent"
+ ActiveRecord::Base.logger.debug "Event dropped -- invalid agent authkey sent"
end
port, ip = Socket.unpack_sockaddr_in(get_peername)
host = Socket.getaddrinfo(ip, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME)[0][2]
ActiveRecord::Base.logger.debug "New event logged from #{host} \n -- Log data: #{line}"
end
#Do this when a connection is initialized
def post_init
port, ip = Socket.unpack_sockaddr_in(get_peername)
host = Socket.getaddrinfo(ip, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME)[0][2]
ActiveRecord::Base.logger.info "-- Collector connection established from #{host}"
end
#Do this when data is received
def receive_data(data)
(@buffer ||= BufferedTokenizer.new(delimiter = "__1_EE")).extract(data).each do |line|
if line.valid?
log_entry(line)
else
port, ip = Socket.unpack_sockaddr_in(get_peername)
host = Socket.getaddrinfo(ip, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME)[0][2]
ActiveRecord::Base.logger.error "Dropped log entry from #{host} - checksum invalid"
end
end
end
#Do this when a connection is closed by a peer
def unbind
ActiveRecord::Base.logger.info "-- Collector connection closed by a peer"
end
end
\ No newline at end of file
|
parabuzzle/cistern
|
e53f92ebf91b5be0dbb87c3332508cda7f75bf55
|
Started on ferret integration
|
diff --git a/.gitignore b/.gitignore
index 41bf3c2..fe383b9 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,6 +1,7 @@
*.log
*.pid
*.sqlite3
src/server/config/database.yml
src/server/config/daemons.yml
src/server/config/collectors.yml
+src/server/index
diff --git a/src/server/app/models/event.rb b/src/server/app/models/event.rb
index 6c00a56..68749e2 100644
--- a/src/server/app/models/event.rb
+++ b/src/server/app/models/event.rb
@@ -1,14 +1,16 @@
class Event < ActiveRecord::Base
+ acts_as_ferret
+
belongs_to :staticentry
belongs_to :agent
belongs_to :loglevel
cattr_reader :per_page
@@per_page = 20
default_scope :order => 'time DESC'
#Validations
validates_presence_of :agent_id, :loglevel_id, :time, :logtype_id
end
diff --git a/src/server/config/environment.rb b/src/server/config/environment.rb
index dfff859..e0f5aac 100644
--- a/src/server/config/environment.rb
+++ b/src/server/config/environment.rb
@@ -1,43 +1,44 @@
# Be sure to restart your server when you modify this file
# Specifies gem version of Rails to use when vendor/rails is not present
RAILS_GEM_VERSION = '2.3.3' unless defined? RAILS_GEM_VERSION
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
Rails::Initializer.run do |config|
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Add additional load paths for your own custom dirs
# config.load_paths += %W( #{RAILS_ROOT}/extras )
# Specify gems that this application depends on and have them installed with rake gems:install
# config.gem "bj"
# config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
# config.gem "sqlite3-ruby", :lib => "sqlite3"
# config.gem "aws-s3", :lib => "aws/s3"
config.gem "eventmachine"
config.gem "will_paginate"
+ config.gem "acts_as_ferret"
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Skip frameworks you're not going to use. To use Rails without a database,
# you must remove the Active Record framework.
# config.frameworks -= [ :active_record, :active_resource, :action_mailer ]
# Activate observers that should always be running
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names.
config.time_zone = 'UTC'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')]
# config.i18n.default_locale = :de
end
\ No newline at end of file
diff --git a/src/server/config/ferret_server.yml b/src/server/config/ferret_server.yml
new file mode 100644
index 0000000..402e54e
--- /dev/null
+++ b/src/server/config/ferret_server.yml
@@ -0,0 +1,24 @@
+# configuration for the acts_as_ferret DRb server
+# host: where to reach the DRb server (used by application processes to contact the server)
+# port: which port the server should listen on
+# socket: where the DRb server should create the socket (absolute path), this setting overrides host:port configuration
+# pid_file: location of the server's pid file (relative to RAILS_ROOT)
+# log_file: log file (default: RAILS_ROOT/log/ferret_server.log
+# log_level: log level for the server's logger
+production:
+ host: localhost
+ port: 9010
+ pid_file: log/ferret.pid
+ log_file: log/ferret_server.log
+ log_level: warn
+
+# aaf won't try to use the DRb server in environments that are not
+# configured here.
+#development:
+# host: localhost
+# port: 9010
+# pid_file: log/ferret.pid
+#test:
+# host: localhost
+# port: 9009
+# pid_file: log/ferret.pid
diff --git a/src/server/script/ferret_server b/src/server/script/ferret_server
new file mode 100755
index 0000000..f5dbf3a
--- /dev/null
+++ b/src/server/script/ferret_server
@@ -0,0 +1,10 @@
+#!/usr/bin/env ruby
+
+begin
+ require File.join(File.dirname(__FILE__), '../vendor/plugins/acts_as_ferret/lib/server_manager')
+rescue LoadError
+ # try the gem
+ require 'rubygems'
+ gem 'acts_as_ferret'
+ require 'server_manager'
+end
|
parabuzzle/cistern
|
1511cb32613d4fac5e502e2901e9b0d2f915614f
|
working on the agent controls for the frontend
|
diff --git a/src/server/app/controllers/agents_controller.rb b/src/server/app/controllers/agents_controller.rb
index 389b744..8cdb3b2 100644
--- a/src/server/app/controllers/agents_controller.rb
+++ b/src/server/app/controllers/agents_controller.rb
@@ -1,19 +1,65 @@
class AgentsController < ApplicationController
def index
@title = "Agents"
@agents = Agent.paginate :all, :per_page => params[:perpage], :page => params[:page]
end
def show
@agent = Agent.find(params[:id])
@title = "All Events for #{@agent.name}"
if params[:logtype].nil?
@event = @agent.events.paginate :all, :per_page => params[:perpage], :page => params[:page]
else
@event = @agent.events.paginate :all, :per_page => params[:perpage], :page => params[:page], :conditions => "logtype_id = '#{params[:logtype]}'"
end
@events = rebuildevents(@event)
end
+ def new
+ if request.post?
+ @agent = Agent.new(params[:agent])
+ @agent.key = Digest::MD5.hexdigest(@agent.hostname + Time.now.to_s)
+ if @agent.save
+ flash[:notice] = "Agent #{@agent.name} added"
+ redirect_to :action => "index"
+ else
+ flash[:error] = "There were errors creating your agent"
+ end
+ else
+ @title = "Create New Agent"
+ end
+ end
+
+ def edit
+ @agent = Agent.find(params[:id])
+ if request.post?
+ @agent.update_attributes(params[:agent])
+ if @agent.save
+ flash[:notice] = "Agent #{@agent.name} updated"
+ redirect_to :action => "index"
+ else
+ flash[:error] = "There were errors updating your agent"
+ end
+ else
+ @title = "Edit #{@agent.name}"
+ end
+ end
+
+ def delete
+ @agent = params[:id]
+ if request.post?
+ if @agent.destroy
+ flash[:notice] = "Agent deleted"
+ redirect_to :action => "index"
+ else
+ flash[:error] = "Error trying to delete agent"
+ redirect_to :action => "index"
+ end
+ else
+ flash[:error] = "Poking around is never a good idea"
+ redirect_to :action => "index"
+ end
+ end
+
end
diff --git a/src/server/app/models/agent.rb b/src/server/app/models/agent.rb
index ea89f0c..4aa2367 100644
--- a/src/server/app/models/agent.rb
+++ b/src/server/app/models/agent.rb
@@ -1,11 +1,11 @@
class Agent < ActiveRecord::Base
has_and_belongs_to_many :logtypes, :join_table => :agents_logtypes
has_many :events
#Validations
- validates_presence_of :hostname, :port
+ validates_presence_of :hostname, :port, :name
validates_format_of :hostname, :with => /([A-Z0-9-]+\.)+[A-Z]{2,4}$/i
end
diff --git a/src/server/app/views/agents/edit.rhtml b/src/server/app/views/agents/edit.rhtml
new file mode 100644
index 0000000..b065695
--- /dev/null
+++ b/src/server/app/views/agents/edit.rhtml
@@ -0,0 +1,30 @@
+<h1>Edit <%=@agent.name%></h1>
+<%= error_messages_for 'agent' %>
+<div id="form">
+
+ <table width="100%">
+ <% form_for :agent do |f|%>
+ <tr>
+ <td>Name:</td>
+ <td align="right"><%= f.text_field :name, :class => "fbox"%></td>
+ </tr>
+ <tr>
+ <td>Hostname:</td>
+ <td align="right"><%= f.text_field :hostname, :class => "fbox"%></td>
+ </tr>
+ <tr>
+ <td>Port:</td>
+ <td align="right"><%= f.text_field :port, :class => "fbox"%></td>
+ </tr>
+ <tr>
+ <td>Key:</td>
+ <td align="right"><%= f.text_field :key, :class => "fbox"%></td>
+ </tr>
+ <tr>
+ <td><%= submit_tag "Update Agent", :class => "submitbutton" %></td>
+ <td></td>
+ </tr>
+ <%end%>
+ </table>
+
+</div>
\ No newline at end of file
diff --git a/src/server/app/views/agents/index.rhtml b/src/server/app/views/agents/index.rhtml
index bb8821e..852dd98 100644
--- a/src/server/app/views/agents/index.rhtml
+++ b/src/server/app/views/agents/index.rhtml
@@ -1,10 +1,10 @@
<h1>Agents</h1>
<ul>
<% for agent in @agents do%>
- <li><%=link_to(agent.name, :action => 'show', :id => agent.id)%> [<%=agent.hostname%>] :: <%= agent.events.count%> total events</li>
+ <li><%=link_to(agent.name, :action => 'show', :id => agent.id)%> [<%=agent.hostname%>] <%=link_to("edit", :action => 'edit', :id => agent.id)%> :: <%= agent.events.count%> total events</li>
<%end%>
</ul>
<div class="pagination">
<%= will_paginate @event %>
</div>
\ No newline at end of file
diff --git a/src/server/app/views/agents/new.rhtml b/src/server/app/views/agents/new.rhtml
new file mode 100644
index 0000000..da41b64
--- /dev/null
+++ b/src/server/app/views/agents/new.rhtml
@@ -0,0 +1,26 @@
+<h1>Create a New Agent</h1>
+<%= error_messages_for 'agent' %>
+<div id="form">
+
+ <table width="100%">
+ <% form_for :agent do |f|%>
+ <tr>
+ <td>Name:</td>
+ <td align="right"><%= f.text_field :name, :class => "fbox"%></td>
+ </tr>
+ <tr>
+ <td>Hostname:</td>
+ <td align="right"><%= f.text_field :hostname, :class => "fbox"%></td>
+ </tr>
+ <tr>
+ <td>Port:</td>
+ <td align="right"><%= f.text_field :port, :class => "fbox", :value => "9845"%></td>
+ </tr>
+ <tr>
+ <td><%= submit_tag "Add Agent", :class => "submitbutton" %></td>
+ <td></td>
+ </tr>
+ <%end%>
+ </table>
+
+</div>
\ No newline at end of file
diff --git a/src/server/app/views/layouts/application.rhtml b/src/server/app/views/layouts/application.rhtml
index 9423acf..becb8c7 100644
--- a/src/server/app/views/layouts/application.rhtml
+++ b/src/server/app/views/layouts/application.rhtml
@@ -1,74 +1,78 @@
<%starttime = Time.now.to_f %>
<!DOCTYPE HTML PUBLIC "!//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Cistern :: <%= @title %></title>
<%= stylesheet_link_tag "main" %>
<%= javascript_include_tag "jquery.min"%>
<%= javascript_include_tag "application"%>
</head>
<body>
<div id="header">
<div id="logo">Cistern</div>
<div id="search ">
Search all Events
<% form_for :search do |form| %>
<div><%= form.text_field :data, :size => 20, :class => "searchbox" %></div>
<div class="adendem">advanced</div>
<%end%>
</div>
</div> <!-- header -->
<div id="container">
<div id="topnav">
<%= link_to("Events", :controller => "events", :action => "index")%> <%= link_to("Agents", :controller => "agents", :action => "index")%> <%= link_to("Logtypes", :controller => "logtypes", :action => "index")%>
</div>
<div id="main">
-
-
+ <% if flash[:notice]%>
+ <div id="notice"><%=flash[:notice]%></div>
+ <%end%>
+ <%if flash[:error]%>
+ <div id="error"><%=flash[:error]%></div>
+ <%end%>
<%= @content_for_layout %>
</div> <!-- main -->
<div id="footer">
Copyright © 2009 Mike Heijmans
<div class="adendum">powered by <a href="http://parabuzzle.github.com/cistern">Cistern</a></div>
</div> <!-- footer -->
<% if ENV["RAILS_ENV"] == "development" #call this block if in dev mode %>
<!-- Dev stuff -->
<div id="debug">
<a href='#' onclick="$('#params_debug_info').toggle();return false">params</a> |
<a href='#' onclick="$('#session_debug_info').toggle();return false">session</a> |
<a href='#' onclick="$('#env_debug_info').toggle();return false">env</a> |
<a href='#' onclick="$('#request_debug_info').toggle();return false">request</a>
<fieldset id="params_debug_info" class="debug_info" style="display:none">
<legend>params</legend>
<%= debug(params) %>
</fieldset>
<fieldset id="session_debug_info" class="debug_info" style="display:none">
<legend>session</legend>
<%= debug(session) %>
</fieldset>
<fieldset id="env_debug_info" class="debug_info" style="display:none">
<legend>env</legend>
<%= debug(request.env) %>
</fieldset>
<fieldset id="request_debug_info" class="debug_info" style="display:none">
<legend>request</legend>
<%= debug(request) %>
</fieldset>
</div>
<!-- end Dev mode only stuff -->
<% end %>
</div> <!-- container -->
</body>
</html>
<% rtime = Time.now.to_f - starttime%>
<% if ENV["RAILS_ENV"] == "development"%>
<%= [rtime*1000].to_s.to_i %> ms
<%else%>
<!-- <%= rtime*1000 %> -->
<%end%>
\ No newline at end of file
diff --git a/src/server/public/stylesheets/main.css b/src/server/public/stylesheets/main.css
index b8bf9bb..2c5ebf4 100644
--- a/src/server/public/stylesheets/main.css
+++ b/src/server/public/stylesheets/main.css
@@ -1,132 +1,175 @@
body {
background: #fff;
color: #000;
margin: 0px;
padding: 0px;
color: #333;
font-weight:bold;
font-family: serif;
}
a {
text-decoration: none;
color: #660033;
}
a:hover {
background: #000033;
color: #fff;
padding: 2px;
}
#container {
padding: 0px;
margin: auto;
width: 900px;
}
#header {
width: 100%;
margin: 0px;
height: 95px;
background: #333;
border-bottom: solid 6px #000;
color:#fff;
}
#logo {
position: absolute;
padding-top: 20px;
padding-left: 45px;
font-weight:bold;
font-size: 55px;
color: #fff;
}
#search {
text-align: right;
padding-top: 20px;
padding-right: 50px;
}
.searchbox {
background: #663366;
border: 1px solid #000;
color: #fff;
font-size: 20px;
padding: 2px;
font-weight: none;
}
#eventlist {
min-height: 350px;
_height: 350px;
}
#topnav a {
background: #000;
padding: 4px;
padding-bottom: 4px;
padding-left: 6px;
padding-right: 6px;
color: #fff;
border-left: solid 2px #000033;
border-right: solid 2px #000033;
border-bottom: solid 2px #000033;
}
#topnav a:hover {
background: #666;
padding: 4px;
padding-bottom: 4px;
padding-left: 6px;
padding-right: 6px;
color: #fff;
border-left: solid 2px #000033;
border-right: solid 2px #000033;
border-bottom: solid 2px #000033;
}
.topnav {
background: #666;
padding: 2px;
padding-bottom: 4px;
padding-left: 6px;
padding-right: 6px;
color: #fff;
border-left: solid 2px #000033;
border-right: solid 2px #000033;
border-bottom: solid 2px #000033;
}
#topnav {
font-size: 20px;
padding: 2px;
padding-bottom: 4px;
padding-left: 6px;
padding-right: 6px;
color: #fff;
}
#main {
min-height: 400px;
_height: 400px; /* IE min-height hack */
}
#footer {
text-align: center;
width: 900px;
border-top: 2px solid #000;
padding-top: 15px;
}
+#notice {
+ margin-top: 10px;
+ width: 100%;
+ background: #09F;
+ color: #000;
+ padding: 10px;
+ border: 1px solid #333;
+}
+#error {
+ margin-top: 10px;
+ width: 100%;
+ background: #F00;
+ color: #000;
+ padding: 10px;
+ border: 1px solid #333;
+}
+
+#form {
+ width: 350px;
+ margin: auto;
+}
+.submitbutton {
+ background: #660033;
+ color: #fff;
+ border: 3px solid #000;
+ padding: 6px;
+}
+.fbox {
+ background: #ffff55;
+ border: 1px solid #333;
+ padding: 2px;
+}
+
.clear {
clear:both;
}
.adendem {
font-size: 14px;
font-weight: normal;
}
.in20 {
padding-left: 20px;
padding-right: 20px;
-}
\ No newline at end of file
+}
+.errorExplanation {
+ width: 800px;
+ margin: auto;
+ padding: 3px;
+ padding-left: 10px;
+ padding-right: 10px;
+ background: #ffff55;
+ border: 1px solid #333;
+ margin-bottom: 10px;
+}
|
parabuzzle/cistern
|
3b9f50bea0b6791e10ced05ecc732fbc5ec030b4
|
Changed the frontend to support loglevel schema change
|
diff --git a/src/server/app/controllers/agents_controller.rb b/src/server/app/controllers/agents_controller.rb
index a0eb85a..389b744 100644
--- a/src/server/app/controllers/agents_controller.rb
+++ b/src/server/app/controllers/agents_controller.rb
@@ -1,19 +1,19 @@
class AgentsController < ApplicationController
def index
@title = "Agents"
@agents = Agent.paginate :all, :per_page => params[:perpage], :page => params[:page]
end
def show
@agent = Agent.find(params[:id])
@title = "All Events for #{@agent.name}"
if params[:logtype].nil?
@event = @agent.events.paginate :all, :per_page => params[:perpage], :page => params[:page]
else
- @event = @agent.events.paginate :all, :per_page => params[:perpage], :page => params[:page], :conditions => "logtype_id == '#{params[:logtype]}'"
+ @event = @agent.events.paginate :all, :per_page => params[:perpage], :page => params[:page], :conditions => "logtype_id = '#{params[:logtype]}'"
end
@events = rebuildevents(@event)
end
end
diff --git a/src/server/app/views/agents/show.rhtml b/src/server/app/views/agents/show.rhtml
index 4f1b3e9..f3874cc 100644
--- a/src/server/app/views/agents/show.rhtml
+++ b/src/server/app/views/agents/show.rhtml
@@ -1,37 +1,37 @@
<h1>All Events for <%=@agent.name%></h1>
<div id="filter">
<% if params[:logtype]%>
Current filter: <%= Logtype.find(params[:logtype]).name%>
<%else%>
Filter by logtype:
<% for type in @agent.logtypes.all do %>
<%= link_to( type.name, :logtype => type.id, :withepoch => params[:withepoch] )%>
<%end%>
<%end%>
<div class="adendem">
<%= link_to("Clear filter", :logtype => nil, :withepoch => params[:withepoch])%>
</div>
</div>
<div id="eventlist">
<ul>
<% for event in @events do %>
- <li><%= if params[:withepoch] then event.time else Time.at(event.time.to_f) end %> : <%= displaylevel(event.loglevel)%> <%=event.payload%></li>
+ <li><%= if params[:withepoch] then event.time else Time.at(event.time.to_f) end %> : <%= event.loglevel.name%> <%=event.payload%></li>
<%end%>
</ul>
</div>
<div class="pagination">
<%= will_paginate @event %>
</div>
<div class="adendem">
Records per page:
<%=link_to "20", :withepoch => params[:withepoch], :page => 1, :perpage => "20" %> |
<%=link_to "50", :withepoch => params[:withepoch], :page => 1, :perpage => "50" %> |
<%=link_to "100", :withepoch => params[:withepoch], :page => 1, :perpage => "100" %> |
<%=link_to "200", :withepoch => params[:withepoch], :page => 1, :perpage => "200" %>
</div>
<%if params[:withepoch]%>
<div class="adendem"><%=link_to "show regular time", :withepoch => nil, :page => params[:page], :perpage => params[:perpage], :logtype => params[:logtype] %></div>
<%else%>
<div class="adendem"><%=link_to "show epoch time", :withepoch => 1, :page => params[:page], :perpage => params[:perpage], :logtype => params[:logtype] %></div>
<%end%>
\ No newline at end of file
diff --git a/src/server/app/views/events/show.rhtml b/src/server/app/views/events/show.rhtml
index c4fef92..dfad149 100644
--- a/src/server/app/views/events/show.rhtml
+++ b/src/server/app/views/events/show.rhtml
@@ -1,23 +1,23 @@
<h1>All Events</h1>
<ul>
<% for event in @events do %>
- <li><%= if params[:withepoch] then event.time else Time.at(event.time.to_f) end %> : <%= displaylevel(event.loglevel)%> <%=event.payload%></li>
+ <li><%= if params[:withepoch] then event.time else Time.at(event.time.to_f) end %> : <%= event.loglevel.name%> <%=event.payload%></li>
<%end%>
</ul>
<div class="pagination">
<%= will_paginate @event %>
</div>
<div class="adendem">
Records per page:
<%=link_to "20", :withepoch => params[:withepoch], :page => 1, :perpage => "20" %> |
<%=link_to "50", :withepoch => params[:withepoch], :page => 1, :perpage => "50" %> |
<%=link_to "100", :withepoch => params[:withepoch], :page => 1, :perpage => "100" %> |
<%=link_to "200", :withepoch => params[:withepoch], :page => 1, :perpage => "200" %>
</div>
<%if params[:withepoch]%>
<div class="adendem"><%=link_to "show regular time", :withepoch => nil, :page => params[:page], :perpage => params[:perpage] %></div>
<%else%>
<div class="adendem"><%=link_to "show epoch time", :withepoch => 1, :page => params[:page], :perpage => params[:perpage] %></div>
<%end%>
diff --git a/src/server/app/views/logtypes/show.rhtml b/src/server/app/views/logtypes/show.rhtml
index 1c1b0e8..b72325e 100644
--- a/src/server/app/views/logtypes/show.rhtml
+++ b/src/server/app/views/logtypes/show.rhtml
@@ -1,24 +1,24 @@
<h1>All Events for <%=@logtype.name%></h1>
<div id="eventlist">
<ul>
<% for event in @events do %>
- <li><%= if params[:withepoch] then event.time else Time.at(event.time.to_f) end %> : <%= displaylevel(event.loglevel)%> <%=event.payload%></li>
+ <li><%= event.agent.name %> : <%= if params[:withepoch] then event.time else Time.at(event.time.to_f) end %> : <%= event.loglevel.name %> <%=event.payload%></li>
<%end%>
</ul>
</div>
<div class="pagination">
<%= will_paginate @event %>
</div>
<div class="adendem">
Records per page:
<%=link_to "20", :withepoch => params[:withepoch], :page => 1, :perpage => "20" %> |
<%=link_to "50", :withepoch => params[:withepoch], :page => 1, :perpage => "50" %> |
<%=link_to "100", :withepoch => params[:withepoch], :page => 1, :perpage => "100" %> |
<%=link_to "200", :withepoch => params[:withepoch], :page => 1, :perpage => "200" %>
</div>
<%if params[:withepoch]%>
<div class="adendem"><%=link_to "show regular time", :withepoch => nil, :page => params[:page], :perpage => params[:perpage] %></div>
<%else%>
<div class="adendem"><%=link_to "show epoch time", :withepoch => 1, :page => params[:page], :perpage => params[:perpage] %></div>
<%end%>
\ No newline at end of file
|
parabuzzle/cistern
|
2a4b6aef7b1f2b0e8f1db7f7de94b20ebe5ecb88
|
Pulled loglevel out of event and made a table for it. This allows for filtering by loglevel in the frontend
|
diff --git a/src/server/app/models/event.rb b/src/server/app/models/event.rb
index 81c3b09..6c00a56 100644
--- a/src/server/app/models/event.rb
+++ b/src/server/app/models/event.rb
@@ -1,13 +1,14 @@
class Event < ActiveRecord::Base
belongs_to :staticentry
belongs_to :agent
+ belongs_to :loglevel
cattr_reader :per_page
@@per_page = 20
default_scope :order => 'time DESC'
#Validations
- validates_presence_of :agent_id, :loglevel, :time, :logtype_id
+ validates_presence_of :agent_id, :loglevel_id, :time, :logtype_id
end
diff --git a/src/server/app/models/loglevel.rb b/src/server/app/models/loglevel.rb
new file mode 100644
index 0000000..343dfb7
--- /dev/null
+++ b/src/server/app/models/loglevel.rb
@@ -0,0 +1,6 @@
+class Loglevel < ActiveRecord::Base
+ has_many :events
+
+ validates_presence_of :name
+
+end
diff --git a/src/server/app/models/staticentry.rb b/src/server/app/models/staticentry.rb
index 13b7720..dec8bf9 100644
--- a/src/server/app/models/staticentry.rb
+++ b/src/server/app/models/staticentry.rb
@@ -1,14 +1,15 @@
class Staticentry < ActiveRecord::Base
has_many :events
belongs_to :logtype
+ has_many :loglevels, :through => :entries
#TODO: Make the id include the logtype to prevent hash collision cross logtypes
def before_create
if Staticentry.find_by_id(Digest::MD5.hexdigest(self.data + self.logtype_id.to_s)) != nil
return false
end
self.id = Digest::MD5.hexdigest(self.data + self.logtype_id.to_s)
end
end
diff --git a/src/server/db/migrate/20090721233433_create_events.rb b/src/server/db/migrate/20090721233433_create_events.rb
index 8970954..e6e43dd 100644
--- a/src/server/db/migrate/20090721233433_create_events.rb
+++ b/src/server/db/migrate/20090721233433_create_events.rb
@@ -1,16 +1,17 @@
class CreateEvents < ActiveRecord::Migration
def self.up
create_table :events do |t|
t.column :payload, :string
t.column :staticentry_id, :string
t.column :agent_id, :int
- t.column :loglevel, :int
+ t.column :loglevel_id, :int
+ t.column :logtype_id, :int
t.column :time, :string
t.timestamps
end
end
def self.down
drop_table :events
end
end
diff --git a/src/server/db/migrate/20090803050441_add_logtype_to_events.rb b/src/server/db/migrate/20090803050441_add_logtype_to_events.rb
deleted file mode 100644
index a53e794..0000000
--- a/src/server/db/migrate/20090803050441_add_logtype_to_events.rb
+++ /dev/null
@@ -1,10 +0,0 @@
-class AddLogtypeToEvents < ActiveRecord::Migration
- def self.up
- add_column :events, :logtype_id, :int
- end
-
- def self.down
- remove_column :events, :logtype_id
- end
-end
-
diff --git a/src/server/db/migrate/20090804022411_create_loglevels.rb b/src/server/db/migrate/20090804022411_create_loglevels.rb
new file mode 100644
index 0000000..8a355fc
--- /dev/null
+++ b/src/server/db/migrate/20090804022411_create_loglevels.rb
@@ -0,0 +1,18 @@
+class CreateLoglevels < ActiveRecord::Migration
+ def self.up
+ create_table :loglevels do |t|
+ t.column :name, :string
+ t.timestamps
+ end
+ Loglevel.create :name => "FATAL", :id => 1
+ Loglevel.create :name => "ERROR", :id => 2
+ Loglevel.create :name => "WARN", :id => 3
+ Loglevel.create :name => "INFO", :id => 4
+ Loglevel.create :name => "DEBUG", :id => 5
+ Loglevel.create :name => "UNKNOWN", :id => 6
+ end
+
+ def self.down
+ drop_table :loglevels
+ end
+end
diff --git a/src/server/db/schema.rb b/src/server/db/schema.rb
index 5b4cb52..262337b 100644
--- a/src/server/db/schema.rb
+++ b/src/server/db/schema.rb
@@ -1,54 +1,60 @@
# This file is auto-generated from the current state of the database. Instead of editing this file,
# please use the migrations feature of Active Record to incrementally modify your database, and
# then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your database schema. If you need
# to create the application database on another system, you should be using db:schema:load, not running
# all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended to check this file into your version control system.
-ActiveRecord::Schema.define(:version => 20090803050441) do
+ActiveRecord::Schema.define(:version => 20090804022411) do
create_table "agents", :force => true do |t|
t.string "name"
t.string "hostname"
t.string "port"
t.string "key"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "agents_logtypes", :force => true do |t|
t.integer "logtype_id"
t.integer "agent_id"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "events", :force => true do |t|
t.string "payload"
t.string "staticentry_id"
t.integer "agent_id"
- t.integer "loglevel"
+ t.integer "loglevel_id"
+ t.integer "logtype_id"
t.string "time"
t.datetime "created_at"
t.datetime "updated_at"
- t.integer "logtype_id"
+ end
+
+ create_table "loglevels", :force => true do |t|
+ t.string "name"
+ t.datetime "created_at"
+ t.datetime "updated_at"
end
create_table "logtypes", :force => true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "staticentries", :force => true do |t|
t.integer "logtype_id"
t.text "data"
t.datetime "created_at"
t.datetime "updated_at"
end
end
diff --git a/src/server/test/fixtures/loglevels.yml b/src/server/test/fixtures/loglevels.yml
new file mode 100644
index 0000000..5bf0293
--- /dev/null
+++ b/src/server/test/fixtures/loglevels.yml
@@ -0,0 +1,7 @@
+# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
+
+# one:
+# column: value
+#
+# two:
+# column: value
diff --git a/src/server/test/unit/event_test.rb b/src/server/test/unit/event_test.rb
index 4157f0f..35b61dd 100644
--- a/src/server/test/unit/event_test.rb
+++ b/src/server/test/unit/event_test.rb
@@ -1,64 +1,64 @@
require 'test_helper'
class EventTest < ActiveSupport::TestCase
# Replace this with your real tests.
test "the truth" do
assert true
end
test "new event" do
e = Event.new
e.payload = "agent3"
e.staticentry_id = "85d229332bf72d4539372498264300d6"
e.agent_id = 1
- e.loglevel = 0
+ e.loglevel_id = 1
e.logtype_id = 1
e.time = 1249062105.06911
assert e.save
end
test "invalid new event - missing agent_id" do
e = Event.new
e.payload = "agent3"
e.staticentry_id = "85d229332bf72d4539372498264300d6"
e.agent_id = nil
- e.loglevel = 0
+ e.loglevel_id = 1
e.logtype_id = 1
e.time = 1249062105.06911
assert !e.save
end
test "invalid new event - missing loglevel" do
e = Event.new
e.payload = "agent3"
e.staticentry_id = "85d229332bf72d4539372498264300d6"
e.agent_id = 1
- e.loglevel = nil
+ e.loglevel_id = nil
e.logtype_id = 1
e.time = 1249062105.06911
assert !e.save
end
test "invalid new event - missing time" do
e = Event.new
e.payload = "agent3"
e.staticentry_id = "85d229332bf72d4539372498264300d6"
e.agent_id = 1
- e.loglevel = 0
+ e.loglevel_id = 1
e.time = nil
e.logtype_id = 1
assert !e.save
end
test "invalid new event - missing logtype_id" do
e = Event.new
e.payload = "agent3"
e.staticentry_id = "85d229332bf72d4539372498264300d6"
e.agent_id = 1
- e.loglevel = 0
+ e.loglevel_id = 1
e.time = 1249062105.06911
e.logtype_id = nil
assert !e.save
end
end
diff --git a/src/server/test/unit/loglevel_test.rb b/src/server/test/unit/loglevel_test.rb
new file mode 100644
index 0000000..1d92622
--- /dev/null
+++ b/src/server/test/unit/loglevel_test.rb
@@ -0,0 +1,8 @@
+require 'test_helper'
+
+class LoglevelTest < ActiveSupport::TestCase
+ # Replace this with your real tests.
+ test "the truth" do
+ assert true
+ end
+end
|
parabuzzle/cistern
|
8d3775c2caba37926aceac560e7621fcc9942ae4
|
removed config files and made example configs
|
diff --git a/.gitignore b/.gitignore
index 68931b8..41bf3c2 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,3 +1,6 @@
*.log
*.pid
*.sqlite3
+src/server/config/database.yml
+src/server/config/daemons.yml
+src/server/config/collectors.yml
diff --git a/src/server/config/collectors.yml b/src/server/config/collectors-example.yml
similarity index 65%
rename from src/server/config/collectors.yml
rename to src/server/config/collectors-example.yml
index 234890d..82dfeac 100644
--- a/src/server/config/collectors.yml
+++ b/src/server/config/collectors-example.yml
@@ -1,26 +1,17 @@
#should contain all the collector config params
#UDP log collection configuration
udpcollector:
#The UDP port to listen on
port: 22222
#The ip address to bind to
#0.0.0.0 will bind to all available interfaces
listenip: 0.0.0.0
#TCP log collection configuration
tcpcollector:
#The TCP port to listen on
port: 9845
#The ip address to bind to
#0.0.0.0 will bind to all available interfaces
listenip: 0.0.0.0
-
-#Admin server configuration
-# -- used for agent checkin and configuration
-commandlistener:
- #The TCP port to listen on
- port: 9850
- #The ip address to bind to
- #0.0.0.0 will bind to all available interfaces
- listenip: 0.0.0.0
\ No newline at end of file
diff --git a/src/server/config/daemons.yml b/src/server/config/daemons-example.yml
similarity index 100%
rename from src/server/config/daemons.yml
rename to src/server/config/daemons-example.yml
diff --git a/src/server/config/database.yml b/src/server/config/database-example.yml
similarity index 66%
rename from src/server/config/database.yml
rename to src/server/config/database-example.yml
index 427ce83..8d0c205 100644
--- a/src/server/config/database.yml
+++ b/src/server/config/database-example.yml
@@ -1,24 +1,28 @@
# SQLite version 3.x
# gem install sqlite3-ruby (not necessary on OS X Leopard)
development:
- adapter: sqlite3
- database: db/development.sqlite3
+ adapter: mysql
+ database: development
pool: 5
timeout: 5000
+ user: cistern
+ password: cistern
# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
adapter: mysql
- database: cistern
+ database: test
pool: 5
- user: root
- password:
timeout: 5000
+ user: cistern
+ password: cistern
production:
- adapter: sqlite3
- database: db/development.sqlite3
+ adapter: mysql
+ database: production
pool: 5
timeout: 5000
+ user: cistern
+ password: cistern
|
parabuzzle/cistern
|
6068467a5058fc3a2fbac255dcd5112b1171afd1
|
Fixed some random bugs
|
diff --git a/src/agent/logsender.rb b/src/agent/logsender.rb
index 0b438f0..23c3b9c 100644
--- a/src/agent/logsender.rb
+++ b/src/agent/logsender.rb
@@ -1,60 +1,60 @@
require 'socket'
require 'yaml'
require 'digest/md5'
include Socket::Constants
@break = "__1_BB"
@value = "__1_VV"
@checksum = "__1_CC"
def close_tx(socket)
socket.write("__1_EE")
end
def newvalbr(socket)
socket.write("__1_BB")
end
def valbr(socket)
socket.write("__1_VV")
end
def checkbr(socket)
socket.write("__1_CC")
end
socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
sockaddr = Socket.pack_sockaddr_in( 9845, '127.0.0.1' )
socket.connect( sockaddr )
#Things you need...
#data - static data
#logtype_id - logtype
#loglevel - The log level of the event
#time - the original time of the event
#payload - The dynamic data for the event (format - NAME=value)
#agent_id - The reporting agent's id
#
#The entire sting should have a checksum or it will be thrown out
event = Hash.new
event.store("key", "123456")
event.store("data","This is a log entry for <<<NAME>>>")
event.store("logtype_id", 1)
event.store("loglevel", 0)
event.store("time", Time.now.to_f)
-event.store("payload", "NAME=TesterApp")
+event.store("payload", "NAME=Biff")
event.store("agent_id", 1)
e = String.new
event.each do |key, val|
e = e + key.to_s + @value + val.to_s + @break
end
puts e
e = e + @checksum + Digest::MD5.hexdigest(e) + "__1_EE"
puts e
socket.write(e)
socket.write(e)
socket.write(e)
diff --git a/src/server/app/models/event.rb b/src/server/app/models/event.rb
index a1036f9..81c3b09 100644
--- a/src/server/app/models/event.rb
+++ b/src/server/app/models/event.rb
@@ -1,13 +1,13 @@
class Event < ActiveRecord::Base
belongs_to :staticentry
belongs_to :agent
cattr_reader :per_page
@@per_page = 20
default_scope :order => 'time DESC'
#Validations
- validates_presence_of :agent_id, :loglevel, :time
+ validates_presence_of :agent_id, :loglevel, :time, :logtype_id
end
diff --git a/src/server/app/models/staticentry.rb b/src/server/app/models/staticentry.rb
index f449e6f..13b7720 100644
--- a/src/server/app/models/staticentry.rb
+++ b/src/server/app/models/staticentry.rb
@@ -1,14 +1,14 @@
class Staticentry < ActiveRecord::Base
has_many :events
belongs_to :logtype
#TODO: Make the id include the logtype to prevent hash collision cross logtypes
def before_create
- if Staticentry.find_by_id(Digest::MD5.hexdigest(self.data)) != nil
+ if Staticentry.find_by_id(Digest::MD5.hexdigest(self.data + self.logtype_id.to_s)) != nil
return false
end
- self.id = Digest::MD5.hexdigest(self.data)
+ self.id = Digest::MD5.hexdigest(self.data + self.logtype_id.to_s)
end
end
diff --git a/src/server/app/views/agents/show.rhtml b/src/server/app/views/agents/show.rhtml
index 7ad5d32..4f1b3e9 100644
--- a/src/server/app/views/agents/show.rhtml
+++ b/src/server/app/views/agents/show.rhtml
@@ -1,33 +1,37 @@
<h1>All Events for <%=@agent.name%></h1>
<div id="filter">
- Filter by logtype:
- <% for type in @agent.logtypes.all do %>
- <%= link_to( type.name, :logtype => type.id )%>
+ <% if params[:logtype]%>
+ Current filter: <%= Logtype.find(params[:logtype]).name%>
+ <%else%>
+ Filter by logtype:
+ <% for type in @agent.logtypes.all do %>
+ <%= link_to( type.name, :logtype => type.id, :withepoch => params[:withepoch] )%>
+ <%end%>
<%end%>
<div class="adendem">
- <%= link_to("Clear filter", :logtype => nil)%>
+ <%= link_to("Clear filter", :logtype => nil, :withepoch => params[:withepoch])%>
</div>
</div>
<div id="eventlist">
<ul>
<% for event in @events do %>
- <li><%= if params[:withepoch] then event.time else Time.at(event.time) end %> : <%= displaylevel(event.loglevel)%> <%=event.payload%></li>
+ <li><%= if params[:withepoch] then event.time else Time.at(event.time.to_f) end %> : <%= displaylevel(event.loglevel)%> <%=event.payload%></li>
<%end%>
</ul>
</div>
<div class="pagination">
<%= will_paginate @event %>
</div>
<div class="adendem">
Records per page:
<%=link_to "20", :withepoch => params[:withepoch], :page => 1, :perpage => "20" %> |
<%=link_to "50", :withepoch => params[:withepoch], :page => 1, :perpage => "50" %> |
<%=link_to "100", :withepoch => params[:withepoch], :page => 1, :perpage => "100" %> |
<%=link_to "200", :withepoch => params[:withepoch], :page => 1, :perpage => "200" %>
</div>
<%if params[:withepoch]%>
- <div class="adendem"><%=link_to "show regular time", :withepoch => nil, :page => params[:page], :perpage => params[:perpage] %></div>
+ <div class="adendem"><%=link_to "show regular time", :withepoch => nil, :page => params[:page], :perpage => params[:perpage], :logtype => params[:logtype] %></div>
<%else%>
- <div class="adendem"><%=link_to "show epoch time", :withepoch => 1, :page => params[:page], :perpage => params[:perpage] %></div>
+ <div class="adendem"><%=link_to "show epoch time", :withepoch => 1, :page => params[:page], :perpage => params[:perpage], :logtype => params[:logtype] %></div>
<%end%>
\ No newline at end of file
diff --git a/src/server/app/views/events/show.rhtml b/src/server/app/views/events/show.rhtml
index 92550a7..c4fef92 100644
--- a/src/server/app/views/events/show.rhtml
+++ b/src/server/app/views/events/show.rhtml
@@ -1,23 +1,23 @@
<h1>All Events</h1>
<ul>
<% for event in @events do %>
- <li><%= if params[:withepoch] then event.time else Time.at(event.time) end %> : <%= displaylevel(event.loglevel)%> <%=event.payload%></li>
+ <li><%= if params[:withepoch] then event.time else Time.at(event.time.to_f) end %> : <%= displaylevel(event.loglevel)%> <%=event.payload%></li>
<%end%>
</ul>
<div class="pagination">
<%= will_paginate @event %>
</div>
<div class="adendem">
Records per page:
<%=link_to "20", :withepoch => params[:withepoch], :page => 1, :perpage => "20" %> |
<%=link_to "50", :withepoch => params[:withepoch], :page => 1, :perpage => "50" %> |
<%=link_to "100", :withepoch => params[:withepoch], :page => 1, :perpage => "100" %> |
<%=link_to "200", :withepoch => params[:withepoch], :page => 1, :perpage => "200" %>
</div>
<%if params[:withepoch]%>
<div class="adendem"><%=link_to "show regular time", :withepoch => nil, :page => params[:page], :perpage => params[:perpage] %></div>
<%else%>
<div class="adendem"><%=link_to "show epoch time", :withepoch => 1, :page => params[:page], :perpage => params[:perpage] %></div>
<%end%>
diff --git a/src/server/app/views/logtypes/show.rhtml b/src/server/app/views/logtypes/show.rhtml
index ce7991d..1c1b0e8 100644
--- a/src/server/app/views/logtypes/show.rhtml
+++ b/src/server/app/views/logtypes/show.rhtml
@@ -1,24 +1,24 @@
<h1>All Events for <%=@logtype.name%></h1>
<div id="eventlist">
<ul>
<% for event in @events do %>
- <li><%= if params[:withepoch] then event.time else Time.at(event.time) end %> : <%= displaylevel(event.loglevel)%> <%=event.payload%></li>
+ <li><%= if params[:withepoch] then event.time else Time.at(event.time.to_f) end %> : <%= displaylevel(event.loglevel)%> <%=event.payload%></li>
<%end%>
</ul>
</div>
<div class="pagination">
<%= will_paginate @event %>
</div>
<div class="adendem">
Records per page:
<%=link_to "20", :withepoch => params[:withepoch], :page => 1, :perpage => "20" %> |
<%=link_to "50", :withepoch => params[:withepoch], :page => 1, :perpage => "50" %> |
<%=link_to "100", :withepoch => params[:withepoch], :page => 1, :perpage => "100" %> |
<%=link_to "200", :withepoch => params[:withepoch], :page => 1, :perpage => "200" %>
</div>
<%if params[:withepoch]%>
<div class="adendem"><%=link_to "show regular time", :withepoch => nil, :page => params[:page], :perpage => params[:perpage] %></div>
<%else%>
<div class="adendem"><%=link_to "show epoch time", :withepoch => 1, :page => params[:page], :perpage => params[:perpage] %></div>
<%end%>
\ No newline at end of file
diff --git a/src/server/db/migrate/20090721233433_create_events.rb b/src/server/db/migrate/20090721233433_create_events.rb
index efeec71..8970954 100644
--- a/src/server/db/migrate/20090721233433_create_events.rb
+++ b/src/server/db/migrate/20090721233433_create_events.rb
@@ -1,16 +1,16 @@
class CreateEvents < ActiveRecord::Migration
def self.up
create_table :events do |t|
t.column :payload, :string
t.column :staticentry_id, :string
t.column :agent_id, :int
t.column :loglevel, :int
- t.column :time, :int
+ t.column :time, :string
t.timestamps
end
end
def self.down
drop_table :events
end
end
diff --git a/src/server/db/schema.rb b/src/server/db/schema.rb
index 3a16546..5b4cb52 100644
--- a/src/server/db/schema.rb
+++ b/src/server/db/schema.rb
@@ -1,56 +1,54 @@
# This file is auto-generated from the current state of the database. Instead of editing this file,
# please use the migrations feature of Active Record to incrementally modify your database, and
# then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your database schema. If you need
# to create the application database on another system, you should be using db:schema:load, not running
# all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended to check this file into your version control system.
ActiveRecord::Schema.define(:version => 20090803050441) do
create_table "agents", :force => true do |t|
t.string "name"
t.string "hostname"
t.string "port"
t.string "key"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "agents_logtypes", :force => true do |t|
t.integer "logtype_id"
t.integer "agent_id"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "events", :force => true do |t|
t.string "payload"
t.string "staticentry_id"
t.integer "agent_id"
- t.integer "type_id"
t.integer "loglevel"
- t.integer "time"
+ t.string "time"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "logtype_id"
end
create_table "logtypes", :force => true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "staticentries", :force => true do |t|
t.integer "logtype_id"
t.text "data"
- t.integer "agent_id"
t.datetime "created_at"
t.datetime "updated_at"
end
end
diff --git a/src/server/lib/modules/collection_server.rb b/src/server/lib/modules/collection_server.rb
index f1148e1..30608b6 100644
--- a/src/server/lib/modules/collection_server.rb
+++ b/src/server/lib/modules/collection_server.rb
@@ -1,73 +1,73 @@
module CollectionServer
#TODO: Checksum check should be wrapped in to an exception and then and handled that way in receive_data
#Set buffer delimiters
@@break = '__1_BB'
@@value = '__1_VV'
@@finish = '__1_EE'
def check_key(agent, key)
if agent.key != key
return false
else
return true
end
end
#Write a log entry
def log_entry(line)
raw = line.split(@@break)
map = Hash.new
raw.each do |keys|
parts = keys.split(@@value)
map.store(parts[0],parts[1])
end
static = Logtype.find(map['logtype_id']).staticentries.new
static.data = map['data']
static.save
- static = Staticentry.find_by_id(Digest::MD5.hexdigest(map['data']))
+ static = Staticentry.find_by_id(Digest::MD5.hexdigest(map['data'] + map['logtype_id'].to_s))
event = static.events.new
event.time = map['time']
event.loglevel = map['loglevel']
event.payload = map['payload']
event.logtype_id = map['logtype_id']
event.agent_id = map['agent_id']
if check_key(Agent.find(map['agent_id']), map['key'])
event.save
else
ActiveRecord::Base.logger.debug "Event dropped -- invalid agent key sent"
end
port, ip = Socket.unpack_sockaddr_in(get_peername)
host = Socket.getaddrinfo(ip, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME)[0][2]
ActiveRecord::Base.logger.debug "New event logged from #{host} \n -- Log data: #{line}"
end
#Do this when a connection is initialized
def post_init
port, ip = Socket.unpack_sockaddr_in(get_peername)
host = Socket.getaddrinfo(ip, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME)[0][2]
ActiveRecord::Base.logger.info "-- Collector connection established from #{host}"
end
#Do this when data is received
def receive_data(data)
(@buffer ||= BufferedTokenizer.new(delimiter = "__1_EE")).extract(data).each do |line|
if line.valid?
log_entry(line)
else
port, ip = Socket.unpack_sockaddr_in(get_peername)
host = Socket.getaddrinfo(ip, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME)[0][2]
ActiveRecord::Base.logger.error "Dropped log entry from #{host} - checksum invalid"
end
end
end
#Do this when a connection is closed by a peer
def unbind
ActiveRecord::Base.logger.info "-- Collector connection closed by a peer"
end
end
\ No newline at end of file
diff --git a/src/server/test/unit/event_test.rb b/src/server/test/unit/event_test.rb
index cc9641a..4157f0f 100644
--- a/src/server/test/unit/event_test.rb
+++ b/src/server/test/unit/event_test.rb
@@ -1,49 +1,64 @@
require 'test_helper'
class EventTest < ActiveSupport::TestCase
# Replace this with your real tests.
test "the truth" do
assert true
end
test "new event" do
e = Event.new
e.payload = "agent3"
e.staticentry_id = "85d229332bf72d4539372498264300d6"
e.agent_id = 1
e.loglevel = 0
+ e.logtype_id = 1
e.time = 1249062105.06911
assert e.save
end
test "invalid new event - missing agent_id" do
e = Event.new
e.payload = "agent3"
e.staticentry_id = "85d229332bf72d4539372498264300d6"
e.agent_id = nil
e.loglevel = 0
+ e.logtype_id = 1
e.time = 1249062105.06911
assert !e.save
end
test "invalid new event - missing loglevel" do
e = Event.new
e.payload = "agent3"
e.staticentry_id = "85d229332bf72d4539372498264300d6"
e.agent_id = 1
e.loglevel = nil
+ e.logtype_id = 1
e.time = 1249062105.06911
assert !e.save
end
test "invalid new event - missing time" do
e = Event.new
e.payload = "agent3"
e.staticentry_id = "85d229332bf72d4539372498264300d6"
e.agent_id = 1
e.loglevel = 0
e.time = nil
+ e.logtype_id = 1
+ assert !e.save
+ end
+
+ test "invalid new event - missing logtype_id" do
+ e = Event.new
+ e.payload = "agent3"
+ e.staticentry_id = "85d229332bf72d4539372498264300d6"
+ e.agent_id = 1
+ e.loglevel = 0
+ e.time = 1249062105.06911
+ e.logtype_id = nil
assert !e.save
end
end
|
parabuzzle/cistern
|
38a32b724c6a15524c150953ea44f194543da6fe
|
basic log browsing is done
|
diff --git a/src/server/app/controllers/agents_controller.rb b/src/server/app/controllers/agents_controller.rb
new file mode 100644
index 0000000..a0eb85a
--- /dev/null
+++ b/src/server/app/controllers/agents_controller.rb
@@ -0,0 +1,19 @@
+class AgentsController < ApplicationController
+
+ def index
+ @title = "Agents"
+ @agents = Agent.paginate :all, :per_page => params[:perpage], :page => params[:page]
+ end
+
+ def show
+ @agent = Agent.find(params[:id])
+ @title = "All Events for #{@agent.name}"
+ if params[:logtype].nil?
+ @event = @agent.events.paginate :all, :per_page => params[:perpage], :page => params[:page]
+ else
+ @event = @agent.events.paginate :all, :per_page => params[:perpage], :page => params[:page], :conditions => "logtype_id == '#{params[:logtype]}'"
+ end
+ @events = rebuildevents(@event)
+ end
+
+end
diff --git a/src/server/app/controllers/logtypes_controller.rb b/src/server/app/controllers/logtypes_controller.rb
new file mode 100644
index 0000000..4f2cacb
--- /dev/null
+++ b/src/server/app/controllers/logtypes_controller.rb
@@ -0,0 +1,15 @@
+class LogtypesController < ApplicationController
+
+ def index
+ @title = "Logtypes"
+ @logtypes = Logtype.paginate :all, :per_page => params[:perpage], :page => params[:page]
+ end
+
+ def show
+ @logtype = Logtype.find(params[:id])
+ @title = "All Events for #{@logtype.name}"
+ @event = @logtype.events.paginate :all, :per_page => params[:perpage], :page => params[:page]
+ @events = rebuildevents(@event)
+ end
+
+end
diff --git a/src/server/app/helpers/agents_helper.rb b/src/server/app/helpers/agents_helper.rb
new file mode 100644
index 0000000..7e54438
--- /dev/null
+++ b/src/server/app/helpers/agents_helper.rb
@@ -0,0 +1,2 @@
+module AgentsHelper
+end
diff --git a/src/server/app/helpers/application_helper.rb b/src/server/app/helpers/application_helper.rb
index 294c262..ba22d9c 100644
--- a/src/server/app/helpers/application_helper.rb
+++ b/src/server/app/helpers/application_helper.rb
@@ -1,40 +1,40 @@
# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
def rebuildevents(events)
@events = Array.new
events.each do |e|
static = e.staticentry
entries = e.payload.split(',')
hash = Hash.new
entries.each do |m|
map = m.split('=')
hash.store('<<<' + map[0] + '>>>',map[1])
end
e.payload = static.data
hash.each do |key, val|
e.payload = e.payload.gsub(key,val)
end
@events << e
end
return @events
end
def displaylevel(level)
- if level = 0
+ if level == 0
level = "FATAL"
- elsif level = 1
+ elsif level == 1
level = "ERROR"
- elsif level = 2
+ elsif level == 2
level = "WARN"
- elsif level = 3
+ elsif level == 3
level = "INFO"
- elsif level = 4
+ elsif level == 4
level = "DEBUG"
else
level = "UNKNOWN"
end
return level
end
end
diff --git a/src/server/app/helpers/logtypes_helper.rb b/src/server/app/helpers/logtypes_helper.rb
new file mode 100644
index 0000000..dace775
--- /dev/null
+++ b/src/server/app/helpers/logtypes_helper.rb
@@ -0,0 +1,2 @@
+module LogtypesHelper
+end
diff --git a/src/server/app/views/agents/index.rhtml b/src/server/app/views/agents/index.rhtml
new file mode 100644
index 0000000..bb8821e
--- /dev/null
+++ b/src/server/app/views/agents/index.rhtml
@@ -0,0 +1,10 @@
+<h1>Agents</h1>
+
+<ul>
+ <% for agent in @agents do%>
+ <li><%=link_to(agent.name, :action => 'show', :id => agent.id)%> [<%=agent.hostname%>] :: <%= agent.events.count%> total events</li>
+ <%end%>
+</ul>
+<div class="pagination">
+ <%= will_paginate @event %>
+</div>
\ No newline at end of file
diff --git a/src/server/app/views/agents/show.rhtml b/src/server/app/views/agents/show.rhtml
new file mode 100644
index 0000000..7ad5d32
--- /dev/null
+++ b/src/server/app/views/agents/show.rhtml
@@ -0,0 +1,33 @@
+<h1>All Events for <%=@agent.name%></h1>
+<div id="filter">
+ Filter by logtype:
+ <% for type in @agent.logtypes.all do %>
+ <%= link_to( type.name, :logtype => type.id )%>
+ <%end%>
+ <div class="adendem">
+ <%= link_to("Clear filter", :logtype => nil)%>
+ </div>
+</div>
+<div id="eventlist">
+ <ul>
+ <% for event in @events do %>
+ <li><%= if params[:withepoch] then event.time else Time.at(event.time) end %> : <%= displaylevel(event.loglevel)%> <%=event.payload%></li>
+ <%end%>
+ </ul>
+</div>
+
+<div class="pagination">
+ <%= will_paginate @event %>
+</div>
+<div class="adendem">
+ Records per page:
+ <%=link_to "20", :withepoch => params[:withepoch], :page => 1, :perpage => "20" %> |
+ <%=link_to "50", :withepoch => params[:withepoch], :page => 1, :perpage => "50" %> |
+ <%=link_to "100", :withepoch => params[:withepoch], :page => 1, :perpage => "100" %> |
+ <%=link_to "200", :withepoch => params[:withepoch], :page => 1, :perpage => "200" %>
+</div>
+<%if params[:withepoch]%>
+ <div class="adendem"><%=link_to "show regular time", :withepoch => nil, :page => params[:page], :perpage => params[:perpage] %></div>
+<%else%>
+ <div class="adendem"><%=link_to "show epoch time", :withepoch => 1, :page => params[:page], :perpage => params[:perpage] %></div>
+<%end%>
\ No newline at end of file
diff --git a/src/server/app/views/events/index.rhtml b/src/server/app/views/events/index.rhtml
index 3f9b527..d76f684 100644
--- a/src/server/app/views/events/index.rhtml
+++ b/src/server/app/views/events/index.rhtml
@@ -1,17 +1,17 @@
<h1>Events Statistics</h1>
<div class="adendem">Select the log events you would like to see:</div>
<h2>Logtypes</h2>
<ul>
<% for type in @logtypes do%>
- <li><%= link_to(type.name, :action => 'show', :logtype => type.id)%> :: <%=type.events.count %> total events</ul>
+ <li><%= link_to(type.name, :action => 'show', :id => type.id)%> :: <%=type.events.count %> total events</ul>
<%end%>
</ul>
<h2>Agents</h2>
<ul>
<% for agent in @agents do%>
- <li><%=link_to(agent.name, :action => 'show', :agent => agent.id)%> [<%=agent.hostname%>] :: <%= agent.events.count%> total events</li>
+ <li><%=link_to(agent.name, :action => 'show', :id => agent.id)%> [<%=agent.hostname%>] :: <%= agent.events.count%> total events</li>
<%end%>
</ul>
<h3><%= link_to('Show all events', :action => 'show')%></h3>
\ No newline at end of file
diff --git a/src/server/app/views/events/show.rhtml b/src/server/app/views/events/show.rhtml
index 4c7d5a7..92550a7 100644
--- a/src/server/app/views/events/show.rhtml
+++ b/src/server/app/views/events/show.rhtml
@@ -1,23 +1,23 @@
<h1>All Events</h1>
<ul>
<% for event in @events do %>
<li><%= if params[:withepoch] then event.time else Time.at(event.time) end %> : <%= displaylevel(event.loglevel)%> <%=event.payload%></li>
<%end%>
</ul>
-<%if params[:withepoch]%>
- <div class="adendem"><%=link_to "show regular time", :withepoch => nil, :page => params[:page], :perpage => params[:perpage] %></div>
-<%else%>
- <div class="adendem"><%=link_to "show epoch time", :withepoch => 1, :page => params[:page], :perpage => params[:perpage] %></div>
-<%end%>
<div class="pagination">
<%= will_paginate @event %>
</div>
<div class="adendem">
Records per page:
<%=link_to "20", :withepoch => params[:withepoch], :page => 1, :perpage => "20" %> |
<%=link_to "50", :withepoch => params[:withepoch], :page => 1, :perpage => "50" %> |
<%=link_to "100", :withepoch => params[:withepoch], :page => 1, :perpage => "100" %> |
<%=link_to "200", :withepoch => params[:withepoch], :page => 1, :perpage => "200" %>
</div>
+<%if params[:withepoch]%>
+ <div class="adendem"><%=link_to "show regular time", :withepoch => nil, :page => params[:page], :perpage => params[:perpage] %></div>
+<%else%>
+ <div class="adendem"><%=link_to "show epoch time", :withepoch => 1, :page => params[:page], :perpage => params[:perpage] %></div>
+<%end%>
diff --git a/src/server/app/views/layouts/application.rhtml b/src/server/app/views/layouts/application.rhtml
index 5f4fb1e..9423acf 100644
--- a/src/server/app/views/layouts/application.rhtml
+++ b/src/server/app/views/layouts/application.rhtml
@@ -1,74 +1,74 @@
<%starttime = Time.now.to_f %>
<!DOCTYPE HTML PUBLIC "!//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Cistern :: <%= @title %></title>
<%= stylesheet_link_tag "main" %>
<%= javascript_include_tag "jquery.min"%>
<%= javascript_include_tag "application"%>
</head>
<body>
<div id="header">
<div id="logo">Cistern</div>
<div id="search ">
Search all Events
<% form_for :search do |form| %>
<div><%= form.text_field :data, :size => 20, :class => "searchbox" %></div>
<div class="adendem">advanced</div>
<%end%>
</div>
</div> <!-- header -->
<div id="container">
<div id="topnav">
- <%= link_to("Events", :controller => "events", :action => "index")%>
+ <%= link_to("Events", :controller => "events", :action => "index")%> <%= link_to("Agents", :controller => "agents", :action => "index")%> <%= link_to("Logtypes", :controller => "logtypes", :action => "index")%>
</div>
<div id="main">
<%= @content_for_layout %>
</div> <!-- main -->
<div id="footer">
Copyright © 2009 Mike Heijmans
<div class="adendum">powered by <a href="http://parabuzzle.github.com/cistern">Cistern</a></div>
</div> <!-- footer -->
<% if ENV["RAILS_ENV"] == "development" #call this block if in dev mode %>
<!-- Dev stuff -->
<div id="debug">
<a href='#' onclick="$('#params_debug_info').toggle();return false">params</a> |
<a href='#' onclick="$('#session_debug_info').toggle();return false">session</a> |
<a href='#' onclick="$('#env_debug_info').toggle();return false">env</a> |
<a href='#' onclick="$('#request_debug_info').toggle();return false">request</a>
<fieldset id="params_debug_info" class="debug_info" style="display:none">
<legend>params</legend>
<%= debug(params) %>
</fieldset>
<fieldset id="session_debug_info" class="debug_info" style="display:none">
<legend>session</legend>
<%= debug(session) %>
</fieldset>
<fieldset id="env_debug_info" class="debug_info" style="display:none">
<legend>env</legend>
<%= debug(request.env) %>
</fieldset>
<fieldset id="request_debug_info" class="debug_info" style="display:none">
<legend>request</legend>
<%= debug(request) %>
</fieldset>
</div>
<!-- end Dev mode only stuff -->
<% end %>
</div> <!-- container -->
</body>
</html>
<% rtime = Time.now.to_f - starttime%>
<% if ENV["RAILS_ENV"] == "development"%>
<%= [rtime*1000].to_s.to_i %> ms
<%else%>
<!-- <%= rtime*1000 %> -->
<%end%>
\ No newline at end of file
diff --git a/src/server/app/views/logtypes/index.rhtml b/src/server/app/views/logtypes/index.rhtml
new file mode 100644
index 0000000..0932b43
--- /dev/null
+++ b/src/server/app/views/logtypes/index.rhtml
@@ -0,0 +1,10 @@
+<h1>Logtypes</h1>
+
+<ul>
+ <% for type in @logtypes do%>
+ <li><%=link_to(type.name, :action => 'show', :id => type.id)%> :: <%= type.events.count%> total events</li>
+ <%end%>
+</ul>
+<div class="pagination">
+ <%= will_paginate @logtypes %>
+</div>
\ No newline at end of file
diff --git a/src/server/app/views/logtypes/show.rhtml b/src/server/app/views/logtypes/show.rhtml
new file mode 100644
index 0000000..ce7991d
--- /dev/null
+++ b/src/server/app/views/logtypes/show.rhtml
@@ -0,0 +1,24 @@
+<h1>All Events for <%=@logtype.name%></h1>
+<div id="eventlist">
+ <ul>
+ <% for event in @events do %>
+ <li><%= if params[:withepoch] then event.time else Time.at(event.time) end %> : <%= displaylevel(event.loglevel)%> <%=event.payload%></li>
+ <%end%>
+ </ul>
+</div>
+
+<div class="pagination">
+ <%= will_paginate @event %>
+</div>
+<div class="adendem">
+ Records per page:
+ <%=link_to "20", :withepoch => params[:withepoch], :page => 1, :perpage => "20" %> |
+ <%=link_to "50", :withepoch => params[:withepoch], :page => 1, :perpage => "50" %> |
+ <%=link_to "100", :withepoch => params[:withepoch], :page => 1, :perpage => "100" %> |
+ <%=link_to "200", :withepoch => params[:withepoch], :page => 1, :perpage => "200" %>
+</div>
+<%if params[:withepoch]%>
+ <div class="adendem"><%=link_to "show regular time", :withepoch => nil, :page => params[:page], :perpage => params[:perpage] %></div>
+<%else%>
+ <div class="adendem"><%=link_to "show epoch time", :withepoch => 1, :page => params[:page], :perpage => params[:perpage] %></div>
+<%end%>
\ No newline at end of file
diff --git a/src/server/config/routes.rb b/src/server/config/routes.rb
index ea14ce1..f522ea1 100644
--- a/src/server/config/routes.rb
+++ b/src/server/config/routes.rb
@@ -1,43 +1,45 @@
ActionController::Routing::Routes.draw do |map|
# The priority is based upon order of creation: first created -> highest priority.
# Sample of regular route:
# map.connect 'products/:id', :controller => 'catalog', :action => 'view'
# Keep in mind you can assign values other than :controller and :action
# Sample of named route:
# map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase'
# This route can be invoked with purchase_url(:id => product.id)
# Sample resource route (maps HTTP verbs to controller actions automatically):
# map.resources :products
# Sample resource route with options:
# map.resources :products, :member => { :short => :get, :toggle => :post }, :collection => { :sold => :get }
# Sample resource route with sub-resources:
# map.resources :products, :has_many => [ :comments, :sales ], :has_one => :seller
# Sample resource route with more complex sub-resources
# map.resources :products do |products|
# products.resources :comments
# products.resources :sales, :collection => { :recent => :get }
# end
# Sample resource route within a namespace:
# map.namespace :admin do |admin|
# # Directs /admin/products/* to Admin::ProductsController (app/controllers/admin/products_controller.rb)
# admin.resources :products
# end
# You can have the root of your site routed with map.root -- just remember to delete public/index.html.
# map.root :controller => "welcome"
# See how all your routes lay out with "rake routes"
# Install the default routes as the lowest priority.
# Note: These default routes make all actions in every controller accessible via GET requests. You should
# consider removing or commenting them out if you're using named routes and resources.
+ map.root :controller => 'events', :action => 'show'
+ map.connect 'events', :controller => "events", :action => 'show'
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
end
diff --git a/src/server/db/migrate/20090803050441_add_logtype_to_events.rb b/src/server/db/migrate/20090803050441_add_logtype_to_events.rb
new file mode 100644
index 0000000..a53e794
--- /dev/null
+++ b/src/server/db/migrate/20090803050441_add_logtype_to_events.rb
@@ -0,0 +1,10 @@
+class AddLogtypeToEvents < ActiveRecord::Migration
+ def self.up
+ add_column :events, :logtype_id, :int
+ end
+
+ def self.down
+ remove_column :events, :logtype_id
+ end
+end
+
diff --git a/src/server/db/schema.rb b/src/server/db/schema.rb
index 368312d..3a16546 100644
--- a/src/server/db/schema.rb
+++ b/src/server/db/schema.rb
@@ -1,55 +1,56 @@
# This file is auto-generated from the current state of the database. Instead of editing this file,
# please use the migrations feature of Active Record to incrementally modify your database, and
# then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your database schema. If you need
# to create the application database on another system, you should be using db:schema:load, not running
# all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended to check this file into your version control system.
-ActiveRecord::Schema.define(:version => 20090730154024) do
+ActiveRecord::Schema.define(:version => 20090803050441) do
create_table "agents", :force => true do |t|
t.string "name"
t.string "hostname"
t.string "port"
t.string "key"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "agents_logtypes", :force => true do |t|
t.integer "logtype_id"
t.integer "agent_id"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "events", :force => true do |t|
t.string "payload"
t.string "staticentry_id"
t.integer "agent_id"
t.integer "type_id"
t.integer "loglevel"
t.integer "time"
t.datetime "created_at"
t.datetime "updated_at"
+ t.integer "logtype_id"
end
create_table "logtypes", :force => true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "staticentries", :force => true do |t|
t.integer "logtype_id"
t.text "data"
t.integer "agent_id"
t.datetime "created_at"
t.datetime "updated_at"
end
end
diff --git a/src/server/lib/modules/collection_server.rb b/src/server/lib/modules/collection_server.rb
index 78a96b8..f1148e1 100644
--- a/src/server/lib/modules/collection_server.rb
+++ b/src/server/lib/modules/collection_server.rb
@@ -1,72 +1,73 @@
module CollectionServer
#TODO: Checksum check should be wrapped in to an exception and then and handled that way in receive_data
#Set buffer delimiters
@@break = '__1_BB'
@@value = '__1_VV'
@@finish = '__1_EE'
def check_key(agent, key)
if agent.key != key
return false
else
return true
end
end
#Write a log entry
def log_entry(line)
raw = line.split(@@break)
map = Hash.new
raw.each do |keys|
parts = keys.split(@@value)
map.store(parts[0],parts[1])
end
static = Logtype.find(map['logtype_id']).staticentries.new
static.data = map['data']
static.save
static = Staticentry.find_by_id(Digest::MD5.hexdigest(map['data']))
event = static.events.new
event.time = map['time']
event.loglevel = map['loglevel']
event.payload = map['payload']
+ event.logtype_id = map['logtype_id']
event.agent_id = map['agent_id']
if check_key(Agent.find(map['agent_id']), map['key'])
event.save
else
ActiveRecord::Base.logger.debug "Event dropped -- invalid agent key sent"
end
port, ip = Socket.unpack_sockaddr_in(get_peername)
host = Socket.getaddrinfo(ip, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME)[0][2]
ActiveRecord::Base.logger.debug "New event logged from #{host} \n -- Log data: #{line}"
end
#Do this when a connection is initialized
def post_init
port, ip = Socket.unpack_sockaddr_in(get_peername)
host = Socket.getaddrinfo(ip, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME)[0][2]
ActiveRecord::Base.logger.info "-- Collector connection established from #{host}"
end
#Do this when data is received
def receive_data(data)
(@buffer ||= BufferedTokenizer.new(delimiter = "__1_EE")).extract(data).each do |line|
if line.valid?
log_entry(line)
else
port, ip = Socket.unpack_sockaddr_in(get_peername)
host = Socket.getaddrinfo(ip, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME)[0][2]
ActiveRecord::Base.logger.error "Dropped log entry from #{host} - checksum invalid"
end
end
end
#Do this when a connection is closed by a peer
def unbind
ActiveRecord::Base.logger.info "-- Collector connection closed by a peer"
end
end
\ No newline at end of file
diff --git a/src/server/public/index.html b/src/server/public/index.html
deleted file mode 100644
index 0dd5189..0000000
--- a/src/server/public/index.html
+++ /dev/null
@@ -1,275 +0,0 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-<html>
- <head>
- <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
- <title>Ruby on Rails: Welcome aboard</title>
- <style type="text/css" media="screen">
- body {
- margin: 0;
- margin-bottom: 25px;
- padding: 0;
- background-color: #f0f0f0;
- font-family: "Lucida Grande", "Bitstream Vera Sans", "Verdana";
- font-size: 13px;
- color: #333;
- }
-
- h1 {
- font-size: 28px;
- color: #000;
- }
-
- a {color: #03c}
- a:hover {
- background-color: #03c;
- color: white;
- text-decoration: none;
- }
-
-
- #page {
- background-color: #f0f0f0;
- width: 750px;
- margin: 0;
- margin-left: auto;
- margin-right: auto;
- }
-
- #content {
- float: left;
- background-color: white;
- border: 3px solid #aaa;
- border-top: none;
- padding: 25px;
- width: 500px;
- }
-
- #sidebar {
- float: right;
- width: 175px;
- }
-
- #footer {
- clear: both;
- }
-
-
- #header, #about, #getting-started {
- padding-left: 75px;
- padding-right: 30px;
- }
-
-
- #header {
- background-image: url("images/rails.png");
- background-repeat: no-repeat;
- background-position: top left;
- height: 64px;
- }
- #header h1, #header h2 {margin: 0}
- #header h2 {
- color: #888;
- font-weight: normal;
- font-size: 16px;
- }
-
-
- #about h3 {
- margin: 0;
- margin-bottom: 10px;
- font-size: 14px;
- }
-
- #about-content {
- background-color: #ffd;
- border: 1px solid #fc0;
- margin-left: -11px;
- }
- #about-content table {
- margin-top: 10px;
- margin-bottom: 10px;
- font-size: 11px;
- border-collapse: collapse;
- }
- #about-content td {
- padding: 10px;
- padding-top: 3px;
- padding-bottom: 3px;
- }
- #about-content td.name {color: #555}
- #about-content td.value {color: #000}
-
- #about-content.failure {
- background-color: #fcc;
- border: 1px solid #f00;
- }
- #about-content.failure p {
- margin: 0;
- padding: 10px;
- }
-
-
- #getting-started {
- border-top: 1px solid #ccc;
- margin-top: 25px;
- padding-top: 15px;
- }
- #getting-started h1 {
- margin: 0;
- font-size: 20px;
- }
- #getting-started h2 {
- margin: 0;
- font-size: 14px;
- font-weight: normal;
- color: #333;
- margin-bottom: 25px;
- }
- #getting-started ol {
- margin-left: 0;
- padding-left: 0;
- }
- #getting-started li {
- font-size: 18px;
- color: #888;
- margin-bottom: 25px;
- }
- #getting-started li h2 {
- margin: 0;
- font-weight: normal;
- font-size: 18px;
- color: #333;
- }
- #getting-started li p {
- color: #555;
- font-size: 13px;
- }
-
-
- #search {
- margin: 0;
- padding-top: 10px;
- padding-bottom: 10px;
- font-size: 11px;
- }
- #search input {
- font-size: 11px;
- margin: 2px;
- }
- #search-text {width: 170px}
-
-
- #sidebar ul {
- margin-left: 0;
- padding-left: 0;
- }
- #sidebar ul h3 {
- margin-top: 25px;
- font-size: 16px;
- padding-bottom: 10px;
- border-bottom: 1px solid #ccc;
- }
- #sidebar li {
- list-style-type: none;
- }
- #sidebar ul.links li {
- margin-bottom: 5px;
- }
-
- </style>
- <script type="text/javascript" src="javascripts/prototype.js"></script>
- <script type="text/javascript" src="javascripts/effects.js"></script>
- <script type="text/javascript">
- function about() {
- if (Element.empty('about-content')) {
- new Ajax.Updater('about-content', 'rails/info/properties', {
- method: 'get',
- onFailure: function() {Element.classNames('about-content').add('failure')},
- onComplete: function() {new Effect.BlindDown('about-content', {duration: 0.25})}
- });
- } else {
- new Effect[Element.visible('about-content') ?
- 'BlindUp' : 'BlindDown']('about-content', {duration: 0.25});
- }
- }
-
- window.onload = function() {
- $('search-text').value = '';
- $('search').onsubmit = function() {
- $('search-text').value = 'site:rubyonrails.org ' + $F('search-text');
- }
- }
- </script>
- </head>
- <body>
- <div id="page">
- <div id="sidebar">
- <ul id="sidebar-items">
- <li>
- <form id="search" action="http://www.google.com/search" method="get">
- <input type="hidden" name="hl" value="en" />
- <input type="text" id="search-text" name="q" value="site:rubyonrails.org " />
- <input type="submit" value="Search" /> the Rails site
- </form>
- </li>
-
- <li>
- <h3>Join the community</h3>
- <ul class="links">
- <li><a href="http://www.rubyonrails.org/">Ruby on Rails</a></li>
- <li><a href="http://weblog.rubyonrails.org/">Official weblog</a></li>
- <li><a href="http://wiki.rubyonrails.org/">Wiki</a></li>
- </ul>
- </li>
-
- <li>
- <h3>Browse the documentation</h3>
- <ul class="links">
- <li><a href="http://api.rubyonrails.org/">Rails API</a></li>
- <li><a href="http://stdlib.rubyonrails.org/">Ruby standard library</a></li>
- <li><a href="http://corelib.rubyonrails.org/">Ruby core</a></li>
- <li><a href="http://guides.rubyonrails.org/">Rails Guides</a></li>
- </ul>
- </li>
- </ul>
- </div>
-
- <div id="content">
- <div id="header">
- <h1>Welcome aboard</h1>
- <h2>You’re riding Ruby on Rails!</h2>
- </div>
-
- <div id="about">
- <h3><a href="rails/info/properties" onclick="about(); return false">About your application’s environment</a></h3>
- <div id="about-content" style="display: none"></div>
- </div>
-
- <div id="getting-started">
- <h1>Getting started</h1>
- <h2>Here’s how to get rolling:</h2>
-
- <ol>
- <li>
- <h2>Use <tt>script/generate</tt> to create your models and controllers</h2>
- <p>To see all available options, run it without parameters.</p>
- </li>
-
- <li>
- <h2>Set up a default route and remove or rename this file</h2>
- <p>Routes are set up in config/routes.rb.</p>
- </li>
-
- <li>
- <h2>Create your database</h2>
- <p>Run <tt>rake db:migrate</tt> to create your database. If you're not using SQLite (the default), edit <tt>config/database.yml</tt> with your username and password.</p>
- </li>
- </ol>
- </div>
- </div>
-
- <div id="footer"> </div>
- </div>
- </body>
-</html>
\ No newline at end of file
diff --git a/src/server/public/stylesheets/main.css b/src/server/public/stylesheets/main.css
index 0ad4dbc..b8bf9bb 100644
--- a/src/server/public/stylesheets/main.css
+++ b/src/server/public/stylesheets/main.css
@@ -1,118 +1,132 @@
body {
background: #fff;
color: #000;
margin: 0px;
padding: 0px;
color: #333;
font-weight:bold;
font-family: serif;
}
a {
text-decoration: none;
color: #660033;
}
a:hover {
background: #000033;
color: #fff;
padding: 2px;
}
#container {
padding: 0px;
margin: auto;
width: 900px;
}
#header {
width: 100%;
margin: 0px;
height: 95px;
background: #333;
border-bottom: solid 6px #000;
color:#fff;
}
#logo {
position: absolute;
padding-top: 20px;
padding-left: 45px;
font-weight:bold;
font-size: 55px;
color: #fff;
}
#search {
text-align: right;
padding-top: 20px;
padding-right: 50px;
}
.searchbox {
background: #663366;
border: 1px solid #000;
color: #fff;
font-size: 20px;
padding: 2px;
font-weight: none;
}
+#eventlist {
+ min-height: 350px;
+ _height: 350px;
+}
+
#topnav a {
background: #000;
padding: 4px;
padding-bottom: 4px;
padding-left: 6px;
padding-right: 6px;
color: #fff;
+ border-left: solid 2px #000033;
+ border-right: solid 2px #000033;
+ border-bottom: solid 2px #000033;
}
#topnav a:hover {
background: #666;
padding: 4px;
padding-bottom: 4px;
padding-left: 6px;
padding-right: 6px;
color: #fff;
+ border-left: solid 2px #000033;
+ border-right: solid 2px #000033;
+ border-bottom: solid 2px #000033;
}
.topnav {
background: #666;
padding: 2px;
padding-bottom: 4px;
padding-left: 6px;
padding-right: 6px;
color: #fff;
+ border-left: solid 2px #000033;
+ border-right: solid 2px #000033;
+ border-bottom: solid 2px #000033;
}
#topnav {
font-size: 20px;
padding: 2px;
padding-bottom: 4px;
padding-left: 6px;
padding-right: 6px;
color: #fff;
}
#main {
- min-height: 500px;
- _height: 500px; /* IE min-height hack */
+ min-height: 400px;
+ _height: 400px; /* IE min-height hack */
}
#footer {
text-align: center;
width: 900px;
border-top: 2px solid #000;
padding-top: 15px;
}
.clear {
clear:both;
}
.adendem {
font-size: 14px;
font-weight: normal;
}
.in20 {
padding-left: 20px;
padding-right: 20px;
}
\ No newline at end of file
diff --git a/src/server/test/functional/agents_controller_test.rb b/src/server/test/functional/agents_controller_test.rb
new file mode 100644
index 0000000..e8c8c80
--- /dev/null
+++ b/src/server/test/functional/agents_controller_test.rb
@@ -0,0 +1,8 @@
+require 'test_helper'
+
+class AgentsControllerTest < ActionController::TestCase
+ # Replace this with your real tests.
+ test "the truth" do
+ assert true
+ end
+end
diff --git a/src/server/test/functional/logtypes_controller_test.rb b/src/server/test/functional/logtypes_controller_test.rb
new file mode 100644
index 0000000..7673cb6
--- /dev/null
+++ b/src/server/test/functional/logtypes_controller_test.rb
@@ -0,0 +1,8 @@
+require 'test_helper'
+
+class LogtypesControllerTest < ActionController::TestCase
+ # Replace this with your real tests.
+ test "the truth" do
+ assert true
+ end
+end
diff --git a/src/server/test/unit/helpers/agents_helper_test.rb b/src/server/test/unit/helpers/agents_helper_test.rb
new file mode 100644
index 0000000..c760506
--- /dev/null
+++ b/src/server/test/unit/helpers/agents_helper_test.rb
@@ -0,0 +1,4 @@
+require 'test_helper'
+
+class AgentsHelperTest < ActionView::TestCase
+end
diff --git a/src/server/test/unit/helpers/logtypes_helper_test.rb b/src/server/test/unit/helpers/logtypes_helper_test.rb
new file mode 100644
index 0000000..89ebea3
--- /dev/null
+++ b/src/server/test/unit/helpers/logtypes_helper_test.rb
@@ -0,0 +1,4 @@
+require 'test_helper'
+
+class LogtypesHelperTest < ActionView::TestCase
+end
|
parabuzzle/cistern
|
9a80a7291114e5c70132b4bda04ee2c988a78ccd
|
Added pagination for events
|
diff --git a/src/server/app/controllers/events_controller.rb b/src/server/app/controllers/events_controller.rb
index 180482b..50d0697 100644
--- a/src/server/app/controllers/events_controller.rb
+++ b/src/server/app/controllers/events_controller.rb
@@ -1,17 +1,17 @@
class EventsController < ApplicationController
include EventsHelper
def index
@title = "Events"
@logtypes = Logtype.all
@agents = Agent.all
end
def show
@title = "All Events"
#@events = Array.new
- events = Event.all
- @events = rebuildevents(events)
+ @event = Event.paginate :all, :per_page => params[:perpage], :page => params[:page]
+ @events = rebuildevents(@event)
end
end
diff --git a/src/server/app/models/event.rb b/src/server/app/models/event.rb
index d50fa7e..a1036f9 100644
--- a/src/server/app/models/event.rb
+++ b/src/server/app/models/event.rb
@@ -1,10 +1,13 @@
class Event < ActiveRecord::Base
belongs_to :staticentry
belongs_to :agent
+ cattr_reader :per_page
+ @@per_page = 20
+
default_scope :order => 'time DESC'
#Validations
validates_presence_of :agent_id, :loglevel, :time
end
diff --git a/src/server/app/views/events/show.rhtml b/src/server/app/views/events/show.rhtml
index 8fe0957..4c7d5a7 100644
--- a/src/server/app/views/events/show.rhtml
+++ b/src/server/app/views/events/show.rhtml
@@ -1,6 +1,23 @@
<h1>All Events</h1>
<ul>
<% for event in @events do %>
- <li><%= Time.at(event.time)%> : <%= displaylevel(event.loglevel)%> <%=event.payload%></li>
+ <li><%= if params[:withepoch] then event.time else Time.at(event.time) end %> : <%= displaylevel(event.loglevel)%> <%=event.payload%></li>
<%end%>
</ul>
+<%if params[:withepoch]%>
+ <div class="adendem"><%=link_to "show regular time", :withepoch => nil, :page => params[:page], :perpage => params[:perpage] %></div>
+<%else%>
+ <div class="adendem"><%=link_to "show epoch time", :withepoch => 1, :page => params[:page], :perpage => params[:perpage] %></div>
+<%end%>
+
+<div class="pagination">
+ <%= will_paginate @event %>
+</div>
+<div class="adendem">
+ Records per page:
+ <%=link_to "20", :withepoch => params[:withepoch], :page => 1, :perpage => "20" %> |
+ <%=link_to "50", :withepoch => params[:withepoch], :page => 1, :perpage => "50" %> |
+ <%=link_to "100", :withepoch => params[:withepoch], :page => 1, :perpage => "100" %> |
+ <%=link_to "200", :withepoch => params[:withepoch], :page => 1, :perpage => "200" %>
+</div>
+
diff --git a/src/server/app/views/layouts/application.rhtml b/src/server/app/views/layouts/application.rhtml
index f7458de..5f4fb1e 100644
--- a/src/server/app/views/layouts/application.rhtml
+++ b/src/server/app/views/layouts/application.rhtml
@@ -1,70 +1,74 @@
<%starttime = Time.now.to_f %>
<!DOCTYPE HTML PUBLIC "!//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Cistern :: <%= @title %></title>
<%= stylesheet_link_tag "main" %>
<%= javascript_include_tag "jquery.min"%>
<%= javascript_include_tag "application"%>
</head>
<body>
<div id="header">
<div id="logo">Cistern</div>
<div id="search ">
Search all Events
<% form_for :search do |form| %>
<div><%= form.text_field :data, :size => 20, :class => "searchbox" %></div>
<div class="adendem">advanced</div>
<%end%>
</div>
</div> <!-- header -->
<div id="container">
+ <div id="topnav">
+ <%= link_to("Events", :controller => "events", :action => "index")%>
+ </div>
<div id="main">
<%= @content_for_layout %>
</div> <!-- main -->
<div id="footer">
- Footer
+ Copyright © 2009 Mike Heijmans
+ <div class="adendum">powered by <a href="http://parabuzzle.github.com/cistern">Cistern</a></div>
</div> <!-- footer -->
<% if ENV["RAILS_ENV"] == "development" #call this block if in dev mode %>
<!-- Dev stuff -->
<div id="debug">
<a href='#' onclick="$('#params_debug_info').toggle();return false">params</a> |
<a href='#' onclick="$('#session_debug_info').toggle();return false">session</a> |
<a href='#' onclick="$('#env_debug_info').toggle();return false">env</a> |
<a href='#' onclick="$('#request_debug_info').toggle();return false">request</a>
<fieldset id="params_debug_info" class="debug_info" style="display:none">
<legend>params</legend>
<%= debug(params) %>
</fieldset>
<fieldset id="session_debug_info" class="debug_info" style="display:none">
<legend>session</legend>
<%= debug(session) %>
</fieldset>
<fieldset id="env_debug_info" class="debug_info" style="display:none">
<legend>env</legend>
<%= debug(request.env) %>
</fieldset>
<fieldset id="request_debug_info" class="debug_info" style="display:none">
<legend>request</legend>
<%= debug(request) %>
</fieldset>
</div>
<!-- end Dev mode only stuff -->
<% end %>
</div> <!-- container -->
</body>
</html>
<% rtime = Time.now.to_f - starttime%>
<% if ENV["RAILS_ENV"] == "development"%>
<%= [rtime*1000].to_s.to_i %> ms
<%else%>
<!-- <%= rtime*1000 %> -->
<%end%>
\ No newline at end of file
diff --git a/src/server/config/environment.rb b/src/server/config/environment.rb
index 06ecaee..dfff859 100644
--- a/src/server/config/environment.rb
+++ b/src/server/config/environment.rb
@@ -1,42 +1,43 @@
# Be sure to restart your server when you modify this file
# Specifies gem version of Rails to use when vendor/rails is not present
RAILS_GEM_VERSION = '2.3.3' unless defined? RAILS_GEM_VERSION
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
Rails::Initializer.run do |config|
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Add additional load paths for your own custom dirs
# config.load_paths += %W( #{RAILS_ROOT}/extras )
# Specify gems that this application depends on and have them installed with rake gems:install
# config.gem "bj"
# config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
# config.gem "sqlite3-ruby", :lib => "sqlite3"
# config.gem "aws-s3", :lib => "aws/s3"
config.gem "eventmachine"
+ config.gem "will_paginate"
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Skip frameworks you're not going to use. To use Rails without a database,
# you must remove the Active Record framework.
# config.frameworks -= [ :active_record, :active_resource, :action_mailer ]
# Activate observers that should always be running
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names.
config.time_zone = 'UTC'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')]
# config.i18n.default_locale = :de
end
\ No newline at end of file
diff --git a/src/server/public/stylesheets/main.css b/src/server/public/stylesheets/main.css
index 4fc7cbb..0ad4dbc 100644
--- a/src/server/public/stylesheets/main.css
+++ b/src/server/public/stylesheets/main.css
@@ -1,68 +1,118 @@
body {
background: #fff;
color: #000;
margin: 0px;
padding: 0px;
color: #333;
font-weight:bold;
font-family: serif;
}
-#container {
+a {
+ text-decoration: none;
+ color: #660033;
+}
+
+a:hover {
+ background: #000033;
+ color: #fff;
padding: 2px;
+}
+
+#container {
+ padding: 0px;
margin: auto;
width: 900px;
}
#header {
width: 100%;
margin: 0px;
height: 95px;
background: #333;
border-bottom: solid 6px #000;
color:#fff;
}
#logo {
position: absolute;
padding-top: 20px;
padding-left: 45px;
font-weight:bold;
font-size: 55px;
color: #fff;
}
#search {
text-align: right;
padding-top: 20px;
padding-right: 50px;
}
.searchbox {
background: #663366;
border: 1px solid #000;
color: #fff;
font-size: 20px;
padding: 2px;
font-weight: none;
}
+#topnav a {
+ background: #000;
+ padding: 4px;
+ padding-bottom: 4px;
+ padding-left: 6px;
+ padding-right: 6px;
+ color: #fff;
+}
+#topnav a:hover {
+ background: #666;
+ padding: 4px;
+ padding-bottom: 4px;
+ padding-left: 6px;
+ padding-right: 6px;
+ color: #fff;
+}
+.topnav {
+ background: #666;
+ padding: 2px;
+ padding-bottom: 4px;
+ padding-left: 6px;
+ padding-right: 6px;
+ color: #fff;
+}
+#topnav {
+ font-size: 20px;
+ padding: 2px;
+ padding-bottom: 4px;
+ padding-left: 6px;
+ padding-right: 6px;
+ color: #fff;
+}
+
#main {
min-height: 500px;
_height: 500px; /* IE min-height hack */
}
#footer {
text-align: center;
width: 900px;
+ border-top: 2px solid #000;
+ padding-top: 15px;
+}
+
+.clear {
+ clear:both;
}
.adendem {
font-size: 14px;
font-weight: normal;
}
.in20 {
padding-left: 20px;
padding-right: 20px;
}
\ No newline at end of file
diff --git a/src/server/vendor/plugins/will_paginate/.manifest b/src/server/vendor/plugins/will_paginate/.manifest
new file mode 100644
index 0000000..c8074e6
--- /dev/null
+++ b/src/server/vendor/plugins/will_paginate/.manifest
@@ -0,0 +1,43 @@
+CHANGELOG.rdoc
+LICENSE
+README.rdoc
+Rakefile
+examples/apple-circle.gif
+examples/index.haml
+examples/index.html
+examples/pagination.css
+examples/pagination.sass
+init.rb
+lib/will_paginate.rb
+lib/will_paginate/array.rb
+lib/will_paginate/collection.rb
+lib/will_paginate/core_ext.rb
+lib/will_paginate/finder.rb
+lib/will_paginate/named_scope.rb
+lib/will_paginate/named_scope_patch.rb
+lib/will_paginate/version.rb
+lib/will_paginate/view_helpers.rb
+test/boot.rb
+test/collection_test.rb
+test/console
+test/database.yml
+test/finder_test.rb
+test/fixtures/admin.rb
+test/fixtures/developer.rb
+test/fixtures/developers_projects.yml
+test/fixtures/project.rb
+test/fixtures/projects.yml
+test/fixtures/replies.yml
+test/fixtures/reply.rb
+test/fixtures/schema.rb
+test/fixtures/topic.rb
+test/fixtures/topics.yml
+test/fixtures/user.rb
+test/fixtures/users.yml
+test/helper.rb
+test/lib/activerecord_test_case.rb
+test/lib/activerecord_test_connector.rb
+test/lib/load_fixtures.rb
+test/lib/view_test_process.rb
+test/tasks.rake
+test/view_test.rb
\ No newline at end of file
diff --git a/src/server/vendor/plugins/will_paginate/CHANGELOG.rdoc b/src/server/vendor/plugins/will_paginate/CHANGELOG.rdoc
new file mode 100644
index 0000000..01aea3a
--- /dev/null
+++ b/src/server/vendor/plugins/will_paginate/CHANGELOG.rdoc
@@ -0,0 +1,110 @@
+== 2.3.6, released 2008-10-26
+
+* Rails 2.2 fix: stop using `extract_attribute_names_from_match` inernal AR method, it no longer exists
+
+== 2.3.5, released 2008-10-07
+
+* update the backported named_scope implementation for Rails versions older than 2.1
+* break out of scope of paginated_each() yielded block when used on named scopes
+* fix paginate(:from)
+
+== 2.3.4, released 2008-09-16
+
+* Removed gem dependency to Active Support (causes trouble with vendored rails).
+* Rails 2.1: fix a failing test and a deprecation warning.
+* Cope with scoped :select when counting.
+
+== 2.3.3, released 2008-08-29
+
+* Ensure that paginate_by_sql doesn't change the original SQL query.
+* RDoc love (now live at http://mislav.caboo.se/static/will_paginate/doc/)
+* Rename :prev_label to :previous_label for consistency. old name still functions but is deprecated
+* ActiveRecord 2.1: Remove :include option from count_all query when it's possible.
+
+== 2.3.2, released 2008-05-16
+
+* Fixed LinkRenderer#stringified_merge by removing "return" from iterator block
+* Ensure that 'href' values in pagination links are escaped URLs
+
+== 2.3.1, released 2008-05-04
+
+* Fixed page numbers not showing with custom routes and implicit first page
+* Try to use Hanna for documentation (falls back to default RDoc template if not)
+
+== 2.3.0, released 2008-04-29
+
+* Changed LinkRenderer to receive collection, options and reference to view template NOT in
+ constructor, but with the #prepare method. This is a step towards supporting passing of
+ LinkRenderer (or subclass) instances that may be preconfigured in some way
+* LinkRenderer now has #page_link and #page_span methods for easier customization of output in
+ subclasses
+* Changed page_entries_info() method to adjust its output according to humanized class name of
+ collection items. Override this with :entry_name parameter (singular).
+
+ page_entries_info(@posts)
+ #-> "Displaying all 12 posts"
+ page_entries_info(@posts, :entry_name => 'item')
+ #-> "Displaying all 12 items"
+
+== 2.2.3, released 2008-04-26
+
+* will_paginate gem is no longer published on RubyForge, but on
+ gems.github.com:
+
+ gem sources -a http://gems.github.com/ (you only need to do this once)
+ gem install mislav-will_paginate
+
+* extract reusable pagination testing stuff into WillPaginate::View
+* rethink the page URL construction mechanizm to be more bulletproof when
+ combined with custom routing for page parameter
+* test that anchor parameter can be used in pagination links
+
+== 2.2.2, released 2008-04-21
+
+* Add support for page parameter in custom routes like "/foo/page/2"
+* Change output of "page_entries_info" on single-page collection and erraneous
+ output with empty collection as reported by Tim Chater
+
+== 2.2.1, released 2008-04-08
+
+* take less risky path when monkeypatching named_scope; fix that it no longer
+ requires ActiveRecord::VERSION
+* use strings in "respond_to?" calls to work around a bug in acts_as_ferret
+ stable (ugh)
+* add rake release task
+
+
+== 2.2.0, released 2008-04-07
+
+=== API changes
+* Rename WillPaginate::Collection#page_count to "total_pages" for consistency.
+ If you implemented this interface, change your implementation accordingly.
+* Remove old, deprecated style of calling Array#paginate as "paginate(page,
+ per_page)". If you want to specify :page, :per_page or :total_entries, use a
+ parameter hash.
+* Rename LinkRenderer#url_options to "url_for" and drastically optimize it
+
+=== View changes
+* Added "prev_page" and "next_page" CSS classes on previous/next page buttons
+* Add examples of pagination links styling in "examples/index.html"
+* Change gap in pagination links from "..." to
+ "<span class="gap">…</span>".
+* Add "paginated_section", a block helper that renders pagination both above and
+ below content in the block
+* Add rel="prev|next|start" to page links
+
+=== Other
+
+* Add ability to opt-in for Rails 2.1 feature "named_scope" by calling
+ WillPaginate.enable_named_scope (tested in Rails 1.2.6 and 2.0.2)
+* Support complex page parameters like "developers[page]"
+* Move Array#paginate definition to will_paginate/array.rb. You can now easily
+ use pagination on arrays outside of Rails:
+
+ gem 'will_paginate'
+ require 'will_paginate/array'
+
+* Add "paginated_each" method for iterating through every record by loading only
+ one page of records at the time
+* Rails 2: Rescue from WillPaginate::InvalidPage error with 404 Not Found by
+ default
diff --git a/src/server/vendor/plugins/will_paginate/LICENSE b/src/server/vendor/plugins/will_paginate/LICENSE
new file mode 100644
index 0000000..96a48cb
--- /dev/null
+++ b/src/server/vendor/plugins/will_paginate/LICENSE
@@ -0,0 +1,18 @@
+Copyright (c) 2007 PJ Hyett and Mislav MarohniÄ
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software is furnished to do so,
+subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/src/server/vendor/plugins/will_paginate/README.rdoc b/src/server/vendor/plugins/will_paginate/README.rdoc
new file mode 100644
index 0000000..2a412f5
--- /dev/null
+++ b/src/server/vendor/plugins/will_paginate/README.rdoc
@@ -0,0 +1,107 @@
+= WillPaginate
+
+Pagination is just limiting the number of records displayed. Why should you let
+it get in your way while developing, then? This plugin makes magic happen. Did
+you ever want to be able to do just this on a model:
+
+ Post.paginate :page => 1, :order => 'created_at DESC'
+
+... and then render the page links with a single view helper? Well, now you
+can.
+
+Some resources to get you started:
+
+* {Installation instructions}[http://github.com/mislav/will_paginate/wikis/installation]
+ on {the wiki}[http://github.com/mislav/will_paginate/wikis]
+* Your mind reels with questions? Join our
+ {Google group}[http://groups.google.com/group/will_paginate].
+* {How to report bugs}[http://github.com/mislav/will_paginate/wikis/report-bugs]
+
+
+== Example usage
+
+Use a paginate finder in the controller:
+
+ @posts = Post.paginate_by_board_id @board.id, :page => params[:page], :order => 'updated_at DESC'
+
+Yeah, +paginate+ works just like +find+ -- it just doesn't fetch all the
+records. Don't forget to tell it which page you want, or it will complain!
+Read more on WillPaginate::Finder::ClassMethods.
+
+Render the posts in your view like you would normally do. When you need to render
+pagination, just stick this in:
+
+ <%= will_paginate @posts %>
+
+You're done. (You can find the option list at WillPaginate::ViewHelpers.)
+
+How does it know how much items to fetch per page? It asks your model by calling
+its <tt>per_page</tt> class method. You can define it like this:
+
+ class Post < ActiveRecord::Base
+ cattr_reader :per_page
+ @@per_page = 50
+ end
+
+... or like this:
+
+ class Post < ActiveRecord::Base
+ def self.per_page
+ 50
+ end
+ end
+
+... or don't worry about it at all. WillPaginate defines it to be <b>30</b> by default.
+But you can always specify the count explicitly when calling +paginate+:
+
+ @posts = Post.paginate :page => params[:page], :per_page => 50
+
+The +paginate+ finder wraps the original finder and returns your resultset that now has
+some new properties. You can use the collection as you would with any ActiveRecord
+resultset. WillPaginate view helpers also need that object to be able to render pagination:
+
+ <ol>
+ <% for post in @posts -%>
+ <li>Render `post` in some nice way.</li>
+ <% end -%>
+ </ol>
+
+ <p>Now let's render us some pagination!</p>
+ <%= will_paginate @posts %>
+
+More detailed documentation:
+
+* WillPaginate::Finder::ClassMethods for pagination on your models;
+* WillPaginate::ViewHelpers for your views.
+
+
+== Authors and credits
+
+Authors:: Mislav MarohniÄ, PJ Hyett
+Original announcement:: http://errtheblog.com/post/929
+Original PHP source:: http://www.strangerstudios.com/sandbox/pagination/diggstyle.php
+
+All these people helped making will_paginate what it is now with their code
+contributions or just simply awesome ideas:
+
+Chris Wanstrath, Dr. Nic Williams, K. Adam Christensen, Mike Garey, Bence
+Golda, Matt Aimonetti, Charles Brian Quinn, Desi McAdam, James Coglan, Matijs
+van Zuijlen, Maria, Brendan Ribera, Todd Willey, Bryan Helmkamp, Jan Berkel,
+Lourens Naudé, Rick Olson, Russell Norris, Piotr Usewicz, Chris Eppstein,
+Denis Barushev, Ben Pickles.
+
+
+== Usable pagination in the UI
+
+There are some CSS styles to get you started in the "examples/" directory. They
+are {showcased online here}[http://mislav.caboo.se/static/will_paginate/].
+
+More reading about pagination as design pattern:
+
+* {Pagination 101}[http://kurafire.net/log/archive/2007/06/22/pagination-101]
+* {Pagination gallery}[http://www.smashingmagazine.com/2007/11/16/pagination-gallery-examples-and-good-practices/]
+* {Pagination on Yahoo Design Pattern Library}[http://developer.yahoo.com/ypatterns/parent.php?pattern=pagination]
+
+Want to discuss, request features, ask questions? Join the
+{Google group}[http://groups.google.com/group/will_paginate].
+
diff --git a/src/server/vendor/plugins/will_paginate/Rakefile b/src/server/vendor/plugins/will_paginate/Rakefile
new file mode 100644
index 0000000..6226b1b
--- /dev/null
+++ b/src/server/vendor/plugins/will_paginate/Rakefile
@@ -0,0 +1,53 @@
+require 'rubygems'
+begin
+ hanna_dir = '/Users/mislav/Projects/Hanna/lib'
+ $:.unshift hanna_dir if File.exists? hanna_dir
+ require 'hanna/rdoctask'
+rescue LoadError
+ require 'rake'
+ require 'rake/rdoctask'
+end
+load 'test/tasks.rake'
+
+desc 'Default: run unit tests.'
+task :default => :test
+
+desc 'Generate RDoc documentation for the will_paginate plugin.'
+Rake::RDocTask.new(:rdoc) do |rdoc|
+ rdoc.rdoc_files.include('README.rdoc', 'LICENSE', 'CHANGELOG.rdoc').
+ include('lib/**/*.rb').
+ exclude('lib/will_paginate/named_scope*').
+ exclude('lib/will_paginate/array.rb').
+ exclude('lib/will_paginate/version.rb')
+
+ rdoc.main = "README.rdoc" # page to start on
+ rdoc.title = "will_paginate documentation"
+
+ rdoc.rdoc_dir = 'doc' # rdoc output folder
+ rdoc.options << '--inline-source' << '--charset=UTF-8'
+ rdoc.options << '--webcvs=http://github.com/mislav/will_paginate/tree/master/'
+end
+
+desc %{Update ".manifest" with the latest list of project filenames. Respect\
+.gitignore by excluding everything that git ignores. Update `files` and\
+`test_files` arrays in "*.gemspec" file if it's present.}
+task :manifest do
+ list = `git ls-files --full-name --exclude=*.gemspec --exclude=.*`.chomp.split("\n")
+
+ if spec_file = Dir['*.gemspec'].first
+ spec = File.read spec_file
+ spec.gsub! /^(\s* s.(test_)?files \s* = \s* )( \[ [^\]]* \] | %w\( [^)]* \) )/mx do
+ assignment = $1
+ bunch = $2 ? list.grep(/^test\//) : list
+ '%s%%w(%s)' % [assignment, bunch.join(' ')]
+ end
+
+ File.open(spec_file, 'w') { |f| f << spec }
+ end
+ File.open('.manifest', 'w') { |f| f << list.join("\n") }
+end
+
+task :examples do
+ %x(haml examples/index.haml examples/index.html)
+ %x(sass examples/pagination.sass examples/pagination.css)
+end
diff --git a/src/server/vendor/plugins/will_paginate/examples/apple-circle.gif b/src/server/vendor/plugins/will_paginate/examples/apple-circle.gif
new file mode 100644
index 0000000..df8cbf7
Binary files /dev/null and b/src/server/vendor/plugins/will_paginate/examples/apple-circle.gif differ
diff --git a/src/server/vendor/plugins/will_paginate/examples/index.haml b/src/server/vendor/plugins/will_paginate/examples/index.haml
new file mode 100644
index 0000000..fb41ac8
--- /dev/null
+++ b/src/server/vendor/plugins/will_paginate/examples/index.haml
@@ -0,0 +1,69 @@
+!!!
+%html
+%head
+ %title Samples of pagination styling for will_paginate
+ %link{ :rel => 'stylesheet', :type => 'text/css', :href => 'pagination.css' }
+ %style{ :type => 'text/css' }
+ :sass
+ html
+ :margin 0
+ :padding 0
+ :background #999
+ :font normal 76% "Lucida Grande", Verdana, Helvetica, sans-serif
+ body
+ :margin 2em
+ :padding 2em
+ :border 2px solid gray
+ :background white
+ :color #222
+ h1
+ :font-size 2em
+ :font-weight normal
+ :margin 0 0 1em 0
+ h2
+ :font-size 1.4em
+ :margin 1em 0 .5em 0
+ pre
+ :font-size 13px
+ :font-family Monaco, "DejaVu Sans Mono", "Bitstream Vera Mono", "Courier New", monospace
+
+- pagination = '<span class="disabled prev_page">« Previous</span> <span class="current">1</span> <a href="./?page=2" rel="next">2</a> <a href="./?page=3">3</a> <a href="./?page=4">4</a> <a href="./?page=5">5</a> <a href="./?page=6">6</a> <a href="./?page=7">7</a> <a href="./?page=8">8</a> <a href="./?page=9">9</a> <span class="gap">…</span> <a href="./?page=29">29</a> <a href="./?page=30">30</a> <a href="./?page=2" rel="next" class="next_page">Next »</a>'
+- pagination_no_page_links = '<span class="disabled prev_page">« Previous</span> <a href="./?page=2" rel="next" class="next_page">Next »</a>'
+
+%body
+ %h1 Samples of pagination styling for will_paginate
+ %p
+ Find these styles in <b>"examples/pagination.css"</b> of <i>will_paginate</i> library.
+ There is a Sass version of it for all you sassy people.
+ %p
+ Read about good rules for pagination:
+ %a{ :href => 'http://kurafire.net/log/archive/2007/06/22/pagination-101' } Pagination 101
+ %p
+ %em Warning:
+ page links below don't lead anywhere (so don't click on them).
+
+ %h2 Unstyled pagination <span style="font-weight:normal">(<i>ewww!</i>)</span>
+ %div= pagination
+
+ %h2 Digg.com
+ .digg_pagination= pagination
+
+ %h2 Digg-style, no page links
+ .digg_pagination= pagination_no_page_links
+ %p Code that renders this:
+ %pre= '<code>%s</code>' % %[<%= will_paginate @posts, :page_links => false %>].gsub('<', '<').gsub('>', '>')
+
+ %h2 Digg-style, extra content
+ .digg_pagination
+ .page_info Displaying entries <b>1 - 6</b> of <b>180</b> in total
+ = pagination
+ %p Code that renders this:
+ %pre= '<code>%s</code>' % %[<div class="digg_pagination">\n <div clas="page_info">\n <%= page_entries_info @posts %>\n </div>\n <%= will_paginate @posts, :container => false %>\n</div>].gsub('<', '<').gsub('>', '>')
+
+ %h2 Apple.com store
+ .apple_pagination= pagination
+
+ %h2 Flickr.com
+ .flickr_pagination
+ = pagination
+ .page_info (118 photos)
diff --git a/src/server/vendor/plugins/will_paginate/examples/index.html b/src/server/vendor/plugins/will_paginate/examples/index.html
new file mode 100644
index 0000000..858f7c6
--- /dev/null
+++ b/src/server/vendor/plugins/will_paginate/examples/index.html
@@ -0,0 +1,92 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html>
+</html>
+<head>
+ <title>Samples of pagination styling for will_paginate</title>
+ <link href='pagination.css' rel='stylesheet' type='text/css' />
+ <style type='text/css'>
+ html {
+ margin: 0;
+ padding: 0;
+ background: #999;
+ font: normal 76% "Lucida Grande", Verdana, Helvetica, sans-serif; }
+
+ body {
+ margin: 2em;
+ padding: 2em;
+ border: 2px solid gray;
+ background: white;
+ color: #222; }
+
+ h1 {
+ font-size: 2em;
+ font-weight: normal;
+ margin: 0 0 1em 0; }
+
+ h2 {
+ font-size: 1.4em;
+ margin: 1em 0 .5em 0; }
+
+ pre {
+ font-size: 13px;
+ font-family: Monaco, "DejaVu Sans Mono", "Bitstream Vera Mono", "Courier New", monospace; }
+ </style>
+</head>
+<body>
+ <h1>Samples of pagination styling for will_paginate</h1>
+ <p>
+ Find these styles in <b>"examples/pagination.css"</b> of <i>will_paginate</i> library.
+ There is a Sass version of it for all you sassy people.
+ </p>
+ <p>
+ Read about good rules for pagination:
+ <a href='http://kurafire.net/log/archive/2007/06/22/pagination-101'>Pagination 101</a>
+ </p>
+ <p>
+ <em>Warning:</em>
+ page links below don't lead anywhere (so don't click on them).
+ </p>
+ <h2>
+ Unstyled pagination <span style="font-weight:normal">(<i>ewww!</i>)</span>
+ </h2>
+ <div>
+ <span class="disabled prev_page">« Previous</span> <span class="current">1</span> <a href="./?page=2" rel="next">2</a> <a href="./?page=3">3</a> <a href="./?page=4">4</a> <a href="./?page=5">5</a> <a href="./?page=6">6</a> <a href="./?page=7">7</a> <a href="./?page=8">8</a> <a href="./?page=9">9</a> <span class="gap">…</span> <a href="./?page=29">29</a> <a href="./?page=30">30</a> <a href="./?page=2" rel="next" class="next_page">Next »</a>
+ </div>
+ <h2>Digg.com</h2>
+ <div class='digg_pagination'>
+ <span class="disabled prev_page">« Previous</span> <span class="current">1</span> <a href="./?page=2" rel="next">2</a> <a href="./?page=3">3</a> <a href="./?page=4">4</a> <a href="./?page=5">5</a> <a href="./?page=6">6</a> <a href="./?page=7">7</a> <a href="./?page=8">8</a> <a href="./?page=9">9</a> <span class="gap">…</span> <a href="./?page=29">29</a> <a href="./?page=30">30</a> <a href="./?page=2" rel="next" class="next_page">Next »</a>
+ </div>
+ <h2>Digg-style, no page links</h2>
+ <div class='digg_pagination'>
+ <span class="disabled prev_page">« Previous</span> <a href="./?page=2" rel="next" class="next_page">Next »</a>
+ </div>
+ <p>Code that renders this:</p>
+ <pre>
+ <code><%= will_paginate @posts, :page_links => false %></code>
+ </pre>
+ <h2>Digg-style, extra content</h2>
+ <div class='digg_pagination'>
+ <div class='page_info'>
+ Displaying entries <b>1 - 6</b> of <b>180</b> in total
+ </div>
+ <span class="disabled prev_page">« Previous</span> <span class="current">1</span> <a href="./?page=2" rel="next">2</a> <a href="./?page=3">3</a> <a href="./?page=4">4</a> <a href="./?page=5">5</a> <a href="./?page=6">6</a> <a href="./?page=7">7</a> <a href="./?page=8">8</a> <a href="./?page=9">9</a> <span class="gap">…</span> <a href="./?page=29">29</a> <a href="./?page=30">30</a> <a href="./?page=2" rel="next" class="next_page">Next »</a>
+ </div>
+ <p>Code that renders this:</p>
+ <pre>
+ <code><div class="digg_pagination">
+ <div clas="page_info">
+ <%= page_entries_info @posts %>
+ </div>
+ <%= will_paginate @posts, :container => false %>
+ </div></code>
+ </pre>
+ <h2>Apple.com store</h2>
+ <div class='apple_pagination'>
+ <span class="disabled prev_page">« Previous</span> <span class="current">1</span> <a href="./?page=2" rel="next">2</a> <a href="./?page=3">3</a> <a href="./?page=4">4</a> <a href="./?page=5">5</a> <a href="./?page=6">6</a> <a href="./?page=7">7</a> <a href="./?page=8">8</a> <a href="./?page=9">9</a> <span class="gap">…</span> <a href="./?page=29">29</a> <a href="./?page=30">30</a> <a href="./?page=2" rel="next" class="next_page">Next »</a>
+ </div>
+ <h2>Flickr.com</h2>
+ <div class='flickr_pagination'>
+ <span class="disabled prev_page">« Previous</span> <span class="current">1</span> <a href="./?page=2" rel="next">2</a> <a href="./?page=3">3</a> <a href="./?page=4">4</a> <a href="./?page=5">5</a> <a href="./?page=6">6</a> <a href="./?page=7">7</a> <a href="./?page=8">8</a> <a href="./?page=9">9</a> <span class="gap">…</span> <a href="./?page=29">29</a> <a href="./?page=30">30</a> <a href="./?page=2" rel="next" class="next_page">Next »</a>
+ <div class='page_info'>(118 photos)</div>
+ </div>
+</body>
diff --git a/src/server/vendor/plugins/will_paginate/examples/pagination.css b/src/server/vendor/plugins/will_paginate/examples/pagination.css
new file mode 100644
index 0000000..b55e977
--- /dev/null
+++ b/src/server/vendor/plugins/will_paginate/examples/pagination.css
@@ -0,0 +1,90 @@
+.digg_pagination {
+ background: white;
+ /* self-clearing method: */ }
+ .digg_pagination a, .digg_pagination span {
+ padding: .2em .5em;
+ display: block;
+ float: left;
+ margin-right: 1px; }
+ .digg_pagination span.disabled {
+ color: #999;
+ border: 1px solid #DDD; }
+ .digg_pagination span.current {
+ font-weight: bold;
+ background: #2E6AB1;
+ color: white;
+ border: 1px solid #2E6AB1; }
+ .digg_pagination a {
+ text-decoration: none;
+ color: #105CB6;
+ border: 1px solid #9AAFE5; }
+ .digg_pagination a:hover, .digg_pagination a:focus {
+ color: #003;
+ border-color: #003; }
+ .digg_pagination .page_info {
+ background: #2E6AB1;
+ color: white;
+ padding: .4em .6em;
+ width: 22em;
+ margin-bottom: .3em;
+ text-align: center; }
+ .digg_pagination .page_info b {
+ color: #003;
+ background: #6aa6ed;
+ padding: .1em .25em; }
+ .digg_pagination:after {
+ content: ".";
+ display: block;
+ height: 0;
+ clear: both;
+ visibility: hidden; }
+ * html .digg_pagination {
+ height: 1%; }
+ *:first-child+html .digg_pagination {
+ overflow: hidden; }
+
+.apple_pagination {
+ background: #F1F1F1;
+ border: 1px solid #E5E5E5;
+ text-align: center;
+ padding: 1em; }
+ .apple_pagination a, .apple_pagination span {
+ padding: .2em .3em; }
+ .apple_pagination span.disabled {
+ color: #AAA; }
+ .apple_pagination span.current {
+ font-weight: bold;
+ background: transparent url(apple-circle.gif) no-repeat 50% 50%; }
+ .apple_pagination a {
+ text-decoration: none;
+ color: black; }
+ .apple_pagination a:hover, .apple_pagination a:focus {
+ text-decoration: underline; }
+
+.flickr_pagination {
+ text-align: center;
+ padding: .3em; }
+ .flickr_pagination a, .flickr_pagination span {
+ padding: .2em .5em; }
+ .flickr_pagination span.disabled {
+ color: #AAA; }
+ .flickr_pagination span.current {
+ font-weight: bold;
+ color: #FF0084; }
+ .flickr_pagination a {
+ border: 1px solid #DDDDDD;
+ color: #0063DC;
+ text-decoration: none; }
+ .flickr_pagination a:hover, .flickr_pagination a:focus {
+ border-color: #003366;
+ background: #0063DC;
+ color: white; }
+ .flickr_pagination .page_info {
+ color: #aaa;
+ padding-top: .8em; }
+ .flickr_pagination .prev_page, .flickr_pagination .next_page {
+ border-width: 2px; }
+ .flickr_pagination .prev_page {
+ margin-right: 1em; }
+ .flickr_pagination .next_page {
+ margin-left: 1em; }
diff --git a/src/server/vendor/plugins/will_paginate/examples/pagination.sass b/src/server/vendor/plugins/will_paginate/examples/pagination.sass
new file mode 100644
index 0000000..737a97b
--- /dev/null
+++ b/src/server/vendor/plugins/will_paginate/examples/pagination.sass
@@ -0,0 +1,91 @@
+.digg_pagination
+ :background white
+ a, span
+ :padding .2em .5em
+ :display block
+ :float left
+ :margin-right 1px
+ span.disabled
+ :color #999
+ :border 1px solid #DDD
+ span.current
+ :font-weight bold
+ :background #2E6AB1
+ :color white
+ :border 1px solid #2E6AB1
+ a
+ :text-decoration none
+ :color #105CB6
+ :border 1px solid #9AAFE5
+ &:hover, &:focus
+ :color #003
+ :border-color #003
+ .page_info
+ :background #2E6AB1
+ :color white
+ :padding .4em .6em
+ :width 22em
+ :margin-bottom .3em
+ :text-align center
+ b
+ :color #003
+ :background = #2E6AB1 + 60
+ :padding .1em .25em
+
+ /* self-clearing method:
+ &:after
+ :content "."
+ :display block
+ :height 0
+ :clear both
+ :visibility hidden
+ * html &
+ :height 1%
+ *:first-child+html &
+ :overflow hidden
+
+.apple_pagination
+ :background #F1F1F1
+ :border 1px solid #E5E5E5
+ :text-align center
+ :padding 1em
+ a, span
+ :padding .2em .3em
+ span.disabled
+ :color #AAA
+ span.current
+ :font-weight bold
+ :background transparent url(apple-circle.gif) no-repeat 50% 50%
+ a
+ :text-decoration none
+ :color black
+ &:hover, &:focus
+ :text-decoration underline
+
+.flickr_pagination
+ :text-align center
+ :padding .3em
+ a, span
+ :padding .2em .5em
+ span.disabled
+ :color #AAA
+ span.current
+ :font-weight bold
+ :color #FF0084
+ a
+ :border 1px solid #DDDDDD
+ :color #0063DC
+ :text-decoration none
+ &:hover, &:focus
+ :border-color #003366
+ :background #0063DC
+ :color white
+ .page_info
+ :color #aaa
+ :padding-top .8em
+ .prev_page, .next_page
+ :border-width 2px
+ .prev_page
+ :margin-right 1em
+ .next_page
+ :margin-left 1em
diff --git a/src/server/vendor/plugins/will_paginate/init.rb b/src/server/vendor/plugins/will_paginate/init.rb
new file mode 100644
index 0000000..838d30e
--- /dev/null
+++ b/src/server/vendor/plugins/will_paginate/init.rb
@@ -0,0 +1 @@
+require 'will_paginate'
diff --git a/src/server/vendor/plugins/will_paginate/lib/will_paginate.rb b/src/server/vendor/plugins/will_paginate/lib/will_paginate.rb
new file mode 100644
index 0000000..a192daf
--- /dev/null
+++ b/src/server/vendor/plugins/will_paginate/lib/will_paginate.rb
@@ -0,0 +1,90 @@
+require 'active_support'
+require 'will_paginate/core_ext'
+
+# = You *will* paginate!
+#
+# First read about WillPaginate::Finder::ClassMethods, then see
+# WillPaginate::ViewHelpers. The magical array you're handling in-between is
+# WillPaginate::Collection.
+#
+# Happy paginating!
+module WillPaginate
+ class << self
+ # shortcut for <tt>enable_actionpack</tt> and <tt>enable_activerecord</tt> combined
+ def enable
+ enable_actionpack
+ enable_activerecord
+ end
+
+ # hooks WillPaginate::ViewHelpers into ActionView::Base
+ def enable_actionpack
+ return if ActionView::Base.instance_methods.include_method? :will_paginate
+ require 'will_paginate/view_helpers'
+ ActionView::Base.send :include, ViewHelpers
+
+ if defined?(ActionController::Base) and ActionController::Base.respond_to? :rescue_responses
+ ActionController::Base.rescue_responses['WillPaginate::InvalidPage'] = :not_found
+ end
+ end
+
+ # hooks WillPaginate::Finder into ActiveRecord::Base and classes that deal
+ # with associations
+ def enable_activerecord
+ return if ActiveRecord::Base.respond_to? :paginate
+ require 'will_paginate/finder'
+ ActiveRecord::Base.send :include, Finder
+
+ # support pagination on associations
+ a = ActiveRecord::Associations
+ returning([ a::AssociationCollection ]) { |classes|
+ # detect http://dev.rubyonrails.org/changeset/9230
+ unless a::HasManyThroughAssociation.superclass == a::HasManyAssociation
+ classes << a::HasManyThroughAssociation
+ end
+ }.each do |klass|
+ klass.send :include, Finder::ClassMethods
+ klass.class_eval { alias_method_chain :method_missing, :paginate }
+ end
+
+ # monkeypatch Rails ticket #2189: "count breaks has_many :through"
+ ActiveRecord::Base.class_eval do
+ protected
+ def self.construct_count_options_from_args(*args)
+ result = super
+ result[0] = '*' if result[0].is_a?(String) and result[0] =~ /\.\*$/
+ result
+ end
+ end
+ end
+
+ # Enable named_scope, a feature of Rails 2.1, even if you have older Rails
+ # (tested on Rails 2.0.2 and 1.2.6).
+ #
+ # You can pass +false+ for +patch+ parameter to skip monkeypatching
+ # *associations*. Use this if you feel that <tt>named_scope</tt> broke
+ # has_many, has_many :through or has_and_belongs_to_many associations in
+ # your app. By passing +false+, you can still use <tt>named_scope</tt> in
+ # your models, but not through associations.
+ def enable_named_scope(patch = true)
+ return if defined? ActiveRecord::NamedScope
+ require 'will_paginate/named_scope'
+ require 'will_paginate/named_scope_patch' if patch
+
+ ActiveRecord::Base.send :include, WillPaginate::NamedScope
+ end
+ end
+
+ module Deprecation # :nodoc:
+ extend ActiveSupport::Deprecation
+
+ def self.warn(message, callstack = caller)
+ message = 'WillPaginate: ' + message.strip.gsub(/\s+/, ' ')
+ ActiveSupport::Deprecation.warn(message, callstack)
+ end
+ end
+end
+
+if defined? Rails
+ WillPaginate.enable_activerecord if defined? ActiveRecord
+ WillPaginate.enable_actionpack if defined? ActionController
+end
diff --git a/src/server/vendor/plugins/will_paginate/lib/will_paginate/array.rb b/src/server/vendor/plugins/will_paginate/lib/will_paginate/array.rb
new file mode 100644
index 0000000..d061d2b
--- /dev/null
+++ b/src/server/vendor/plugins/will_paginate/lib/will_paginate/array.rb
@@ -0,0 +1,16 @@
+require 'will_paginate/collection'
+
+# http://www.desimcadam.com/archives/8
+Array.class_eval do
+ def paginate(options = {})
+ raise ArgumentError, "parameter hash expected (got #{options.inspect})" unless Hash === options
+
+ WillPaginate::Collection.create(
+ options[:page] || 1,
+ options[:per_page] || 30,
+ options[:total_entries] || self.length
+ ) { |pager|
+ pager.replace self[pager.offset, pager.per_page].to_a
+ }
+ end
+end
diff --git a/src/server/vendor/plugins/will_paginate/lib/will_paginate/collection.rb b/src/server/vendor/plugins/will_paginate/lib/will_paginate/collection.rb
new file mode 100644
index 0000000..e253570
--- /dev/null
+++ b/src/server/vendor/plugins/will_paginate/lib/will_paginate/collection.rb
@@ -0,0 +1,146 @@
+module WillPaginate
+ # = Invalid page number error
+ # This is an ArgumentError raised in case a page was requested that is either
+ # zero or negative number. You should decide how do deal with such errors in
+ # the controller.
+ #
+ # If you're using Rails 2, then this error will automatically get handled like
+ # 404 Not Found. The hook is in "will_paginate.rb":
+ #
+ # ActionController::Base.rescue_responses['WillPaginate::InvalidPage'] = :not_found
+ #
+ # If you don't like this, use your preffered method of rescuing exceptions in
+ # public from your controllers to handle this differently. The +rescue_from+
+ # method is a nice addition to Rails 2.
+ #
+ # This error is *not* raised when a page further than the last page is
+ # requested. Use <tt>WillPaginate::Collection#out_of_bounds?</tt> method to
+ # check for those cases and manually deal with them as you see fit.
+ class InvalidPage < ArgumentError
+ def initialize(page, page_num)
+ super "#{page.inspect} given as value, which translates to '#{page_num}' as page number"
+ end
+ end
+
+ # = The key to pagination
+ # Arrays returned from paginating finds are, in fact, instances of this little
+ # class. You may think of WillPaginate::Collection as an ordinary array with
+ # some extra properties. Those properties are used by view helpers to generate
+ # correct page links.
+ #
+ # WillPaginate::Collection also assists in rolling out your own pagination
+ # solutions: see +create+.
+ #
+ # If you are writing a library that provides a collection which you would like
+ # to conform to this API, you don't have to copy these methods over; simply
+ # make your plugin/gem dependant on the "mislav-will_paginate" gem:
+ #
+ # gem 'mislav-will_paginate'
+ # require 'will_paginate/collection'
+ #
+ # # WillPaginate::Collection is now available for use
+ class Collection < Array
+ attr_reader :current_page, :per_page, :total_entries, :total_pages
+
+ # Arguments to the constructor are the current page number, per-page limit
+ # and the total number of entries. The last argument is optional because it
+ # is best to do lazy counting; in other words, count *conditionally* after
+ # populating the collection using the +replace+ method.
+ def initialize(page, per_page, total = nil)
+ @current_page = page.to_i
+ raise InvalidPage.new(page, @current_page) if @current_page < 1
+ @per_page = per_page.to_i
+ raise ArgumentError, "`per_page` setting cannot be less than 1 (#{@per_page} given)" if @per_page < 1
+
+ self.total_entries = total if total
+ end
+
+ # Just like +new+, but yields the object after instantiation and returns it
+ # afterwards. This is very useful for manual pagination:
+ #
+ # @entries = WillPaginate::Collection.create(1, 10) do |pager|
+ # result = Post.find(:all, :limit => pager.per_page, :offset => pager.offset)
+ # # inject the result array into the paginated collection:
+ # pager.replace(result)
+ #
+ # unless pager.total_entries
+ # # the pager didn't manage to guess the total count, do it manually
+ # pager.total_entries = Post.count
+ # end
+ # end
+ #
+ # The possibilities with this are endless. For another example, here is how
+ # WillPaginate used to define pagination for Array instances:
+ #
+ # Array.class_eval do
+ # def paginate(page = 1, per_page = 15)
+ # WillPaginate::Collection.create(page, per_page, size) do |pager|
+ # pager.replace self[pager.offset, pager.per_page].to_a
+ # end
+ # end
+ # end
+ #
+ # The Array#paginate API has since then changed, but this still serves as a
+ # fine example of WillPaginate::Collection usage.
+ def self.create(page, per_page, total = nil)
+ pager = new(page, per_page, total)
+ yield pager
+ pager
+ end
+
+ # Helper method that is true when someone tries to fetch a page with a
+ # larger number than the last page. Can be used in combination with flashes
+ # and redirecting.
+ def out_of_bounds?
+ current_page > total_pages
+ end
+
+ # Current offset of the paginated collection. If we're on the first page,
+ # it is always 0. If we're on the 2nd page and there are 30 entries per page,
+ # the offset is 30. This property is useful if you want to render ordinals
+ # side by side with records in the view: simply start with offset + 1.
+ def offset
+ (current_page - 1) * per_page
+ end
+
+ # current_page - 1 or nil if there is no previous page
+ def previous_page
+ current_page > 1 ? (current_page - 1) : nil
+ end
+
+ # current_page + 1 or nil if there is no next page
+ def next_page
+ current_page < total_pages ? (current_page + 1) : nil
+ end
+
+ # sets the <tt>total_entries</tt> property and calculates <tt>total_pages</tt>
+ def total_entries=(number)
+ @total_entries = number.to_i
+ @total_pages = (@total_entries / per_page.to_f).ceil
+ end
+
+ # This is a magic wrapper for the original Array#replace method. It serves
+ # for populating the paginated collection after initialization.
+ #
+ # Why magic? Because it tries to guess the total number of entries judging
+ # by the size of given array. If it is shorter than +per_page+ limit, then we
+ # know we're on the last page. This trick is very useful for avoiding
+ # unnecessary hits to the database to do the counting after we fetched the
+ # data for the current page.
+ #
+ # However, after using +replace+ you should always test the value of
+ # +total_entries+ and set it to a proper value if it's +nil+. See the example
+ # in +create+.
+ def replace(array)
+ result = super
+
+ # The collection is shorter then page limit? Rejoice, because
+ # then we know that we are on the last page!
+ if total_entries.nil? and length < per_page and (current_page == 1 or length > 0)
+ self.total_entries = offset + length
+ end
+
+ result
+ end
+ end
+end
diff --git a/src/server/vendor/plugins/will_paginate/lib/will_paginate/core_ext.rb b/src/server/vendor/plugins/will_paginate/lib/will_paginate/core_ext.rb
new file mode 100644
index 0000000..3397736
--- /dev/null
+++ b/src/server/vendor/plugins/will_paginate/lib/will_paginate/core_ext.rb
@@ -0,0 +1,43 @@
+require 'set'
+require 'will_paginate/array'
+
+# helper to check for method existance in ruby 1.8- and 1.9-compatible way
+# because `methods`, `instance_methods` and others return strings in 1.8 and symbols in 1.9
+#
+# ['foo', 'bar'].include_method?(:foo) # => true
+class Array
+ def include_method?(name)
+ name = name.to_sym
+ !!(find { |item| item.to_sym == name })
+ end
+end
+
+unless Hash.instance_methods.include_method? :except
+ Hash.class_eval do
+ # Returns a new hash without the given keys.
+ def except(*keys)
+ rejected = Set.new(respond_to?(:convert_key) ? keys.map { |key| convert_key(key) } : keys)
+ reject { |key,| rejected.include?(key) }
+ end
+
+ # Replaces the hash without only the given keys.
+ def except!(*keys)
+ replace(except(*keys))
+ end
+ end
+end
+
+unless Hash.instance_methods.include_method? :slice
+ Hash.class_eval do
+ # Returns a new hash with only the given keys.
+ def slice(*keys)
+ allowed = Set.new(respond_to?(:convert_key) ? keys.map { |key| convert_key(key) } : keys)
+ reject { |key,| !allowed.include?(key) }
+ end
+
+ # Replaces the hash with only the given keys.
+ def slice!(*keys)
+ replace(slice(*keys))
+ end
+ end
+end
diff --git a/src/server/vendor/plugins/will_paginate/lib/will_paginate/finder.rb b/src/server/vendor/plugins/will_paginate/lib/will_paginate/finder.rb
new file mode 100644
index 0000000..b80602b
--- /dev/null
+++ b/src/server/vendor/plugins/will_paginate/lib/will_paginate/finder.rb
@@ -0,0 +1,264 @@
+require 'will_paginate/core_ext'
+
+module WillPaginate
+ # A mixin for ActiveRecord::Base. Provides +per_page+ class method
+ # and hooks things up to provide paginating finders.
+ #
+ # Find out more in WillPaginate::Finder::ClassMethods
+ #
+ module Finder
+ def self.included(base)
+ base.extend ClassMethods
+ class << base
+ alias_method_chain :method_missing, :paginate
+ # alias_method_chain :find_every, :paginate
+ define_method(:per_page) { 30 } unless respond_to?(:per_page)
+ end
+ end
+
+ # = Paginating finders for ActiveRecord models
+ #
+ # WillPaginate adds +paginate+, +per_page+ and other methods to
+ # ActiveRecord::Base class methods and associations. It also hooks into
+ # +method_missing+ to intercept pagination calls to dynamic finders such as
+ # +paginate_by_user_id+ and translate them to ordinary finders
+ # (+find_all_by_user_id+ in this case).
+ #
+ # In short, paginating finders are equivalent to ActiveRecord finders; the
+ # only difference is that we start with "paginate" instead of "find" and
+ # that <tt>:page</tt> is required parameter:
+ #
+ # @posts = Post.paginate :all, :page => params[:page], :order => 'created_at DESC'
+ #
+ # In paginating finders, "all" is implicit. There is no sense in paginating
+ # a single record, right? So, you can drop the <tt>:all</tt> argument:
+ #
+ # Post.paginate(...) => Post.find :all
+ # Post.paginate_all_by_something => Post.find_all_by_something
+ # Post.paginate_by_something => Post.find_all_by_something
+ #
+ # == The importance of the <tt>:order</tt> parameter
+ #
+ # In ActiveRecord finders, <tt>:order</tt> parameter specifies columns for
+ # the <tt>ORDER BY</tt> clause in SQL. It is important to have it, since
+ # pagination only makes sense with ordered sets. Without the <tt>ORDER
+ # BY</tt> clause, databases aren't required to do consistent ordering when
+ # performing <tt>SELECT</tt> queries; this is especially true for
+ # PostgreSQL.
+ #
+ # Therefore, make sure you are doing ordering on a column that makes the
+ # most sense in the current context. Make that obvious to the user, also.
+ # For perfomance reasons you will also want to add an index to that column.
+ module ClassMethods
+ # This is the main paginating finder.
+ #
+ # == Special parameters for paginating finders
+ # * <tt>:page</tt> -- REQUIRED, but defaults to 1 if false or nil
+ # * <tt>:per_page</tt> -- defaults to <tt>CurrentModel.per_page</tt> (which is 30 if not overridden)
+ # * <tt>:total_entries</tt> -- use only if you manually count total entries
+ # * <tt>:count</tt> -- additional options that are passed on to +count+
+ # * <tt>:finder</tt> -- name of the ActiveRecord finder used (default: "find")
+ #
+ # All other options (+conditions+, +order+, ...) are forwarded to +find+
+ # and +count+ calls.
+ def paginate(*args)
+ options = args.pop
+ page, per_page, total_entries = wp_parse_options(options)
+ finder = (options[:finder] || 'find').to_s
+
+ if finder == 'find'
+ # an array of IDs may have been given:
+ total_entries ||= (Array === args.first and args.first.size)
+ # :all is implicit
+ args.unshift(:all) if args.empty?
+ end
+
+ WillPaginate::Collection.create(page, per_page, total_entries) do |pager|
+ count_options = options.except :page, :per_page, :total_entries, :finder
+ find_options = count_options.except(:count).update(:offset => pager.offset, :limit => pager.per_page)
+
+ args << find_options
+ # @options_from_last_find = nil
+ pager.replace(send(finder, *args) { |*a| yield(*a) if block_given? })
+
+ # magic counting for user convenience:
+ pager.total_entries = wp_count(count_options, args, finder) unless pager.total_entries
+ end
+ end
+
+ # Iterates through all records by loading one page at a time. This is useful
+ # for migrations or any other use case where you don't want to load all the
+ # records in memory at once.
+ #
+ # It uses +paginate+ internally; therefore it accepts all of its options.
+ # You can specify a starting page with <tt>:page</tt> (default is 1). Default
+ # <tt>:order</tt> is <tt>"id"</tt>, override if necessary.
+ #
+ # See {Faking Cursors in ActiveRecord}[http://weblog.jamisbuck.org/2007/4/6/faking-cursors-in-activerecord]
+ # where Jamis Buck describes this and a more efficient way for MySQL.
+ def paginated_each(options = {})
+ options = { :order => 'id', :page => 1 }.merge options
+ options[:page] = options[:page].to_i
+ options[:total_entries] = 0 # skip the individual count queries
+ total = 0
+
+ begin
+ collection = paginate(options)
+ with_exclusive_scope(:find => {}) do
+ # using exclusive scope so that the block is yielded in scope-free context
+ total += collection.each { |item| yield item }.size
+ end
+ options[:page] += 1
+ end until collection.size < collection.per_page
+
+ total
+ end
+
+ # Wraps +find_by_sql+ by simply adding LIMIT and OFFSET to your SQL string
+ # based on the params otherwise used by paginating finds: +page+ and
+ # +per_page+.
+ #
+ # Example:
+ #
+ # @developers = Developer.paginate_by_sql ['select * from developers where salary > ?', 80000],
+ # :page => params[:page], :per_page => 3
+ #
+ # A query for counting rows will automatically be generated if you don't
+ # supply <tt>:total_entries</tt>. If you experience problems with this
+ # generated SQL, you might want to perform the count manually in your
+ # application.
+ #
+ def paginate_by_sql(sql, options)
+ WillPaginate::Collection.create(*wp_parse_options(options)) do |pager|
+ query = sanitize_sql(sql.dup)
+ original_query = query.dup
+ # add limit, offset
+ add_limit! query, :offset => pager.offset, :limit => pager.per_page
+ # perfom the find
+ pager.replace find_by_sql(query)
+
+ unless pager.total_entries
+ count_query = original_query.sub /\bORDER\s+BY\s+[\w`,\s]+$/mi, ''
+ count_query = "SELECT COUNT(*) FROM (#{count_query})"
+
+ unless self.connection.adapter_name =~ /^(oracle|oci$)/i
+ count_query << ' AS count_table'
+ end
+ # perform the count query
+ pager.total_entries = count_by_sql(count_query)
+ end
+ end
+ end
+
+ def respond_to?(method, include_priv = false) #:nodoc:
+ case method.to_sym
+ when :paginate, :paginate_by_sql
+ true
+ else
+ super(method.to_s.sub(/^paginate/, 'find'), include_priv)
+ end
+ end
+
+ protected
+
+ def method_missing_with_paginate(method, *args) #:nodoc:
+ # did somebody tried to paginate? if not, let them be
+ unless method.to_s.index('paginate') == 0
+ if block_given?
+ return method_missing_without_paginate(method, *args) { |*a| yield(*a) }
+ else
+ return method_missing_without_paginate(method, *args)
+ end
+ end
+
+ # paginate finders are really just find_* with limit and offset
+ finder = method.to_s.sub('paginate', 'find')
+ finder.sub!('find', 'find_all') if finder.index('find_by_') == 0
+
+ options = args.pop
+ raise ArgumentError, 'parameter hash expected' unless options.respond_to? :symbolize_keys
+ options = options.dup
+ options[:finder] = finder
+ args << options
+
+ paginate(*args) { |*a| yield(*a) if block_given? }
+ end
+
+ # Does the not-so-trivial job of finding out the total number of entries
+ # in the database. It relies on the ActiveRecord +count+ method.
+ def wp_count(options, args, finder)
+ excludees = [:count, :order, :limit, :offset, :readonly]
+ excludees << :from unless ActiveRecord::Calculations::CALCULATIONS_OPTIONS.include?(:from)
+
+ # we may be in a model or an association proxy
+ klass = (@owner and @reflection) ? @reflection.klass : self
+
+ # Use :select from scope if it isn't already present.
+ options[:select] = scope(:find, :select) unless options[:select]
+
+ if options[:select] and options[:select] =~ /^\s*DISTINCT\b/i
+ # Remove quoting and check for table_name.*-like statement.
+ if options[:select].gsub('`', '') =~ /\w+\.\*/
+ options[:select] = "DISTINCT #{klass.table_name}.#{klass.primary_key}"
+ end
+ else
+ excludees << :select # only exclude the select param if it doesn't begin with DISTINCT
+ end
+
+ # count expects (almost) the same options as find
+ count_options = options.except *excludees
+
+ # merge the hash found in :count
+ # this allows you to specify :select, :order, or anything else just for the count query
+ count_options.update options[:count] if options[:count]
+
+ # forget about includes if they are irrelevant (Rails 2.1)
+ if count_options[:include] and
+ klass.private_methods.include_method?(:references_eager_loaded_tables?) and
+ !klass.send(:references_eager_loaded_tables?, count_options)
+ count_options.delete :include
+ end
+
+ # we may have to scope ...
+ counter = Proc.new { count(count_options) }
+
+ count = if finder.index('find_') == 0 and klass.respond_to?(scoper = finder.sub('find', 'with'))
+ # scope_out adds a 'with_finder' method which acts like with_scope, if it's present
+ # then execute the count with the scoping provided by the with_finder
+ send(scoper, &counter)
+ elsif finder =~ /^find_(all_by|by)_([_a-zA-Z]\w*)$/
+ # extract conditions from calls like "paginate_by_foo_and_bar"
+ attribute_names = $2.split('_and_')
+ conditions = construct_attributes_from_arguments(attribute_names, args)
+ with_scope(:find => { :conditions => conditions }, &counter)
+ else
+ counter.call
+ end
+
+ count.respond_to?(:length) ? count.length : count
+ end
+
+ def wp_parse_options(options) #:nodoc:
+ raise ArgumentError, 'parameter hash expected' unless options.respond_to? :symbolize_keys
+ options = options.symbolize_keys
+ raise ArgumentError, ':page parameter required' unless options.key? :page
+
+ if options[:count] and options[:total_entries]
+ raise ArgumentError, ':count and :total_entries are mutually exclusive'
+ end
+
+ page = options[:page] || 1
+ per_page = options[:per_page] || self.per_page
+ total = options[:total_entries]
+ [page, per_page, total]
+ end
+
+ private
+
+ # def find_every_with_paginate(options)
+ # @options_from_last_find = options
+ # find_every_without_paginate(options)
+ # end
+ end
+ end
+end
diff --git a/src/server/vendor/plugins/will_paginate/lib/will_paginate/named_scope.rb b/src/server/vendor/plugins/will_paginate/lib/will_paginate/named_scope.rb
new file mode 100644
index 0000000..5a743d7
--- /dev/null
+++ b/src/server/vendor/plugins/will_paginate/lib/will_paginate/named_scope.rb
@@ -0,0 +1,170 @@
+module WillPaginate
+ # This is a feature backported from Rails 2.1 because of its usefullness not only with will_paginate,
+ # but in other aspects when managing complex conditions that you want to be reusable.
+ module NamedScope
+ # All subclasses of ActiveRecord::Base have two named_scopes:
+ # * <tt>all</tt>, which is similar to a <tt>find(:all)</tt> query, and
+ # * <tt>scoped</tt>, which allows for the creation of anonymous scopes, on the fly: <tt>Shirt.scoped(:conditions => {:color => 'red'}).scoped(:include => :washing_instructions)</tt>
+ #
+ # These anonymous scopes tend to be useful when procedurally generating complex queries, where passing
+ # intermediate values (scopes) around as first-class objects is convenient.
+ def self.included(base)
+ base.class_eval do
+ extend ClassMethods
+ named_scope :scoped, lambda { |scope| scope }
+ end
+ end
+
+ module ClassMethods
+ def scopes
+ read_inheritable_attribute(:scopes) || write_inheritable_attribute(:scopes, {})
+ end
+
+ # Adds a class method for retrieving and querying objects. A scope represents a narrowing of a database query,
+ # such as <tt>:conditions => {:color => :red}, :select => 'shirts.*', :include => :washing_instructions</tt>.
+ #
+ # class Shirt < ActiveRecord::Base
+ # named_scope :red, :conditions => {:color => 'red'}
+ # named_scope :dry_clean_only, :joins => :washing_instructions, :conditions => ['washing_instructions.dry_clean_only = ?', true]
+ # end
+ #
+ # The above calls to <tt>named_scope</tt> define class methods <tt>Shirt.red</tt> and <tt>Shirt.dry_clean_only</tt>. <tt>Shirt.red</tt>,
+ # in effect, represents the query <tt>Shirt.find(:all, :conditions => {:color => 'red'})</tt>.
+ #
+ # Unlike Shirt.find(...), however, the object returned by <tt>Shirt.red</tt> is not an Array; it resembles the association object
+ # constructed by a <tt>has_many</tt> declaration. For instance, you can invoke <tt>Shirt.red.find(:first)</tt>, <tt>Shirt.red.count</tt>,
+ # <tt>Shirt.red.find(:all, :conditions => {:size => 'small'})</tt>. Also, just
+ # as with the association objects, name scopes acts like an Array, implementing Enumerable; <tt>Shirt.red.each(&block)</tt>,
+ # <tt>Shirt.red.first</tt>, and <tt>Shirt.red.inject(memo, &block)</tt> all behave as if Shirt.red really were an Array.
+ #
+ # These named scopes are composable. For instance, <tt>Shirt.red.dry_clean_only</tt> will produce all shirts that are both red and dry clean only.
+ # Nested finds and calculations also work with these compositions: <tt>Shirt.red.dry_clean_only.count</tt> returns the number of garments
+ # for which these criteria obtain. Similarly with <tt>Shirt.red.dry_clean_only.average(:thread_count)</tt>.
+ #
+ # All scopes are available as class methods on the ActiveRecord::Base descendent upon which the scopes were defined. But they are also available to
+ # <tt>has_many</tt> associations. If,
+ #
+ # class Person < ActiveRecord::Base
+ # has_many :shirts
+ # end
+ #
+ # then <tt>elton.shirts.red.dry_clean_only</tt> will return all of Elton's red, dry clean
+ # only shirts.
+ #
+ # Named scopes can also be procedural.
+ #
+ # class Shirt < ActiveRecord::Base
+ # named_scope :colored, lambda { |color|
+ # { :conditions => { :color => color } }
+ # }
+ # end
+ #
+ # In this example, <tt>Shirt.colored('puce')</tt> finds all puce shirts.
+ #
+ # Named scopes can also have extensions, just as with <tt>has_many</tt> declarations:
+ #
+ # class Shirt < ActiveRecord::Base
+ # named_scope :red, :conditions => {:color => 'red'} do
+ # def dom_id
+ # 'red_shirts'
+ # end
+ # end
+ # end
+ #
+ #
+ # For testing complex named scopes, you can examine the scoping options using the
+ # <tt>proxy_options</tt> method on the proxy itself.
+ #
+ # class Shirt < ActiveRecord::Base
+ # named_scope :colored, lambda { |color|
+ # { :conditions => { :color => color } }
+ # }
+ # end
+ #
+ # expected_options = { :conditions => { :colored => 'red' } }
+ # assert_equal expected_options, Shirt.colored('red').proxy_options
+ def named_scope(name, options = {})
+ name = name.to_sym
+ scopes[name] = lambda do |parent_scope, *args|
+ Scope.new(parent_scope, case options
+ when Hash
+ options
+ when Proc
+ options.call(*args)
+ end) { |*a| yield(*a) if block_given? }
+ end
+ (class << self; self end).instance_eval do
+ define_method name do |*args|
+ scopes[name].call(self, *args)
+ end
+ end
+ end
+ end
+
+ class Scope
+ attr_reader :proxy_scope, :proxy_options
+
+ [].methods.each do |m|
+ unless m =~ /(^__|^nil\?|^send|^object_id$|class|extend|^find$|count|sum|average|maximum|minimum|paginate|first|last|empty\?|respond_to\?)/
+ delegate m, :to => :proxy_found
+ end
+ end
+
+ delegate :scopes, :with_scope, :to => :proxy_scope
+
+ def initialize(proxy_scope, options)
+ [options[:extend]].flatten.each { |extension| extend extension } if options[:extend]
+ extend Module.new { |*args| yield(*args) } if block_given?
+ @proxy_scope, @proxy_options = proxy_scope, options.except(:extend)
+ end
+
+ def reload
+ load_found; self
+ end
+
+ def first(*args)
+ if args.first.kind_of?(Integer) || (@found && !args.first.kind_of?(Hash))
+ proxy_found.first(*args)
+ else
+ find(:first, *args)
+ end
+ end
+
+ def last(*args)
+ if args.first.kind_of?(Integer) || (@found && !args.first.kind_of?(Hash))
+ proxy_found.last(*args)
+ else
+ find(:last, *args)
+ end
+ end
+
+ def empty?
+ @found ? @found.empty? : count.zero?
+ end
+
+ def respond_to?(method, include_private = false)
+ super || @proxy_scope.respond_to?(method, include_private)
+ end
+
+ protected
+ def proxy_found
+ @found || load_found
+ end
+
+ private
+ def method_missing(method, *args)
+ if scopes.include?(method)
+ scopes[method].call(self, *args)
+ else
+ with_scope :find => proxy_options do
+ proxy_scope.send(method, *args) { |*a| yield(*a) if block_given? }
+ end
+ end
+ end
+
+ def load_found
+ @found = find(:all)
+ end
+ end
+ end
+end
diff --git a/src/server/vendor/plugins/will_paginate/lib/will_paginate/named_scope_patch.rb b/src/server/vendor/plugins/will_paginate/lib/will_paginate/named_scope_patch.rb
new file mode 100644
index 0000000..7daff59
--- /dev/null
+++ b/src/server/vendor/plugins/will_paginate/lib/will_paginate/named_scope_patch.rb
@@ -0,0 +1,37 @@
+ActiveRecord::Associations::AssociationProxy.class_eval do
+ protected
+ def with_scope(*args)
+ @reflection.klass.send(:with_scope, *args) { |*a| yield(*a) if block_given? }
+ end
+end
+
+[ ActiveRecord::Associations::AssociationCollection,
+ ActiveRecord::Associations::HasManyThroughAssociation ].each do |klass|
+ klass.class_eval do
+ protected
+ alias :method_missing_without_scopes :method_missing_without_paginate
+ def method_missing_without_paginate(method, *args)
+ if @reflection.klass.scopes.include?(method)
+ @reflection.klass.scopes[method].call(self, *args) { |*a| yield(*a) if block_given? }
+ else
+ method_missing_without_scopes(method, *args) { |*a| yield(*a) if block_given? }
+ end
+ end
+ end
+end
+
+# Rails 1.2.6
+ActiveRecord::Associations::HasAndBelongsToManyAssociation.class_eval do
+ protected
+ def method_missing(method, *args)
+ if @target.respond_to?(method) || (!@reflection.klass.respond_to?(method) && Class.respond_to?(method))
+ super
+ elsif @reflection.klass.scopes.include?(method)
+ @reflection.klass.scopes[method].call(self, *args)
+ else
+ @reflection.klass.with_scope(:find => { :conditions => @finder_sql, :joins => @join_sql, :readonly => false }) do
+ @reflection.klass.send(method, *args) { |*a| yield(*a) if block_given? }
+ end
+ end
+ end
+end if ActiveRecord::Base.respond_to? :find_first
diff --git a/src/server/vendor/plugins/will_paginate/lib/will_paginate/version.rb b/src/server/vendor/plugins/will_paginate/lib/will_paginate/version.rb
new file mode 100644
index 0000000..bb879b5
--- /dev/null
+++ b/src/server/vendor/plugins/will_paginate/lib/will_paginate/version.rb
@@ -0,0 +1,9 @@
+module WillPaginate
+ module VERSION
+ MAJOR = 2
+ MINOR = 3
+ TINY = 11
+
+ STRING = [MAJOR, MINOR, TINY].join('.')
+ end
+end
diff --git a/src/server/vendor/plugins/will_paginate/lib/will_paginate/view_helpers.rb b/src/server/vendor/plugins/will_paginate/lib/will_paginate/view_helpers.rb
new file mode 100644
index 0000000..bb87a41
--- /dev/null
+++ b/src/server/vendor/plugins/will_paginate/lib/will_paginate/view_helpers.rb
@@ -0,0 +1,404 @@
+require 'will_paginate/core_ext'
+
+module WillPaginate
+ # = Will Paginate view helpers
+ #
+ # The main view helper, #will_paginate, renders
+ # pagination links for the given collection. The helper itself is lightweight
+ # and serves only as a wrapper around LinkRenderer instantiation; the
+ # renderer then does all the hard work of generating the HTML.
+ #
+ # == Global options for helpers
+ #
+ # Options for pagination helpers are optional and get their default values from the
+ # <tt>WillPaginate::ViewHelpers.pagination_options</tt> hash. You can write to this hash to
+ # override default options on the global level:
+ #
+ # WillPaginate::ViewHelpers.pagination_options[:previous_label] = 'Previous page'
+ #
+ # By putting this into "config/initializers/will_paginate.rb" (or simply environment.rb in
+ # older versions of Rails) you can easily translate link texts to previous
+ # and next pages, as well as override some other defaults to your liking.
+ module ViewHelpers
+ # default options that can be overridden on the global level
+ @@pagination_options = {
+ :class => 'pagination',
+ :previous_label => '« Previous',
+ :next_label => 'Next »',
+ :inner_window => 4, # links around the current page
+ :outer_window => 1, # links around beginning and end
+ :separator => ' ', # single space is friendly to spiders and non-graphic browsers
+ :param_name => :page,
+ :params => nil,
+ :renderer => 'WillPaginate::LinkRenderer',
+ :page_links => true,
+ :container => true
+ }
+ mattr_reader :pagination_options
+
+ # Renders Digg/Flickr-style pagination for a WillPaginate::Collection
+ # object. Nil is returned if there is only one page in total; no point in
+ # rendering the pagination in that case...
+ #
+ # ==== Options
+ # Display options:
+ # * <tt>:previous_label</tt> -- default: "« Previous" (this parameter is called <tt>:prev_label</tt> in versions <b>2.3.2</b> and older!)
+ # * <tt>:next_label</tt> -- default: "Next »"
+ # * <tt>:page_links</tt> -- when false, only previous/next links are rendered (default: true)
+ # * <tt>:inner_window</tt> -- how many links are shown around the current page (default: 4)
+ # * <tt>:outer_window</tt> -- how many links are around the first and the last page (default: 1)
+ # * <tt>:separator</tt> -- string separator for page HTML elements (default: single space)
+ #
+ # HTML options:
+ # * <tt>:class</tt> -- CSS class name for the generated DIV (default: "pagination")
+ # * <tt>:container</tt> -- toggles rendering of the DIV container for pagination links, set to
+ # false only when you are rendering your own pagination markup (default: true)
+ # * <tt>:id</tt> -- HTML ID for the container (default: nil). Pass +true+ to have the ID
+ # automatically generated from the class name of objects in collection: for example, paginating
+ # ArticleComment models would yield an ID of "article_comments_pagination".
+ #
+ # Advanced options:
+ # * <tt>:param_name</tt> -- parameter name for page number in URLs (default: <tt>:page</tt>)
+ # * <tt>:params</tt> -- additional parameters when generating pagination links
+ # (eg. <tt>:controller => "foo", :action => nil</tt>)
+ # * <tt>:renderer</tt> -- class name, class or instance of a link renderer (default:
+ # <tt>WillPaginate::LinkRenderer</tt>)
+ #
+ # All options not recognized by will_paginate will become HTML attributes on the container
+ # element for pagination links (the DIV). For example:
+ #
+ # <%= will_paginate @posts, :style => 'font-size: small' %>
+ #
+ # ... will result in:
+ #
+ # <div class="pagination" style="font-size: small"> ... </div>
+ #
+ # ==== Using the helper without arguments
+ # If the helper is called without passing in the collection object, it will
+ # try to read from the instance variable inferred by the controller name.
+ # For example, calling +will_paginate+ while the current controller is
+ # PostsController will result in trying to read from the <tt>@posts</tt>
+ # variable. Example:
+ #
+ # <%= will_paginate :id => true %>
+ #
+ # ... will result in <tt>@post</tt> collection getting paginated:
+ #
+ # <div class="pagination" id="posts_pagination"> ... </div>
+ #
+ def will_paginate(collection = nil, options = {})
+ options, collection = collection, nil if collection.is_a? Hash
+ unless collection or !controller
+ collection_name = "@#{controller.controller_name}"
+ collection = instance_variable_get(collection_name)
+ raise ArgumentError, "The #{collection_name} variable appears to be empty. Did you " +
+ "forget to pass the collection object for will_paginate?" unless collection
+ end
+ # early exit if there is nothing to render
+ return nil unless WillPaginate::ViewHelpers.total_pages_for_collection(collection) > 1
+
+ options = options.symbolize_keys.reverse_merge WillPaginate::ViewHelpers.pagination_options
+ if options[:prev_label]
+ WillPaginate::Deprecation::warn(":prev_label view parameter is now :previous_label; the old name has been deprecated", caller)
+ options[:previous_label] = options.delete(:prev_label)
+ end
+
+ # get the renderer instance
+ renderer = case options[:renderer]
+ when String
+ options[:renderer].to_s.constantize.new
+ when Class
+ options[:renderer].new
+ else
+ options[:renderer]
+ end
+ # render HTML for pagination
+ renderer.prepare collection, options, self
+ renderer.to_html
+ end
+
+ # Wrapper for rendering pagination links at both top and bottom of a block
+ # of content.
+ #
+ # <% paginated_section @posts do %>
+ # <ol id="posts">
+ # <% for post in @posts %>
+ # <li> ... </li>
+ # <% end %>
+ # </ol>
+ # <% end %>
+ #
+ # will result in:
+ #
+ # <div class="pagination"> ... </div>
+ # <ol id="posts">
+ # ...
+ # </ol>
+ # <div class="pagination"> ... </div>
+ #
+ # Arguments are passed to a <tt>will_paginate</tt> call, so the same options
+ # apply. Don't use the <tt>:id</tt> option; otherwise you'll finish with two
+ # blocks of pagination links sharing the same ID (which is invalid HTML).
+ def paginated_section(*args, &block)
+ pagination = will_paginate(*args).to_s
+
+ unless ActionView::Base.respond_to? :erb_variable
+ concat pagination
+ yield
+ concat pagination
+ else
+ content = pagination + capture(&block) + pagination
+ concat(content, block.binding)
+ end
+ end
+
+ # Renders a helpful message with numbers of displayed vs. total entries.
+ # You can use this as a blueprint for your own, similar helpers.
+ #
+ # <%= page_entries_info @posts %>
+ # #-> Displaying posts 6 - 10 of 26 in total
+ #
+ # By default, the message will use the humanized class name of objects
+ # in collection: for instance, "project types" for ProjectType models.
+ # Override this with the <tt>:entry_name</tt> parameter:
+ #
+ # <%= page_entries_info @posts, :entry_name => 'item' %>
+ # #-> Displaying items 6 - 10 of 26 in total
+ def page_entries_info(collection, options = {})
+ entry_name = options[:entry_name] ||
+ (collection.empty?? 'entry' : collection.first.class.name.underscore.sub('_', ' '))
+
+ if collection.total_pages < 2
+ case collection.size
+ when 0; "No #{entry_name.pluralize} found"
+ when 1; "Displaying <b>1</b> #{entry_name}"
+ else; "Displaying <b>all #{collection.size}</b> #{entry_name.pluralize}"
+ end
+ else
+ %{Displaying #{entry_name.pluralize} <b>%d - %d</b> of <b>%d</b> in total} % [
+ collection.offset + 1,
+ collection.offset + collection.length,
+ collection.total_entries
+ ]
+ end
+ end
+
+ def self.total_pages_for_collection(collection) #:nodoc:
+ if collection.respond_to?('page_count') and !collection.respond_to?('total_pages')
+ WillPaginate::Deprecation.warn %{
+ You are using a paginated collection of class #{collection.class.name}
+ which conforms to the old API of WillPaginate::Collection by using
+ `page_count`, while the current method name is `total_pages`. Please
+ upgrade yours or 3rd-party code that provides the paginated collection}, caller
+ class << collection
+ def total_pages; page_count; end
+ end
+ end
+ collection.total_pages
+ end
+ end
+
+ # This class does the heavy lifting of actually building the pagination
+ # links. It is used by the <tt>will_paginate</tt> helper internally.
+ class LinkRenderer
+
+ # The gap in page links is represented by:
+ #
+ # <span class="gap">…</span>
+ attr_accessor :gap_marker
+
+ def initialize
+ @gap_marker = '<span class="gap">…</span>'
+ end
+
+ # * +collection+ is a WillPaginate::Collection instance or any other object
+ # that conforms to that API
+ # * +options+ are forwarded from +will_paginate+ view helper
+ # * +template+ is the reference to the template being rendered
+ def prepare(collection, options, template)
+ @collection = collection
+ @options = options
+ @template = template
+
+ # reset values in case we're re-using this instance
+ @total_pages = @param_name = @url_string = nil
+ end
+
+ # Process it! This method returns the complete HTML string which contains
+ # pagination links. Feel free to subclass LinkRenderer and change this
+ # method as you see fit.
+ def to_html
+ links = @options[:page_links] ? windowed_links : []
+ # previous/next buttons
+ links.unshift page_link_or_span(@collection.previous_page, 'disabled prev_page', @options[:previous_label])
+ links.push page_link_or_span(@collection.next_page, 'disabled next_page', @options[:next_label])
+
+ html = links.join(@options[:separator])
+ @options[:container] ? @template.content_tag(:div, html, html_attributes) : html
+ end
+
+ # Returns the subset of +options+ this instance was initialized with that
+ # represent HTML attributes for the container element of pagination links.
+ def html_attributes
+ return @html_attributes if @html_attributes
+ @html_attributes = @options.except *(WillPaginate::ViewHelpers.pagination_options.keys - [:class])
+ # pagination of Post models will have the ID of "posts_pagination"
+ if @options[:container] and @options[:id] === true
+ @html_attributes[:id] = @collection.first.class.name.underscore.pluralize + '_pagination'
+ end
+ @html_attributes
+ end
+
+ protected
+
+ # Collects link items for visible page numbers.
+ def windowed_links
+ prev = nil
+
+ visible_page_numbers.inject [] do |links, n|
+ # detect gaps:
+ links << gap_marker if prev and n > prev + 1
+ links << page_link_or_span(n, 'current')
+ prev = n
+ links
+ end
+ end
+
+ # Calculates visible page numbers using the <tt>:inner_window</tt> and
+ # <tt>:outer_window</tt> options.
+ def visible_page_numbers
+ inner_window, outer_window = @options[:inner_window].to_i, @options[:outer_window].to_i
+ window_from = current_page - inner_window
+ window_to = current_page + inner_window
+
+ # adjust lower or upper limit if other is out of bounds
+ if window_to > total_pages
+ window_from -= window_to - total_pages
+ window_to = total_pages
+ end
+ if window_from < 1
+ window_to += 1 - window_from
+ window_from = 1
+ window_to = total_pages if window_to > total_pages
+ end
+
+ visible = (1..total_pages).to_a
+ left_gap = (2 + outer_window)...window_from
+ right_gap = (window_to + 1)...(total_pages - outer_window)
+ visible -= left_gap.to_a if left_gap.last - left_gap.first > 1
+ visible -= right_gap.to_a if right_gap.last - right_gap.first > 1
+
+ visible
+ end
+
+ def page_link_or_span(page, span_class, text = nil)
+ text ||= page.to_s
+
+ if page and page != current_page
+ classnames = span_class && span_class.index(' ') && span_class.split(' ', 2).last
+ page_link page, text, :rel => rel_value(page), :class => classnames
+ else
+ page_span page, text, :class => span_class
+ end
+ end
+
+ def page_link(page, text, attributes = {})
+ @template.link_to text, url_for(page), attributes
+ end
+
+ def page_span(page, text, attributes = {})
+ @template.content_tag :span, text, attributes
+ end
+
+ # Returns URL params for +page_link_or_span+, taking the current GET params
+ # and <tt>:params</tt> option into account.
+ def url_for(page)
+ page_one = page == 1
+ unless @url_string and !page_one
+ @url_params = {}
+ # page links should preserve GET parameters
+ stringified_merge @url_params, @template.params if @template.request.get?
+ stringified_merge @url_params, @options[:params] if @options[:params]
+
+ if complex = param_name.index(/[^\w-]/)
+ page_param = parse_query_parameters("#{param_name}=#{page}")
+
+ stringified_merge @url_params, page_param
+ else
+ @url_params[param_name] = page_one ? 1 : 2
+ end
+
+ url = @template.url_for(@url_params)
+ return url if page_one
+
+ if complex
+ @url_string = url.sub(%r!((?:\?|&)#{CGI.escape param_name}=)#{page}!, "\\1\0")
+ return url
+ else
+ @url_string = url
+ @url_params[param_name] = 3
+ @template.url_for(@url_params).split(//).each_with_index do |char, i|
+ if char == '3' and url[i, 1] == '2'
+ @url_string[i] = "\0"
+ break
+ end
+ end
+ end
+ end
+ # finally!
+ @url_string.sub "\0", page.to_s
+ end
+
+ private
+
+ def rel_value(page)
+ case page
+ when @collection.previous_page; 'prev' + (page == 1 ? ' start' : '')
+ when @collection.next_page; 'next'
+ when 1; 'start'
+ end
+ end
+
+ def current_page
+ @collection.current_page
+ end
+
+ def total_pages
+ @total_pages ||= WillPaginate::ViewHelpers.total_pages_for_collection(@collection)
+ end
+
+ def param_name
+ @param_name ||= @options[:param_name].to_s
+ end
+
+ # Recursively merge into target hash by using stringified keys from the other one
+ def stringified_merge(target, other)
+ other.each do |key, value|
+ key = key.to_s # this line is what it's all about!
+ existing = target[key]
+
+ if value.is_a?(Hash) and (existing.is_a?(Hash) or existing.nil?)
+ stringified_merge(existing || (target[key] = {}), value)
+ else
+ target[key] = value
+ end
+ end
+ end
+
+ def parse_query_parameters(params)
+ if defined? Rack::Utils
+ # For Rails > 2.3
+ Rack::Utils.parse_nested_query(params)
+ elsif defined?(ActionController::AbstractRequest)
+ ActionController::AbstractRequest.parse_query_parameters(params)
+ elsif defined?(ActionController::UrlEncodedPairParser)
+ # For Rails > 2.2
+ ActionController::UrlEncodedPairParser.parse_query_parameters(params)
+ elsif defined?(CGIMethods)
+ CGIMethods.parse_query_parameters(params)
+ else
+ raise "unsupported ActionPack version"
+ end
+ end
+ end
+end
diff --git a/src/server/vendor/plugins/will_paginate/test/boot.rb b/src/server/vendor/plugins/will_paginate/test/boot.rb
new file mode 100644
index 0000000..622fc93
--- /dev/null
+++ b/src/server/vendor/plugins/will_paginate/test/boot.rb
@@ -0,0 +1,21 @@
+plugin_root = File.join(File.dirname(__FILE__), '..')
+version = ENV['RAILS_VERSION']
+version = nil if version and version == ""
+
+# first look for a symlink to a copy of the framework
+if !version and framework_root = ["#{plugin_root}/rails", "#{plugin_root}/../../rails"].find { |p| File.directory? p }
+ puts "found framework root: #{framework_root}"
+ # this allows for a plugin to be tested outside of an app and without Rails gems
+ $:.unshift "#{framework_root}/activesupport/lib", "#{framework_root}/activerecord/lib", "#{framework_root}/actionpack/lib"
+else
+ # simply use installed gems if available
+ puts "using Rails#{version ? ' ' + version : nil} gems"
+ require 'rubygems'
+
+ if version
+ gem 'rails', version
+ else
+ gem 'actionpack'
+ gem 'activerecord'
+ end
+end
diff --git a/src/server/vendor/plugins/will_paginate/test/collection_test.rb b/src/server/vendor/plugins/will_paginate/test/collection_test.rb
new file mode 100644
index 0000000..a9336bb
--- /dev/null
+++ b/src/server/vendor/plugins/will_paginate/test/collection_test.rb
@@ -0,0 +1,143 @@
+require 'helper'
+require 'will_paginate/array'
+
+class ArrayPaginationTest < Test::Unit::TestCase
+
+ def setup ; end
+
+ def test_simple
+ collection = ('a'..'e').to_a
+
+ [{ :page => 1, :per_page => 3, :expected => %w( a b c ) },
+ { :page => 2, :per_page => 3, :expected => %w( d e ) },
+ { :page => 1, :per_page => 5, :expected => %w( a b c d e ) },
+ { :page => 3, :per_page => 5, :expected => [] },
+ ].
+ each do |conditions|
+ expected = conditions.delete :expected
+ assert_equal expected, collection.paginate(conditions)
+ end
+ end
+
+ def test_defaults
+ result = (1..50).to_a.paginate
+ assert_equal 1, result.current_page
+ assert_equal 30, result.size
+ end
+
+ def test_deprecated_api
+ assert_raise(ArgumentError) { [].paginate(2) }
+ assert_raise(ArgumentError) { [].paginate(2, 10) }
+ end
+
+ def test_total_entries_has_precedence
+ result = %w(a b c).paginate :total_entries => 5
+ assert_equal 5, result.total_entries
+ end
+
+ def test_argument_error_with_params_and_another_argument
+ assert_raise ArgumentError do
+ [].paginate({}, 5)
+ end
+ end
+
+ def test_paginated_collection
+ entries = %w(a b c)
+ collection = create(2, 3, 10) do |pager|
+ assert_equal entries, pager.replace(entries)
+ end
+
+ assert_equal entries, collection
+ assert_respond_to_all collection, %w(total_pages each offset size current_page per_page total_entries)
+ assert_kind_of Array, collection
+ assert_instance_of Array, collection.entries
+ assert_equal 3, collection.offset
+ assert_equal 4, collection.total_pages
+ assert !collection.out_of_bounds?
+ end
+
+ def test_previous_next_pages
+ collection = create(1, 1, 3)
+ assert_nil collection.previous_page
+ assert_equal 2, collection.next_page
+
+ collection = create(2, 1, 3)
+ assert_equal 1, collection.previous_page
+ assert_equal 3, collection.next_page
+
+ collection = create(3, 1, 3)
+ assert_equal 2, collection.previous_page
+ assert_nil collection.next_page
+ end
+
+ def test_out_of_bounds
+ entries = create(2, 3, 2){}
+ assert entries.out_of_bounds?
+
+ entries = create(1, 3, 2){}
+ assert !entries.out_of_bounds?
+ end
+
+ def test_guessing_total_count
+ entries = create do |pager|
+ # collection is shorter than limit
+ pager.replace array
+ end
+ assert_equal 8, entries.total_entries
+
+ entries = create(2, 5, 10) do |pager|
+ # collection is shorter than limit, but we have an explicit count
+ pager.replace array
+ end
+ assert_equal 10, entries.total_entries
+
+ entries = create do |pager|
+ # collection is the same as limit; we can't guess
+ pager.replace array(5)
+ end
+ assert_equal nil, entries.total_entries
+
+ entries = create do |pager|
+ # collection is empty; we can't guess
+ pager.replace array(0)
+ end
+ assert_equal nil, entries.total_entries
+
+ entries = create(1) do |pager|
+ # collection is empty and we're on page 1,
+ # so the whole thing must be empty, too
+ pager.replace array(0)
+ end
+ assert_equal 0, entries.total_entries
+ end
+
+ def test_invalid_page
+ bad_inputs = [0, -1, nil, '', 'Schnitzel']
+
+ bad_inputs.each do |bad|
+ assert_raise(WillPaginate::InvalidPage) { create bad }
+ end
+ end
+
+ def test_invalid_per_page_setting
+ assert_raise(ArgumentError) { create(1, -1) }
+ end
+
+ def test_page_count_was_removed
+ assert_raise(NoMethodError) { create.page_count }
+ # It's `total_pages` now.
+ end
+
+ private
+ def create(page = 2, limit = 5, total = nil, &block)
+ if block_given?
+ WillPaginate::Collection.create(page, limit, total, &block)
+ else
+ WillPaginate::Collection.new(page, limit, total)
+ end
+ end
+
+ def array(size = 3)
+ Array.new(size)
+ end
+end
diff --git a/src/server/vendor/plugins/will_paginate/test/console b/src/server/vendor/plugins/will_paginate/test/console
new file mode 100755
index 0000000..3f282f1
--- /dev/null
+++ b/src/server/vendor/plugins/will_paginate/test/console
@@ -0,0 +1,8 @@
+#!/usr/bin/env ruby
+irb = RUBY_PLATFORM =~ /(:?mswin|mingw)/ ? 'irb.bat' : 'irb'
+libs = []
+
+libs << 'irb/completion'
+libs << File.join('lib', 'load_fixtures')
+
+exec "#{irb} -Ilib:test#{libs.map{ |l| " -r #{l}" }.join} --simple-prompt"
diff --git a/src/server/vendor/plugins/will_paginate/test/database.yml b/src/server/vendor/plugins/will_paginate/test/database.yml
new file mode 100644
index 0000000..b2794c3
--- /dev/null
+++ b/src/server/vendor/plugins/will_paginate/test/database.yml
@@ -0,0 +1,22 @@
+sqlite3:
+ database: ":memory:"
+ adapter: sqlite3
+ timeout: 500
+
+sqlite2:
+ database: ":memory:"
+ adapter: sqlite2
+
+mysql:
+ adapter: mysql
+ username: root
+ password:
+ encoding: utf8
+ database: will_paginate_unittest
+
+postgres:
+ adapter: postgresql
+ username: mislav
+ password:
+ database: will_paginate_unittest
+ min_messages: warning
diff --git a/src/server/vendor/plugins/will_paginate/test/finder_test.rb b/src/server/vendor/plugins/will_paginate/test/finder_test.rb
new file mode 100644
index 0000000..a1eeb94
--- /dev/null
+++ b/src/server/vendor/plugins/will_paginate/test/finder_test.rb
@@ -0,0 +1,473 @@
+require 'helper'
+require 'lib/activerecord_test_case'
+
+require 'will_paginate'
+WillPaginate.enable_activerecord
+WillPaginate.enable_named_scope
+
+class FinderTest < ActiveRecordTestCase
+ fixtures :topics, :replies, :users, :projects, :developers_projects
+
+ def test_new_methods_presence
+ assert_respond_to_all Topic, %w(per_page paginate paginate_by_sql)
+ end
+
+ def test_simple_paginate
+ assert_queries(1) do
+ entries = Topic.paginate :page => nil
+ assert_equal 1, entries.current_page
+ assert_equal 1, entries.total_pages
+ assert_equal 4, entries.size
+ end
+
+ assert_queries(2) do
+ entries = Topic.paginate :page => 2
+ assert_equal 1, entries.total_pages
+ assert entries.empty?
+ end
+ end
+
+ def test_parameter_api
+ # :page parameter in options is required!
+ assert_raise(ArgumentError){ Topic.paginate }
+ assert_raise(ArgumentError){ Topic.paginate({}) }
+
+ # explicit :all should not break anything
+ assert_equal Topic.paginate(:page => nil), Topic.paginate(:all, :page => 1)
+
+ # :count could be nil and we should still not cry
+ assert_nothing_raised { Topic.paginate :page => 1, :count => nil }
+ end
+
+ def test_paginate_with_per_page
+ entries = Topic.paginate :page => 1, :per_page => 1
+ assert_equal 1, entries.size
+ assert_equal 4, entries.total_pages
+
+ # Developer class has explicit per_page at 10
+ entries = Developer.paginate :page => 1
+ assert_equal 10, entries.size
+ assert_equal 2, entries.total_pages
+
+ entries = Developer.paginate :page => 1, :per_page => 5
+ assert_equal 11, entries.total_entries
+ assert_equal 5, entries.size
+ assert_equal 3, entries.total_pages
+ end
+
+ def test_paginate_with_order
+ entries = Topic.paginate :page => 1, :order => 'created_at desc'
+ expected = [topics(:futurama), topics(:harvey_birdman), topics(:rails), topics(:ar)].reverse
+ assert_equal expected, entries.to_a
+ assert_equal 1, entries.total_pages
+ end
+
+ def test_paginate_with_conditions
+ entries = Topic.paginate :page => 1, :conditions => ["created_at > ?", 30.minutes.ago]
+ expected = [topics(:rails), topics(:ar)]
+ assert_equal expected, entries.to_a
+ assert_equal 1, entries.total_pages
+ end
+
+ def test_paginate_with_include_and_conditions
+ entries = Topic.paginate \
+ :page => 1,
+ :include => :replies,
+ :conditions => "replies.content LIKE 'Bird%' ",
+ :per_page => 10
+
+ expected = Topic.find :all,
+ :include => 'replies',
+ :conditions => "replies.content LIKE 'Bird%' ",
+ :limit => 10
+
+ assert_equal expected, entries.to_a
+ assert_equal 1, entries.total_entries
+ end
+
+ def test_paginate_with_include_and_order
+ entries = nil
+ assert_queries(2) do
+ entries = Topic.paginate \
+ :page => 1,
+ :include => :replies,
+ :order => 'replies.created_at asc, topics.created_at asc',
+ :per_page => 10
+ end
+
+ expected = Topic.find :all,
+ :include => 'replies',
+ :order => 'replies.created_at asc, topics.created_at asc',
+ :limit => 10
+
+ assert_equal expected, entries.to_a
+ assert_equal 4, entries.total_entries
+ end
+
+ def test_paginate_associations_with_include
+ entries, project = nil, projects(:active_record)
+
+ assert_nothing_raised "THIS IS A BUG in Rails 1.2.3 that was fixed in [7326]. " +
+ "Please upgrade to a newer version of Rails." do
+ entries = project.topics.paginate \
+ :page => 1,
+ :include => :replies,
+ :conditions => "replies.content LIKE 'Nice%' ",
+ :per_page => 10
+ end
+
+ expected = Topic.find :all,
+ :include => 'replies',
+ :conditions => "project_id = #{project.id} AND replies.content LIKE 'Nice%' ",
+ :limit => 10
+
+ assert_equal expected, entries.to_a
+ end
+
+ def test_paginate_associations
+ dhh = users :david
+ expected_name_ordered = [projects(:action_controller), projects(:active_record)]
+ expected_id_ordered = [projects(:active_record), projects(:action_controller)]
+
+ assert_queries(2) do
+ # with association-specified order
+ entries = dhh.projects.paginate(:page => 1)
+ assert_equal expected_name_ordered, entries
+ assert_equal 2, entries.total_entries
+ end
+
+ # with explicit order
+ entries = dhh.projects.paginate(:page => 1, :order => 'projects.id')
+ assert_equal expected_id_ordered, entries
+ assert_equal 2, entries.total_entries
+
+ assert_nothing_raised { dhh.projects.find(:all, :order => 'projects.id', :limit => 4) }
+ entries = dhh.projects.paginate(:page => 1, :order => 'projects.id', :per_page => 4)
+ assert_equal expected_id_ordered, entries
+
+ # has_many with implicit order
+ topic = Topic.find(1)
+ expected = [replies(:spam), replies(:witty_retort)]
+ assert_equal expected.map(&:id).sort, topic.replies.paginate(:page => 1).map(&:id).sort
+ assert_equal expected.reverse, topic.replies.paginate(:page => 1, :order => 'replies.id ASC')
+ end
+
+ def test_paginate_association_extension
+ project = Project.find(:first)
+
+ assert_queries(2) do
+ entries = project.replies.paginate_recent :page => 1
+ assert_equal [replies(:brave)], entries
+ end
+ end
+
+ def test_paginate_with_joins
+ entries = nil
+
+ assert_queries(1) do
+ entries = Developer.paginate :page => 1,
+ :joins => 'LEFT JOIN developers_projects ON users.id = developers_projects.developer_id',
+ :conditions => 'project_id = 1'
+ assert_equal 2, entries.size
+ developer_names = entries.map &:name
+ assert developer_names.include?('David')
+ assert developer_names.include?('Jamis')
+ end
+
+ assert_queries(1) do
+ expected = entries.to_a
+ entries = Developer.paginate :page => 1,
+ :joins => 'LEFT JOIN developers_projects ON users.id = developers_projects.developer_id',
+ :conditions => 'project_id = 1', :count => { :select => "users.id" }
+ assert_equal expected, entries.to_a
+ assert_equal 2, entries.total_entries
+ end
+ end
+
+ def test_paginate_with_group
+ entries = nil
+ assert_queries(1) do
+ entries = Developer.paginate :page => 1, :per_page => 10,
+ :group => 'salary', :select => 'salary', :order => 'salary'
+ end
+
+ expected = [ users(:david), users(:jamis), users(:dev_10), users(:poor_jamis) ].map(&:salary).sort
+ assert_equal expected, entries.map(&:salary)
+ end
+
+ def test_paginate_with_dynamic_finder
+ expected = [replies(:witty_retort), replies(:spam)]
+ assert_equal expected, Reply.paginate_by_topic_id(1, :page => 1)
+
+ entries = Developer.paginate :conditions => { :salary => 100000 }, :page => 1, :per_page => 5
+ assert_equal 8, entries.total_entries
+ assert_equal entries, Developer.paginate_by_salary(100000, :page => 1, :per_page => 5)
+
+ # dynamic finder + conditions
+ entries = Developer.paginate_by_salary(100000, :page => 1,
+ :conditions => ['id > ?', 6])
+ assert_equal 4, entries.total_entries
+ assert_equal (7..10).to_a, entries.map(&:id)
+
+ assert_raises NoMethodError do
+ Developer.paginate_by_inexistent_attribute 100000, :page => 1
+ end
+ end
+
+ def test_scoped_paginate
+ entries = Developer.with_poor_ones { Developer.paginate :page => 1 }
+
+ assert_equal 2, entries.size
+ assert_equal 2, entries.total_entries
+ end
+
+ ## named_scope ##
+
+ def test_paginate_in_named_scope
+ entries = Developer.poor.paginate :page => 1, :per_page => 1
+
+ assert_equal 1, entries.size
+ assert_equal 2, entries.total_entries
+ end
+
+ def test_paginate_in_named_scope_on_habtm_association
+ project = projects(:active_record)
+ assert_queries(2) do
+ entries = project.developers.poor.paginate :page => 1, :per_page => 1
+
+ assert_equal 1, entries.size, 'one developer should be found'
+ assert_equal 1, entries.total_entries, 'only one developer should be found'
+ end
+ end
+
+ def test_paginate_in_named_scope_on_hmt_association
+ project = projects(:active_record)
+ expected = [replies(:brave)]
+
+ assert_queries(2) do
+ entries = project.replies.recent.paginate :page => 1, :per_page => 1
+ assert_equal expected, entries
+ assert_equal 1, entries.total_entries, 'only one reply should be found'
+ end
+ end
+
+ def test_paginate_in_named_scope_on_has_many_association
+ project = projects(:active_record)
+ expected = [topics(:ar)]
+
+ assert_queries(2) do
+ entries = project.topics.mentions_activerecord.paginate :page => 1, :per_page => 1
+ assert_equal expected, entries
+ assert_equal 1, entries.total_entries, 'only one topic should be found'
+ end
+ end
+
+ def test_named_scope_with_include
+ project = projects(:active_record)
+ entries = project.topics.with_replies_starting_with('AR ').paginate(:page => 1, :per_page => 1)
+ assert_equal 1, entries.size
+ end
+
+ ## misc ##
+
+ def test_count_and_total_entries_options_are_mutually_exclusive
+ e = assert_raise ArgumentError do
+ Developer.paginate :page => 1, :count => {}, :total_entries => 1
+ end
+ assert_match /exclusive/, e.to_s
+ end
+
+ def test_readonly
+ assert_nothing_raised { Developer.paginate :readonly => true, :page => 1 }
+ end
+
+ # this functionality is temporarily removed
+ def xtest_pagination_defines_method
+ pager = "paginate_by_created_at"
+ assert !User.methods.include_method?(pager), "User methods should not include `#{pager}` method"
+ # paginate!
+ assert 0, User.send(pager, nil, :page => 1).total_entries
+ # the paging finder should now be defined
+ assert User.methods.include_method?(pager), "`#{pager}` method should be defined on User"
+ end
+
+ # Is this Rails 2.0? Find out by testing find_all which was removed in [6998]
+ unless ActiveRecord::Base.respond_to? :find_all
+ def test_paginate_array_of_ids
+ # AR finders also accept arrays of IDs
+ # (this was broken in Rails before [6912])
+ assert_queries(1) do
+ entries = Developer.paginate((1..8).to_a, :per_page => 3, :page => 2, :order => 'id')
+ assert_equal (4..6).to_a, entries.map(&:id)
+ assert_equal 8, entries.total_entries
+ end
+ end
+ end
+
+ uses_mocha 'internals' do
+ def test_implicit_all_with_dynamic_finders
+ Topic.expects(:find_all_by_foo).returns([])
+ Topic.expects(:count).returns(0)
+ Topic.paginate_by_foo :page => 2
+ end
+
+ def test_guessing_the_total_count
+ Topic.expects(:find).returns(Array.new(2))
+ Topic.expects(:count).never
+
+ entries = Topic.paginate :page => 2, :per_page => 4
+ assert_equal 6, entries.total_entries
+ end
+
+ def test_guessing_that_there_are_no_records
+ Topic.expects(:find).returns([])
+ Topic.expects(:count).never
+
+ entries = Topic.paginate :page => 1, :per_page => 4
+ assert_equal 0, entries.total_entries
+ end
+
+ def test_extra_parameters_stay_untouched
+ Topic.expects(:find).with(:all, {:foo => 'bar', :limit => 4, :offset => 0 }).returns(Array.new(5))
+ Topic.expects(:count).with({:foo => 'bar'}).returns(1)
+
+ Topic.paginate :foo => 'bar', :page => 1, :per_page => 4
+ end
+
+ def test_count_skips_select
+ Developer.stubs(:find).returns([])
+ Developer.expects(:count).with({}).returns(0)
+ Developer.paginate :select => 'salary', :page => 2
+ end
+
+ def test_count_select_when_distinct
+ Developer.stubs(:find).returns([])
+ Developer.expects(:count).with(:select => 'DISTINCT salary').returns(0)
+ Developer.paginate :select => 'DISTINCT salary', :page => 2
+ end
+
+ def test_count_with_scoped_select_when_distinct
+ Developer.stubs(:find).returns([])
+ Developer.expects(:count).with(:select => 'DISTINCT users.id').returns(0)
+ Developer.distinct.paginate :page => 2
+ end
+
+ def test_should_use_scoped_finders_if_present
+ # scope-out compatibility
+ Topic.expects(:find_best).returns(Array.new(5))
+ Topic.expects(:with_best).returns(1)
+
+ Topic.paginate_best :page => 1, :per_page => 4
+ end
+
+ def test_paginate_by_sql
+ sql = "SELECT * FROM users WHERE type = 'Developer' ORDER BY id"
+ entries = Developer.paginate_by_sql(sql, :page => 2, :per_page => 3)
+ assert_equal 11, entries.total_entries
+ assert_equal [users(:dev_4), users(:dev_5), users(:dev_6)], entries
+ end
+
+ def test_paginate_by_sql_respects_total_entries_setting
+ sql = "SELECT * FROM users"
+ entries = Developer.paginate_by_sql(sql, :page => 1, :total_entries => 999)
+ assert_equal 999, entries.total_entries
+ end
+
+ def test_paginate_by_sql_strips_order_by_when_counting
+ Developer.expects(:find_by_sql).returns([])
+ Developer.expects(:count_by_sql).with("SELECT COUNT(*) FROM (sql\n ) AS count_table").returns(0)
+
+ Developer.paginate_by_sql "sql\n ORDER\nby foo, bar, `baz` ASC", :page => 2
+ end
+
+ # TODO: counts are still wrong
+ def test_ability_to_use_with_custom_finders
+ # acts_as_taggable defines find_tagged_with(tag, options)
+ Topic.expects(:find_tagged_with).with('will_paginate', :offset => 5, :limit => 5).returns([])
+ Topic.expects(:count).with({}).returns(0)
+
+ Topic.paginate_tagged_with 'will_paginate', :page => 2, :per_page => 5
+ end
+
+ def test_array_argument_doesnt_eliminate_count
+ ids = (1..8).to_a
+ Developer.expects(:find_all_by_id).returns([])
+ Developer.expects(:count).returns(0)
+
+ Developer.paginate_by_id(ids, :per_page => 3, :page => 2, :order => 'id')
+ end
+
+ def test_paginating_finder_doesnt_mangle_options
+ Developer.expects(:find).returns([])
+ options = { :page => 1, :per_page => 2, :foo => 'bar' }
+ options_before = options.dup
+
+ Developer.paginate(options)
+ assert_equal options_before, options
+ end
+
+ def test_paginate_by_sql_doesnt_change_original_query
+ query = 'SQL QUERY'
+ original_query = query.dup
+ Developer.expects(:find_by_sql).returns([])
+
+ Developer.paginate_by_sql query, :page => 1
+ assert_equal original_query, query
+ end
+
+ def test_paginated_each
+ collection = stub('collection', :size => 5, :empty? => false, :per_page => 5)
+ collection.expects(:each).times(2).returns(collection)
+ last_collection = stub('collection', :size => 4, :empty? => false, :per_page => 5)
+ last_collection.expects(:each).returns(last_collection)
+
+ params = { :order => 'id', :total_entries => 0 }
+
+ Developer.expects(:paginate).with(params.merge(:page => 2)).returns(collection)
+ Developer.expects(:paginate).with(params.merge(:page => 3)).returns(collection)
+ Developer.expects(:paginate).with(params.merge(:page => 4)).returns(last_collection)
+
+ assert_equal 14, Developer.paginated_each(:page => '2') { }
+ end
+
+ def test_paginated_each_with_named_scope
+ assert_equal 2, Developer.poor.paginated_each(:per_page => 1) {
+ assert_equal 11, Developer.count
+ }
+ end
+
+ # detect ActiveRecord 2.1
+ if ActiveRecord::Base.private_methods.include_method?(:references_eager_loaded_tables?)
+ def test_removes_irrelevant_includes_in_count
+ Developer.expects(:find).returns([1])
+ Developer.expects(:count).with({}).returns(0)
+
+ Developer.paginate :page => 1, :per_page => 1, :include => :projects
+ end
+
+ def test_doesnt_remove_referenced_includes_in_count
+ Developer.expects(:find).returns([1])
+ Developer.expects(:count).with({ :include => :projects, :conditions => 'projects.id > 2' }).returns(0)
+
+ Developer.paginate :page => 1, :per_page => 1,
+ :include => :projects, :conditions => 'projects.id > 2'
+ end
+ end
+
+ def test_paginate_from
+ result = Developer.paginate(:from => 'users', :page => 1, :per_page => 1)
+ assert_equal 1, result.size
+ end
+
+ def test_hmt_with_include
+ # ticket #220
+ reply = projects(:active_record).replies.find(:first, :order => 'replies.id')
+ assert_equal replies(:decisive), reply
+
+ # ticket #223
+ Project.find(1, :include => :replies)
+
+ # I cannot reproduce any of the failures from those reports :(
+ end
+ end
+end
diff --git a/src/server/vendor/plugins/will_paginate/test/fixtures/admin.rb b/src/server/vendor/plugins/will_paginate/test/fixtures/admin.rb
new file mode 100644
index 0000000..1d5e7f3
--- /dev/null
+++ b/src/server/vendor/plugins/will_paginate/test/fixtures/admin.rb
@@ -0,0 +1,3 @@
+class Admin < User
+ has_many :companies, :finder_sql => 'SELECT * FROM companies'
+end
diff --git a/src/server/vendor/plugins/will_paginate/test/fixtures/developer.rb b/src/server/vendor/plugins/will_paginate/test/fixtures/developer.rb
new file mode 100644
index 0000000..0224f4b
--- /dev/null
+++ b/src/server/vendor/plugins/will_paginate/test/fixtures/developer.rb
@@ -0,0 +1,14 @@
+class Developer < User
+ has_and_belongs_to_many :projects, :include => :topics, :order => 'projects.name'
+
+ def self.with_poor_ones(&block)
+ with_scope :find => { :conditions => ['salary <= ?', 80000], :order => 'salary' } do
+ yield
+ end
+ end
+
+ named_scope :distinct, :select => 'DISTINCT `users`.*'
+ named_scope :poor, :conditions => ['salary <= ?', 80000], :order => 'salary'
+
+ def self.per_page() 10 end
+end
diff --git a/src/server/vendor/plugins/will_paginate/test/fixtures/developers_projects.yml b/src/server/vendor/plugins/will_paginate/test/fixtures/developers_projects.yml
new file mode 100644
index 0000000..cee359c
--- /dev/null
+++ b/src/server/vendor/plugins/will_paginate/test/fixtures/developers_projects.yml
@@ -0,0 +1,13 @@
+david_action_controller:
+ developer_id: 1
+ project_id: 2
+ joined_on: 2004-10-10
+
+david_active_record:
+ developer_id: 1
+ project_id: 1
+ joined_on: 2004-10-10
+
+jamis_active_record:
+ developer_id: 2
+ project_id: 1
\ No newline at end of file
diff --git a/src/server/vendor/plugins/will_paginate/test/fixtures/project.rb b/src/server/vendor/plugins/will_paginate/test/fixtures/project.rb
new file mode 100644
index 0000000..0f85ef5
--- /dev/null
+++ b/src/server/vendor/plugins/will_paginate/test/fixtures/project.rb
@@ -0,0 +1,15 @@
+class Project < ActiveRecord::Base
+ has_and_belongs_to_many :developers, :uniq => true
+
+ has_many :topics
+ # :finder_sql => 'SELECT * FROM topics WHERE (topics.project_id = #{id})',
+ # :counter_sql => 'SELECT COUNT(*) FROM topics WHERE (topics.project_id = #{id})'
+
+ has_many :replies, :through => :topics do
+ def find_recent(params = {})
+ with_scope :find => { :conditions => ['replies.created_at > ?', 15.minutes.ago] } do
+ find :all, params
+ end
+ end
+ end
+end
diff --git a/src/server/vendor/plugins/will_paginate/test/fixtures/projects.yml b/src/server/vendor/plugins/will_paginate/test/fixtures/projects.yml
new file mode 100644
index 0000000..74f3c32
--- /dev/null
+++ b/src/server/vendor/plugins/will_paginate/test/fixtures/projects.yml
@@ -0,0 +1,6 @@
+active_record:
+ id: 1
+ name: Active Record
+action_controller:
+ id: 2
+ name: Active Controller
diff --git a/src/server/vendor/plugins/will_paginate/test/fixtures/replies.yml b/src/server/vendor/plugins/will_paginate/test/fixtures/replies.yml
new file mode 100644
index 0000000..9a83c00
--- /dev/null
+++ b/src/server/vendor/plugins/will_paginate/test/fixtures/replies.yml
@@ -0,0 +1,29 @@
+witty_retort:
+ id: 1
+ topic_id: 1
+ content: Birdman is better!
+ created_at: <%= 6.hours.ago.to_s(:db) %>
+
+another:
+ id: 2
+ topic_id: 2
+ content: Nuh uh!
+ created_at: <%= 1.hour.ago.to_s(:db) %>
+
+spam:
+ id: 3
+ topic_id: 1
+ content: Nice site!
+ created_at: <%= 1.hour.ago.to_s(:db) %>
+
+decisive:
+ id: 4
+ topic_id: 4
+ content: "I'm getting to the bottom of this"
+ created_at: <%= 30.minutes.ago.to_s(:db) %>
+
+brave:
+ id: 5
+ topic_id: 4
+ content: "AR doesn't scare me a bit"
+ created_at: <%= 10.minutes.ago.to_s(:db) %>
diff --git a/src/server/vendor/plugins/will_paginate/test/fixtures/reply.rb b/src/server/vendor/plugins/will_paginate/test/fixtures/reply.rb
new file mode 100644
index 0000000..ecaf3c1
--- /dev/null
+++ b/src/server/vendor/plugins/will_paginate/test/fixtures/reply.rb
@@ -0,0 +1,7 @@
+class Reply < ActiveRecord::Base
+ belongs_to :topic, :include => [:replies]
+
+ named_scope :recent, :conditions => ['replies.created_at > ?', 15.minutes.ago]
+
+ validates_presence_of :content
+end
diff --git a/src/server/vendor/plugins/will_paginate/test/fixtures/schema.rb b/src/server/vendor/plugins/will_paginate/test/fixtures/schema.rb
new file mode 100644
index 0000000..8831aad
--- /dev/null
+++ b/src/server/vendor/plugins/will_paginate/test/fixtures/schema.rb
@@ -0,0 +1,38 @@
+ActiveRecord::Schema.define do
+
+ create_table "users", :force => true do |t|
+ t.column "name", :text
+ t.column "salary", :integer, :default => 70000
+ t.column "created_at", :datetime
+ t.column "updated_at", :datetime
+ t.column "type", :text
+ end
+
+ create_table "projects", :force => true do |t|
+ t.column "name", :text
+ end
+
+ create_table "developers_projects", :id => false, :force => true do |t|
+ t.column "developer_id", :integer, :null => false
+ t.column "project_id", :integer, :null => false
+ t.column "joined_on", :date
+ t.column "access_level", :integer, :default => 1
+ end
+
+ create_table "topics", :force => true do |t|
+ t.column "project_id", :integer
+ t.column "title", :string
+ t.column "subtitle", :string
+ t.column "content", :text
+ t.column "created_at", :datetime
+ t.column "updated_at", :datetime
+ end
+
+ create_table "replies", :force => true do |t|
+ t.column "content", :text
+ t.column "created_at", :datetime
+ t.column "updated_at", :datetime
+ t.column "topic_id", :integer
+ end
+
+end
diff --git a/src/server/vendor/plugins/will_paginate/test/fixtures/topic.rb b/src/server/vendor/plugins/will_paginate/test/fixtures/topic.rb
new file mode 100644
index 0000000..2c2ce72
--- /dev/null
+++ b/src/server/vendor/plugins/will_paginate/test/fixtures/topic.rb
@@ -0,0 +1,10 @@
+class Topic < ActiveRecord::Base
+ has_many :replies, :dependent => :destroy, :order => 'replies.created_at DESC'
+ belongs_to :project
+
+ named_scope :mentions_activerecord, :conditions => ['topics.title LIKE ?', '%ActiveRecord%']
+
+ named_scope :with_replies_starting_with, lambda { |text|
+ { :conditions => "replies.content LIKE '#{text}%' ", :include => :replies }
+ }
+end
diff --git a/src/server/vendor/plugins/will_paginate/test/fixtures/topics.yml b/src/server/vendor/plugins/will_paginate/test/fixtures/topics.yml
new file mode 100644
index 0000000..0a26904
--- /dev/null
+++ b/src/server/vendor/plugins/will_paginate/test/fixtures/topics.yml
@@ -0,0 +1,30 @@
+futurama:
+ id: 1
+ title: Isnt futurama awesome?
+ subtitle: It really is, isnt it.
+ content: I like futurama
+ created_at: <%= 1.day.ago.to_s(:db) %>
+ updated_at:
+
+harvey_birdman:
+ id: 2
+ title: Harvey Birdman is the king of all men
+ subtitle: yup
+ content: He really is
+ created_at: <%= 2.hours.ago.to_s(:db) %>
+ updated_at:
+
+rails:
+ id: 3
+ project_id: 1
+ title: Rails is nice
+ subtitle: It makes me happy
+ content: except when I have to hack internals to fix pagination. even then really.
+ created_at: <%= 20.minutes.ago.to_s(:db) %>
+
+ar:
+ id: 4
+ project_id: 1
+ title: ActiveRecord sometimes freaks me out
+ content: "I mean, what's the deal with eager loading?"
+ created_at: <%= 15.minutes.ago.to_s(:db) %>
diff --git a/src/server/vendor/plugins/will_paginate/test/fixtures/user.rb b/src/server/vendor/plugins/will_paginate/test/fixtures/user.rb
new file mode 100644
index 0000000..4a57cf0
--- /dev/null
+++ b/src/server/vendor/plugins/will_paginate/test/fixtures/user.rb
@@ -0,0 +1,2 @@
+class User < ActiveRecord::Base
+end
diff --git a/src/server/vendor/plugins/will_paginate/test/fixtures/users.yml b/src/server/vendor/plugins/will_paginate/test/fixtures/users.yml
new file mode 100644
index 0000000..ed2c03a
--- /dev/null
+++ b/src/server/vendor/plugins/will_paginate/test/fixtures/users.yml
@@ -0,0 +1,35 @@
+david:
+ id: 1
+ name: David
+ salary: 80000
+ type: Developer
+
+jamis:
+ id: 2
+ name: Jamis
+ salary: 150000
+ type: Developer
+
+<% for digit in 3..10 %>
+dev_<%= digit %>:
+ id: <%= digit %>
+ name: fixture_<%= digit %>
+ salary: 100000
+ type: Developer
+<% end %>
+
+poor_jamis:
+ id: 11
+ name: Jamis
+ salary: 9000
+ type: Developer
+
+admin:
+ id: 12
+ name: admin
+ type: Admin
+
+goofy:
+ id: 13
+ name: Goofy
+ type: Admin
diff --git a/src/server/vendor/plugins/will_paginate/test/helper.rb b/src/server/vendor/plugins/will_paginate/test/helper.rb
new file mode 100644
index 0000000..019b1fd
--- /dev/null
+++ b/src/server/vendor/plugins/will_paginate/test/helper.rb
@@ -0,0 +1,40 @@
+require 'test/unit'
+require 'rubygems'
+
+# gem install redgreen for colored test output
+begin require 'redgreen'; rescue LoadError; end
+
+require 'boot' unless defined?(ActiveRecord)
+
+class Test::Unit::TestCase
+ protected
+ def assert_respond_to_all object, methods
+ methods.each do |method|
+ [method.to_s, method.to_sym].each { |m| assert_respond_to object, m }
+ end
+ end
+
+ def collect_deprecations
+ old_behavior = WillPaginate::Deprecation.behavior
+ deprecations = []
+ WillPaginate::Deprecation.behavior = Proc.new do |message, callstack|
+ deprecations << message
+ end
+ result = yield
+ [result, deprecations]
+ ensure
+ WillPaginate::Deprecation.behavior = old_behavior
+ end
+end
+
+# Wrap tests that use Mocha and skip if unavailable.
+def uses_mocha(test_name)
+ unless Object.const_defined?(:Mocha)
+ gem 'mocha', '>= 0.9.5'
+ require 'mocha'
+ end
+rescue LoadError => load_error
+ $stderr.puts "Skipping #{test_name} tests. `gem install mocha` and try again."
+else
+ yield
+end
diff --git a/src/server/vendor/plugins/will_paginate/test/lib/activerecord_test_case.rb b/src/server/vendor/plugins/will_paginate/test/lib/activerecord_test_case.rb
new file mode 100644
index 0000000..72a6b16
--- /dev/null
+++ b/src/server/vendor/plugins/will_paginate/test/lib/activerecord_test_case.rb
@@ -0,0 +1,43 @@
+require 'lib/activerecord_test_connector'
+
+class ActiveRecordTestCase < Test::Unit::TestCase
+ if defined?(ActiveSupport::Testing::SetupAndTeardown)
+ include ActiveSupport::Testing::SetupAndTeardown
+ end
+
+ if defined?(ActiveRecord::TestFixtures)
+ include ActiveRecord::TestFixtures
+ end
+ # Set our fixture path
+ if ActiveRecordTestConnector.able_to_connect
+ self.fixture_path = File.join(File.dirname(__FILE__), '..', 'fixtures')
+ self.use_transactional_fixtures = true
+ end
+
+ def self.fixtures(*args)
+ super if ActiveRecordTestConnector.connected
+ end
+
+ def run(*args)
+ super if ActiveRecordTestConnector.connected
+ end
+
+ # Default so Test::Unit::TestCase doesn't complain
+ def test_truth
+ end
+
+ protected
+
+ def assert_queries(num = 1)
+ $query_count = 0
+ yield
+ ensure
+ assert_equal num, $query_count, "#{$query_count} instead of #{num} queries were executed."
+ end
+
+ def assert_no_queries(&block)
+ assert_queries(0, &block)
+ end
+end
+
+ActiveRecordTestConnector.setup
diff --git a/src/server/vendor/plugins/will_paginate/test/lib/activerecord_test_connector.rb b/src/server/vendor/plugins/will_paginate/test/lib/activerecord_test_connector.rb
new file mode 100644
index 0000000..1130cf5
--- /dev/null
+++ b/src/server/vendor/plugins/will_paginate/test/lib/activerecord_test_connector.rb
@@ -0,0 +1,75 @@
+require 'active_record'
+require 'active_record/version'
+require 'active_record/fixtures'
+
+class ActiveRecordTestConnector
+ cattr_accessor :able_to_connect
+ cattr_accessor :connected
+
+ FIXTURES_PATH = File.join(File.dirname(__FILE__), '..', 'fixtures')
+
+ # Set our defaults
+ self.connected = false
+ self.able_to_connect = true
+
+ def self.setup
+ unless self.connected || !self.able_to_connect
+ setup_connection
+ load_schema
+ add_load_path FIXTURES_PATH
+ self.connected = true
+ end
+ rescue Exception => e # errors from ActiveRecord setup
+ $stderr.puts "\nSkipping ActiveRecord tests: #{e}\n\n"
+ self.able_to_connect = false
+ end
+
+ private
+
+ def self.add_load_path(path)
+ dep = defined?(ActiveSupport::Dependencies) ? ActiveSupport::Dependencies : ::Dependencies
+ dep.load_paths.unshift path
+ end
+
+ def self.setup_connection
+ db = ENV['DB'].blank?? 'sqlite3' : ENV['DB']
+
+ configurations = YAML.load_file(File.join(File.dirname(__FILE__), '..', 'database.yml'))
+ raise "no configuration for '#{db}'" unless configurations.key? db
+ configuration = configurations[db]
+
+ ActiveRecord::Base.logger = Logger.new(STDOUT) if $0 == 'irb'
+ puts "using #{configuration['adapter']} adapter" unless ENV['DB'].blank?
+
+ gem 'sqlite3-ruby' if 'sqlite3' == db
+
+ ActiveRecord::Base.establish_connection(configuration)
+ ActiveRecord::Base.configurations = { db => configuration }
+ prepare ActiveRecord::Base.connection
+
+ unless Object.const_defined?(:QUOTED_TYPE)
+ Object.send :const_set, :QUOTED_TYPE, ActiveRecord::Base.connection.quote_column_name('type')
+ end
+ end
+
+ def self.load_schema
+ ActiveRecord::Base.silence do
+ ActiveRecord::Migration.verbose = false
+ load File.join(FIXTURES_PATH, 'schema.rb')
+ end
+ end
+
+ def self.prepare(conn)
+ class << conn
+ IGNORED_SQL = [/^PRAGMA/, /^SELECT currval/, /^SELECT CAST/, /^SELECT @@IDENTITY/, /^SELECT @@ROWCOUNT/, /^SHOW FIELDS /]
+
+ def execute_with_counting(sql, name = nil, &block)
+ $query_count ||= 0
+ $query_count += 1 unless IGNORED_SQL.any? { |r| sql =~ r }
+ execute_without_counting(sql, name, &block)
+ end
+
+ alias_method_chain :execute, :counting
+ end
+ end
+end
diff --git a/src/server/vendor/plugins/will_paginate/test/lib/load_fixtures.rb b/src/server/vendor/plugins/will_paginate/test/lib/load_fixtures.rb
new file mode 100644
index 0000000..10d6f42
--- /dev/null
+++ b/src/server/vendor/plugins/will_paginate/test/lib/load_fixtures.rb
@@ -0,0 +1,11 @@
+require 'boot'
+require 'lib/activerecord_test_connector'
+
+# setup the connection
+ActiveRecordTestConnector.setup
+
+# load all fixtures
+Fixtures.create_fixtures(ActiveRecordTestConnector::FIXTURES_PATH, ActiveRecord::Base.connection.tables)
+
+require 'will_paginate'
+WillPaginate.enable_activerecord
diff --git a/src/server/vendor/plugins/will_paginate/test/lib/view_test_process.rb b/src/server/vendor/plugins/will_paginate/test/lib/view_test_process.rb
new file mode 100644
index 0000000..8da1b71
--- /dev/null
+++ b/src/server/vendor/plugins/will_paginate/test/lib/view_test_process.rb
@@ -0,0 +1,179 @@
+require 'will_paginate/core_ext'
+require 'action_controller'
+require 'action_controller/test_process'
+
+require 'will_paginate'
+WillPaginate.enable_actionpack
+
+ActionController::Routing::Routes.draw do |map|
+ map.connect 'dummy/page/:page', :controller => 'dummy'
+ map.connect 'dummy/dots/page.:page', :controller => 'dummy', :action => 'dots'
+ map.connect 'ibocorp/:page', :controller => 'ibocorp',
+ :requirements => { :page => /\d+/ },
+ :defaults => { :page => 1 }
+
+ map.connect ':controller/:action/:id'
+end
+
+ActionController::Base.perform_caching = false
+
+class WillPaginate::ViewTestCase < Test::Unit::TestCase
+ if defined?(ActionController::TestCase::Assertions)
+ include ActionController::TestCase::Assertions
+ end
+ if defined?(ActiveSupport::Testing::Deprecation)
+ include ActiveSupport::Testing::Deprecation
+ end
+
+ def setup
+ super
+ @controller = DummyController.new
+ @request = @controller.request
+ @html_result = nil
+ @template = '<%= will_paginate collection, options %>'
+
+ @view = ActionView::Base.new
+ @view.assigns['controller'] = @controller
+ @view.assigns['_request'] = @request
+ @view.assigns['_params'] = @request.params
+ end
+
+ def test_no_complain; end
+
+ protected
+
+ def paginate(collection = {}, options = {}, &block)
+ if collection.instance_of? Hash
+ page_options = { :page => 1, :total_entries => 11, :per_page => 4 }.merge(collection)
+ collection = [1].paginate(page_options)
+ end
+
+ locals = { :collection => collection, :options => options }
+
+ unless @view.respond_to? :render_template
+ # Rails 2.2
+ @html_result = ActionView::InlineTemplate.new(@template).render(@view, locals)
+ else
+ if defined? ActionView::InlineTemplate
+ # Rails 2.1
+ args = [ ActionView::InlineTemplate.new(@view, @template, locals) ]
+ else
+ # older Rails versions
+ args = [nil, @template, nil, locals]
+ end
+
+ @html_result = @view.render_template(*args)
+ end
+
+ @html_document = HTML::Document.new(@html_result, true, false)
+
+ if block_given?
+ classname = options[:class] || WillPaginate::ViewHelpers.pagination_options[:class]
+ assert_select("div.#{classname}", 1, 'no main DIV', &block)
+ end
+ end
+
+ def response_from_page_or_rjs
+ @html_document.root
+ end
+
+ def validate_page_numbers expected, links, param_name = :page
+ param_pattern = /\W#{CGI.escape(param_name.to_s)}=([^&]*)/
+
+ assert_equal(expected, links.map { |e|
+ e['href'] =~ param_pattern
+ $1 ? $1.to_i : $1
+ })
+ end
+
+ def assert_links_match pattern, links = nil, numbers = nil
+ links ||= assert_select 'div.pagination a[href]' do |elements|
+ elements
+ end
+
+ pages = [] if numbers
+
+ links.each do |el|
+ assert_match pattern, el['href']
+ if numbers
+ el['href'] =~ pattern
+ pages << ($1.nil?? nil : $1.to_i)
+ end
+ end
+
+ assert_equal numbers, pages, "page numbers don't match" if numbers
+ end
+
+ def assert_no_links_match pattern
+ assert_select 'div.pagination a[href]' do |elements|
+ elements.each do |el|
+ assert_no_match pattern, el['href']
+ end
+ end
+ end
+end
+
+class DummyRequest
+ attr_accessor :symbolized_path_parameters
+
+ def initialize
+ @get = true
+ @params = {}
+ @symbolized_path_parameters = { :controller => 'foo', :action => 'bar' }
+ end
+
+ def get?
+ @get
+ end
+
+ def post
+ @get = false
+ end
+
+ def relative_url_root
+ ''
+ end
+
+ def params(more = nil)
+ @params.update(more) if more
+ @params
+ end
+end
+
+class DummyController
+ attr_reader :request
+ attr_accessor :controller_name
+
+ def initialize
+ @request = DummyRequest.new
+ @url = ActionController::UrlRewriter.new(@request, @request.params)
+ end
+
+ def params
+ @request.params
+ end
+
+ def url_for(params)
+ @url.rewrite(params)
+ end
+end
+
+module HTML
+ Node.class_eval do
+ def inner_text
+ children.map(&:inner_text).join('')
+ end
+ end
+
+ Text.class_eval do
+ def inner_text
+ self.to_s
+ end
+ end
+
+ Tag.class_eval do
+ def inner_text
+ childless?? '' : super
+ end
+ end
+end
diff --git a/src/server/vendor/plugins/will_paginate/test/tasks.rake b/src/server/vendor/plugins/will_paginate/test/tasks.rake
new file mode 100644
index 0000000..a0453e6
--- /dev/null
+++ b/src/server/vendor/plugins/will_paginate/test/tasks.rake
@@ -0,0 +1,59 @@
+require 'rake/testtask'
+
+desc 'Test the will_paginate plugin.'
+Rake::TestTask.new(:test) do |t|
+ t.pattern = 'test/**/*_test.rb'
+ t.verbose = true
+ t.libs << 'test'
+end
+
+# I want to specify environment variables at call time
+class EnvTestTask < Rake::TestTask
+ attr_accessor :env
+
+ def ruby(*args)
+ env.each { |key, value| ENV[key] = value } if env
+ super
+ env.keys.each { |key| ENV.delete key } if env
+ end
+end
+
+for configuration in %w( sqlite3 mysql postgres )
+ EnvTestTask.new("test_#{configuration}") do |t|
+ t.pattern = 'test/finder_test.rb'
+ t.verbose = true
+ t.env = { 'DB' => configuration }
+ t.libs << 'test'
+ end
+end
+
+task :test_databases => %w(test_mysql test_sqlite3 test_postgres)
+
+desc %{Test everything on SQLite3, MySQL and PostgreSQL}
+task :test_full => %w(test test_mysql test_postgres)
+
+desc %{Test everything with Rails 2.1.x, 2.0.x & 1.2.x gems}
+task :test_all do
+ all = Rake::Task['test_full']
+ versions = %w(2.3.2 2.2.2 2.1.0 2.0.4 1.2.6)
+ versions.each do |version|
+ ENV['RAILS_VERSION'] = "~> #{version}"
+ all.invoke
+ reset_invoked unless version == versions.last
+ end
+end
+
+def reset_invoked
+ %w( test_full test test_mysql test_postgres ).each do |name|
+ Rake::Task[name].instance_variable_set '@already_invoked', false
+ end
+end
+
+task :rcov do
+ excludes = %w( lib/will_paginate/named_scope*
+ lib/will_paginate/core_ext.rb
+ lib/will_paginate.rb
+ rails* )
+
+ system %[rcov -Itest:lib test/*.rb -x #{excludes.join(',')}]
+end
diff --git a/src/server/vendor/plugins/will_paginate/test/view_test.rb b/src/server/vendor/plugins/will_paginate/test/view_test.rb
new file mode 100644
index 0000000..3777cce
--- /dev/null
+++ b/src/server/vendor/plugins/will_paginate/test/view_test.rb
@@ -0,0 +1,373 @@
+require 'helper'
+require 'lib/view_test_process'
+
+class AdditionalLinkAttributesRenderer < WillPaginate::LinkRenderer
+ def initialize(link_attributes = nil)
+ super()
+ @additional_link_attributes = link_attributes || { :default => 'true' }
+ end
+
+ def page_link(page, text, attributes = {})
+ @template.link_to text, url_for(page), attributes.merge(@additional_link_attributes)
+ end
+end
+
+class ViewTest < WillPaginate::ViewTestCase
+
+ ## basic pagination ##
+
+ def test_will_paginate
+ paginate do |pagination|
+ assert_select 'a[href]', 3 do |elements|
+ validate_page_numbers [2,3,2], elements
+ assert_select elements.last, ':last-child', "Next »"
+ end
+ assert_select 'span', 2
+ assert_select 'span.disabled:first-child', '« Previous'
+ assert_select 'span.current', '1'
+ assert_equal '« Previous 1 2 3 Next »', pagination.first.inner_text
+ end
+ end
+
+ def test_no_pagination_when_page_count_is_one
+ paginate :per_page => 30
+ assert_equal '', @html_result
+ end
+
+ def test_will_paginate_with_options
+ paginate({ :page => 2 },
+ :class => 'will_paginate', :previous_label => 'Prev', :next_label => 'Next') do
+ assert_select 'a[href]', 4 do |elements|
+ validate_page_numbers [1,1,3,3], elements
+ # test rel attribute values:
+ assert_select elements[1], 'a', '1' do |link|
+ assert_equal 'prev start', link.first['rel']
+ end
+ assert_select elements.first, 'a', "Prev" do |link|
+ assert_equal 'prev start', link.first['rel']
+ end
+ assert_select elements.last, 'a', "Next" do |link|
+ assert_equal 'next', link.first['rel']
+ end
+ end
+ assert_select 'span.current', '2'
+ end
+ end
+
+ def test_will_paginate_using_renderer_class
+ paginate({}, :renderer => AdditionalLinkAttributesRenderer) do
+ assert_select 'a[default=true]', 3
+ end
+ end
+
+ def test_will_paginate_using_renderer_instance
+ renderer = WillPaginate::LinkRenderer.new
+ renderer.gap_marker = '<span class="my-gap">~~</span>'
+
+ paginate({ :per_page => 2 }, :inner_window => 0, :outer_window => 0, :renderer => renderer) do
+ assert_select 'span.my-gap', '~~'
+ end
+
+ renderer = AdditionalLinkAttributesRenderer.new(:title => 'rendered')
+ paginate({}, :renderer => renderer) do
+ assert_select 'a[title=rendered]', 3
+ end
+ end
+
+ def test_prev_next_links_have_classnames
+ paginate do |pagination|
+ assert_select 'span.disabled.prev_page:first-child'
+ assert_select 'a.next_page[href]:last-child'
+ end
+ end
+
+ def test_prev_label_deprecated
+ assert_deprecated ':previous_label' do
+ paginate({ :page => 2 }, :prev_label => 'Deprecated') do
+ assert_select 'a[href]:first-child', 'Deprecated'
+ end
+ end
+ end
+
+ def test_full_output
+ paginate
+ expected = <<-HTML
+ <div class="pagination"><span class="disabled prev_page">« Previous</span>
+ <span class="current">1</span>
+ <a href="/foo/bar?page=2" rel="next">2</a>
+ <a href="/foo/bar?page=3">3</a>
+ <a href="/foo/bar?page=2" class="next_page" rel="next">Next »</a></div>
+ HTML
+ expected.strip!.gsub!(/\s{2,}/, ' ')
+
+ assert_dom_equal expected, @html_result
+ end
+
+ def test_escaping_of_urls
+ paginate({:page => 1, :per_page => 1, :total_entries => 2},
+ :page_links => false, :params => { :tag => '<br>' })
+
+ assert_select 'a[href]', 1 do |links|
+ query = links.first['href'].split('?', 2)[1]
+ assert_equal %w(page=2 tag=%3Cbr%3E), query.split('&').sort
+ end
+ end
+
+ ## advanced options for pagination ##
+
+ def test_will_paginate_without_container
+ paginate({}, :container => false)
+ assert_select 'div.pagination', 0, 'main DIV present when it shouldn\'t'
+ assert_select 'a[href]', 3
+ end
+
+ def test_will_paginate_without_page_links
+ paginate({ :page => 2 }, :page_links => false) do
+ assert_select 'a[href]', 2 do |elements|
+ validate_page_numbers [1,3], elements
+ end
+ end
+ end
+
+ def test_will_paginate_windows
+ paginate({ :page => 6, :per_page => 1 }, :inner_window => 1) do |pagination|
+ assert_select 'a[href]', 8 do |elements|
+ validate_page_numbers [5,1,2,5,7,10,11,7], elements
+ assert_select elements.first, 'a', '« Previous'
+ assert_select elements.last, 'a', 'Next »'
+ end
+ assert_select 'span.current', '6'
+ assert_equal '« Previous 1 2 … 5 6 7 … 10 11 Next »', pagination.first.inner_text
+ end
+ end
+
+ def test_will_paginate_eliminates_small_gaps
+ paginate({ :page => 6, :per_page => 1 }, :inner_window => 2) do
+ assert_select 'a[href]', 12 do |elements|
+ validate_page_numbers [5,1,2,3,4,5,7,8,9,10,11,7], elements
+ end
+ end
+ end
+
+ def test_container_id
+ paginate do |div|
+ assert_nil div.first['id']
+ end
+
+ # magic ID
+ paginate({}, :id => true) do |div|
+ assert_equal 'fixnums_pagination', div.first['id']
+ end
+
+ # explicit ID
+ paginate({}, :id => 'custom_id') do |div|
+ assert_equal 'custom_id', div.first['id']
+ end
+ end
+
+ ## other helpers ##
+
+ def test_paginated_section
+ @template = <<-ERB
+ <% paginated_section collection, options do %>
+ <%= content_tag :div, '', :id => "developers" %>
+ <% end %>
+ ERB
+
+ paginate
+ assert_select 'div.pagination', 2
+ assert_select 'div.pagination + div#developers', 1
+ end
+
+ def test_page_entries_info
+ @template = '<%= page_entries_info collection %>'
+ array = ('a'..'z').to_a
+
+ paginate array.paginate(:page => 2, :per_page => 5)
+ assert_equal %{Displaying strings <b>6 - 10</b> of <b>26</b> in total},
+ @html_result
+
+ paginate array.paginate(:page => 7, :per_page => 4)
+ assert_equal %{Displaying strings <b>25 - 26</b> of <b>26</b> in total},
+ @html_result
+ end
+
+ uses_mocha 'class name' do
+ def test_page_entries_info_with_longer_class_name
+ @template = '<%= page_entries_info collection %>'
+ collection = ('a'..'z').to_a.paginate
+ collection.first.stubs(:class).returns(mock('class', :name => 'ProjectType'))
+
+ paginate collection
+ assert @html_result.index('project types'), "expected <#{@html_result.inspect}> to mention 'project types'"
+ end
+ end
+
+ def test_page_entries_info_with_single_page_collection
+ @template = '<%= page_entries_info collection %>'
+
+ paginate(('a'..'d').to_a.paginate(:page => 1, :per_page => 5))
+ assert_equal %{Displaying <b>all 4</b> strings}, @html_result
+
+ paginate(['a'].paginate(:page => 1, :per_page => 5))
+ assert_equal %{Displaying <b>1</b> string}, @html_result
+
+ paginate([].paginate(:page => 1, :per_page => 5))
+ assert_equal %{No entries found}, @html_result
+ end
+
+ def test_page_entries_info_with_custom_entry_name
+ @template = '<%= page_entries_info collection, :entry_name => "author" %>'
+
+ entries = (1..20).to_a
+
+ paginate(entries.paginate(:page => 1, :per_page => 5))
+ assert_equal %{Displaying authors <b>1 - 5</b> of <b>20</b> in total}, @html_result
+
+ paginate(entries.paginate(:page => 1, :per_page => 20))
+ assert_equal %{Displaying <b>all 20</b> authors}, @html_result
+
+ paginate(['a'].paginate(:page => 1, :per_page => 5))
+ assert_equal %{Displaying <b>1</b> author}, @html_result
+
+ paginate([].paginate(:page => 1, :per_page => 5))
+ assert_equal %{No authors found}, @html_result
+ end
+
+ ## parameter handling in page links ##
+
+ def test_will_paginate_preserves_parameters_on_get
+ @request.params :foo => { :bar => 'baz' }
+ paginate
+ assert_links_match /foo%5Bbar%5D=baz/
+ end
+
+ def test_will_paginate_doesnt_preserve_parameters_on_post
+ @request.post
+ @request.params :foo => 'bar'
+ paginate
+ assert_no_links_match /foo=bar/
+ end
+
+ def test_adding_additional_parameters
+ paginate({}, :params => { :foo => 'bar' })
+ assert_links_match /foo=bar/
+ end
+
+ def test_adding_anchor_parameter
+ paginate({}, :params => { :anchor => 'anchor' })
+ assert_links_match /#anchor$/
+ end
+
+ def test_removing_arbitrary_parameters
+ @request.params :foo => 'bar'
+ paginate({}, :params => { :foo => nil })
+ assert_no_links_match /foo=bar/
+ end
+
+ def test_adding_additional_route_parameters
+ paginate({}, :params => { :controller => 'baz', :action => 'list' })
+ assert_links_match %r{\Wbaz/list\W}
+ end
+
+ def test_will_paginate_with_custom_page_param
+ paginate({ :page => 2 }, :param_name => :developers_page) do
+ assert_select 'a[href]', 4 do |elements|
+ validate_page_numbers [1,1,3,3], elements, :developers_page
+ end
+ end
+ end
+
+ def test_will_paginate_with_atmark_url
+ @request.symbolized_path_parameters[:action] = "@tag"
+ renderer = WillPaginate::LinkRenderer.new
+
+ paginate({ :page => 1 }, :renderer=>renderer)
+ assert_links_match %r[/foo/@tag\?page=\d]
+ end
+
+ def test_complex_custom_page_param
+ @request.params :developers => { :page => 2 }
+
+ paginate({ :page => 2 }, :param_name => 'developers[page]') do
+ assert_select 'a[href]', 4 do |links|
+ assert_links_match /\?developers%5Bpage%5D=\d+$/, links
+ validate_page_numbers [1,1,3,3], links, 'developers[page]'
+ end
+ end
+ end
+
+ def test_custom_routing_page_param
+ @request.symbolized_path_parameters.update :controller => 'dummy', :action => nil
+ paginate :per_page => 2 do
+ assert_select 'a[href]', 6 do |links|
+ assert_links_match %r{/page/(\d+)$}, links, [2, 3, 4, 5, 6, 2]
+ end
+ end
+ end
+
+ def test_custom_routing_page_param_with_dot_separator
+ @request.symbolized_path_parameters.update :controller => 'dummy', :action => 'dots'
+ paginate :per_page => 2 do
+ assert_select 'a[href]', 6 do |links|
+ assert_links_match %r{/page\.(\d+)$}, links, [2, 3, 4, 5, 6, 2]
+ end
+ end
+ end
+
+ def test_custom_routing_with_first_page_hidden
+ @request.symbolized_path_parameters.update :controller => 'ibocorp', :action => nil
+ paginate :page => 2, :per_page => 2 do
+ assert_select 'a[href]', 7 do |links|
+ assert_links_match %r{/ibocorp(?:/(\d+))?$}, links, [nil, nil, 3, 4, 5, 6, 3]
+ end
+ end
+ end
+
+ ## internal hardcore stuff ##
+
+ class LegacyCollection < WillPaginate::Collection
+ alias :page_count :total_pages
+ undef :total_pages
+ end
+
+ def test_deprecation_notices_with_page_count
+ collection = LegacyCollection.new(1, 1, 2)
+
+ assert_deprecated collection.class.name do
+ paginate collection
+ end
+ end
+
+ uses_mocha 'view internals' do
+ def test_collection_name_can_be_guessed
+ collection = mock
+ collection.expects(:total_pages).returns(1)
+
+ @template = '<%= will_paginate options %>'
+ @controller.controller_name = 'developers'
+ @view.assigns['developers'] = collection
+
+ paginate(nil)
+ end
+ end
+
+ def test_inferred_collection_name_raises_error_when_nil
+ @template = '<%= will_paginate options %>'
+ @controller.controller_name = 'developers'
+
+ e = assert_raise ArgumentError do
+ paginate(nil)
+ end
+ assert e.message.include?('@developers')
+ end
+
+ if ActionController::Base.respond_to? :rescue_responses
+ # only on Rails 2
+ def test_rescue_response_hook_presence
+ assert_equal :not_found,
+ ActionController::Base.rescue_responses['WillPaginate::InvalidPage']
+ end
+ end
+
+end
diff --git a/src/server/vendor/plugins/will_paginate/will_paginate.gemspec b/src/server/vendor/plugins/will_paginate/will_paginate.gemspec
new file mode 100644
index 0000000..2220491
--- /dev/null
+++ b/src/server/vendor/plugins/will_paginate/will_paginate.gemspec
@@ -0,0 +1,20 @@
+Gem::Specification.new do |s|
+ s.name = 'will_paginate'
+ s.version = '2.3.11'
+ s.date = '2009-06-02'
+
+ s.summary = "Most awesome pagination solution for Rails"
+ s.description = "The will_paginate library provides a simple, yet powerful and extensible API for ActiveRecord pagination and rendering of pagination links in ActionView templates."
+
+ s.authors = ['Mislav MarohniÄ', 'PJ Hyett']
+ s.email = 'mislav.marohnic@gmail.com'
+ s.homepage = 'http://github.com/mislav/will_paginate/wikis'
+
+ s.has_rdoc = true
+ s.rdoc_options = ['--main', 'README.rdoc']
+ s.rdoc_options << '--inline-source' << '--charset=UTF-8'
+ s.extra_rdoc_files = ['README.rdoc', 'LICENSE', 'CHANGELOG.rdoc']
+
+ s.files = %w(CHANGELOG.rdoc LICENSE README.rdoc Rakefile examples/apple-circle.gif examples/index.haml examples/index.html examples/pagination.css examples/pagination.sass init.rb lib/will_paginate.rb lib/will_paginate/array.rb lib/will_paginate/collection.rb lib/will_paginate/core_ext.rb lib/will_paginate/finder.rb lib/will_paginate/named_scope.rb lib/will_paginate/named_scope_patch.rb lib/will_paginate/version.rb lib/will_paginate/view_helpers.rb test/boot.rb test/collection_test.rb test/console test/database.yml test/finder_test.rb test/fixtures/admin.rb test/fixtures/developer.rb test/fixtures/developers_projects.yml test/fixtures/project.rb test/fixtures/projects.yml test/fixtures/replies.yml test/fixtures/reply.rb test/fixtures/schema.rb test/fixtures/topic.rb test/fixtures/topics.yml test/fixtures/user.rb test/fixtures/users.yml test/helper.rb test/lib/activerecord_test_case.rb test/lib/activerecord_test_connector.rb test/lib/load_fixtures.rb test/lib/view_test_process.rb test/tasks.rake test/view_test.rb)
+ s.test_files = %w(test/boot.rb test/collection_test.rb test/console test/database.yml test/finder_test.rb test/fixtures/admin.rb test/fixtures/developer.rb test/fixtures/developers_projects.yml test/fixtures/project.rb test/fixtures/projects.yml test/fixtures/replies.yml test/fixtures/reply.rb test/fixtures/schema.rb test/fixtures/topic.rb test/fixtures/topics.yml test/fixtures/user.rb test/fixtures/users.yml test/helper.rb test/lib/activerecord_test_case.rb test/lib/activerecord_test_connector.rb test/lib/load_fixtures.rb test/lib/view_test_process.rb test/tasks.rake test/view_test.rb)
+end
|
parabuzzle/cistern
|
501a7554e9ec3bc08b4ff2941f517c638e8bf609
|
Front end work. Added methods for constructing logevents based on static data for display
|
diff --git a/src/server/app/controllers/application_controller.rb b/src/server/app/controllers/application_controller.rb
index 6635a3f..6605d54 100644
--- a/src/server/app/controllers/application_controller.rb
+++ b/src/server/app/controllers/application_controller.rb
@@ -1,10 +1,11 @@
# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
class ApplicationController < ActionController::Base
helper :all # include all helpers, all the time
protect_from_forgery # See ActionController::RequestForgeryProtection for details
-
+ include ApplicationHelper
+
# Scrub sensitive parameters from your log
- # filter_parameter_logging :password
+ filter_parameter_logging :password
end
diff --git a/src/server/app/controllers/events_controller.rb b/src/server/app/controllers/events_controller.rb
index 5175242..180482b 100644
--- a/src/server/app/controllers/events_controller.rb
+++ b/src/server/app/controllers/events_controller.rb
@@ -1,2 +1,17 @@
class EventsController < ApplicationController
+ include EventsHelper
+
+ def index
+ @title = "Events"
+ @logtypes = Logtype.all
+ @agents = Agent.all
+ end
+
+ def show
+ @title = "All Events"
+ #@events = Array.new
+ events = Event.all
+ @events = rebuildevents(events)
+ end
+
end
diff --git a/src/server/app/helpers/application_helper.rb b/src/server/app/helpers/application_helper.rb
index 22a7940..294c262 100644
--- a/src/server/app/helpers/application_helper.rb
+++ b/src/server/app/helpers/application_helper.rb
@@ -1,3 +1,40 @@
# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
+
+ def rebuildevents(events)
+ @events = Array.new
+ events.each do |e|
+ static = e.staticentry
+ entries = e.payload.split(',')
+ hash = Hash.new
+ entries.each do |m|
+ map = m.split('=')
+ hash.store('<<<' + map[0] + '>>>',map[1])
+ end
+ e.payload = static.data
+ hash.each do |key, val|
+ e.payload = e.payload.gsub(key,val)
+ end
+ @events << e
+ end
+ return @events
+ end
+
+ def displaylevel(level)
+ if level = 0
+ level = "FATAL"
+ elsif level = 1
+ level = "ERROR"
+ elsif level = 2
+ level = "WARN"
+ elsif level = 3
+ level = "INFO"
+ elsif level = 4
+ level = "DEBUG"
+ else
+ level = "UNKNOWN"
+ end
+ return level
+ end
+
end
diff --git a/src/server/app/models/event.rb b/src/server/app/models/event.rb
index d6e5ba8..d50fa7e 100644
--- a/src/server/app/models/event.rb
+++ b/src/server/app/models/event.rb
@@ -1,8 +1,10 @@
class Event < ActiveRecord::Base
belongs_to :staticentry
belongs_to :agent
+ default_scope :order => 'time DESC'
+
#Validations
validates_presence_of :agent_id, :loglevel, :time
end
diff --git a/src/server/app/views/events/index.rhtml b/src/server/app/views/events/index.rhtml
new file mode 100644
index 0000000..3f9b527
--- /dev/null
+++ b/src/server/app/views/events/index.rhtml
@@ -0,0 +1,17 @@
+<h1>Events Statistics</h1>
+<div class="adendem">Select the log events you would like to see:</div>
+<h2>Logtypes</h2>
+<ul>
+ <% for type in @logtypes do%>
+ <li><%= link_to(type.name, :action => 'show', :logtype => type.id)%> :: <%=type.events.count %> total events</ul>
+ <%end%>
+</ul>
+
+<h2>Agents</h2>
+<ul>
+ <% for agent in @agents do%>
+ <li><%=link_to(agent.name, :action => 'show', :agent => agent.id)%> [<%=agent.hostname%>] :: <%= agent.events.count%> total events</li>
+ <%end%>
+</ul>
+
+<h3><%= link_to('Show all events', :action => 'show')%></h3>
\ No newline at end of file
diff --git a/src/server/app/views/events/show.rhtml b/src/server/app/views/events/show.rhtml
new file mode 100644
index 0000000..8fe0957
--- /dev/null
+++ b/src/server/app/views/events/show.rhtml
@@ -0,0 +1,6 @@
+<h1>All Events</h1>
+<ul>
+<% for event in @events do %>
+ <li><%= Time.at(event.time)%> : <%= displaylevel(event.loglevel)%> <%=event.payload%></li>
+<%end%>
+</ul>
diff --git a/src/server/app/views/layouts/application.rhtml b/src/server/app/views/layouts/application.rhtml
new file mode 100644
index 0000000..f7458de
--- /dev/null
+++ b/src/server/app/views/layouts/application.rhtml
@@ -0,0 +1,70 @@
+<%starttime = Time.now.to_f %>
+<!DOCTYPE HTML PUBLIC "!//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<html>
+<head>
+<title>Cistern :: <%= @title %></title>
+
+<%= stylesheet_link_tag "main" %>
+<%= javascript_include_tag "jquery.min"%>
+<%= javascript_include_tag "application"%>
+</head>
+
+<body>
+ <div id="header">
+ <div id="logo">Cistern</div>
+ <div id="search ">
+ Search all Events
+ <% form_for :search do |form| %>
+ <div><%= form.text_field :data, :size => 20, :class => "searchbox" %></div>
+ <div class="adendem">advanced</div>
+ <%end%>
+ </div>
+ </div> <!-- header -->
+ <div id="container">
+ <div id="main">
+
+
+ <%= @content_for_layout %>
+
+ </div> <!-- main -->
+ <div id="footer">
+ Footer
+ </div> <!-- footer -->
+
+ <% if ENV["RAILS_ENV"] == "development" #call this block if in dev mode %>
+ <!-- Dev stuff -->
+ <div id="debug">
+ <a href='#' onclick="$('#params_debug_info').toggle();return false">params</a> |
+ <a href='#' onclick="$('#session_debug_info').toggle();return false">session</a> |
+ <a href='#' onclick="$('#env_debug_info').toggle();return false">env</a> |
+ <a href='#' onclick="$('#request_debug_info').toggle();return false">request</a>
+ <fieldset id="params_debug_info" class="debug_info" style="display:none">
+ <legend>params</legend>
+ <%= debug(params) %>
+ </fieldset>
+ <fieldset id="session_debug_info" class="debug_info" style="display:none">
+ <legend>session</legend>
+ <%= debug(session) %>
+ </fieldset>
+ <fieldset id="env_debug_info" class="debug_info" style="display:none">
+ <legend>env</legend>
+ <%= debug(request.env) %>
+ </fieldset>
+ <fieldset id="request_debug_info" class="debug_info" style="display:none">
+ <legend>request</legend>
+ <%= debug(request) %>
+ </fieldset>
+ </div>
+ <!-- end Dev mode only stuff -->
+ <% end %>
+ </div> <!-- container -->
+
+</body>
+</html>
+<% rtime = Time.now.to_f - starttime%>
+
+<% if ENV["RAILS_ENV"] == "development"%>
+<%= [rtime*1000].to_s.to_i %> ms
+<%else%>
+<!-- <%= rtime*1000 %> -->
+<%end%>
\ No newline at end of file
diff --git a/src/server/public/javascripts/jquery.min.js b/src/server/public/javascripts/jquery.min.js
new file mode 100644
index 0000000..b1ae21d
--- /dev/null
+++ b/src/server/public/javascripts/jquery.min.js
@@ -0,0 +1,19 @@
+/*
+ * jQuery JavaScript Library v1.3.2
+ * http://jquery.com/
+ *
+ * Copyright (c) 2009 John Resig
+ * Dual licensed under the MIT and GPL licenses.
+ * http://docs.jquery.com/License
+ *
+ * Date: 2009-02-19 17:34:21 -0500 (Thu, 19 Feb 2009)
+ * Revision: 6246
+ */
+(function(){var l=this,g,y=l.jQuery,p=l.$,o=l.jQuery=l.$=function(E,F){return new o.fn.init(E,F)},D=/^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,f=/^.[^:#\[\.,]*$/;o.fn=o.prototype={init:function(E,H){E=E||document;if(E.nodeType){this[0]=E;this.length=1;this.context=E;return this}if(typeof E==="string"){var G=D.exec(E);if(G&&(G[1]||!H)){if(G[1]){E=o.clean([G[1]],H)}else{var I=document.getElementById(G[3]);if(I&&I.id!=G[3]){return o().find(E)}var F=o(I||[]);F.context=document;F.selector=E;return F}}else{return o(H).find(E)}}else{if(o.isFunction(E)){return o(document).ready(E)}}if(E.selector&&E.context){this.selector=E.selector;this.context=E.context}return this.setArray(o.isArray(E)?E:o.makeArray(E))},selector:"",jquery:"1.3.2",size:function(){return this.length},get:function(E){return E===g?Array.prototype.slice.call(this):this[E]},pushStack:function(F,H,E){var G=o(F);G.prevObject=this;G.context=this.context;if(H==="find"){G.selector=this.selector+(this.selector?" ":"")+E}else{if(H){G.selector=this.selector+"."+H+"("+E+")"}}return G},setArray:function(E){this.length=0;Array.prototype.push.apply(this,E);return this},each:function(F,E){return o.each(this,F,E)},index:function(E){return o.inArray(E&&E.jquery?E[0]:E,this)},attr:function(F,H,G){var E=F;if(typeof F==="string"){if(H===g){return this[0]&&o[G||"attr"](this[0],F)}else{E={};E[F]=H}}return this.each(function(I){for(F in E){o.attr(G?this.style:this,F,o.prop(this,E[F],G,I,F))}})},css:function(E,F){if((E=="width"||E=="height")&&parseFloat(F)<0){F=g}return this.attr(E,F,"curCSS")},text:function(F){if(typeof F!=="object"&&F!=null){return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(F))}var E="";o.each(F||this,function(){o.each(this.childNodes,function(){if(this.nodeType!=8){E+=this.nodeType!=1?this.nodeValue:o.fn.text([this])}})});return E},wrapAll:function(E){if(this[0]){var F=o(E,this[0].ownerDocument).clone();if(this[0].parentNode){F.insertBefore(this[0])}F.map(function(){var G=this;while(G.firstChild){G=G.firstChild}return G}).append(this)}return this},wrapInner:function(E){return this.each(function(){o(this).contents().wrapAll(E)})},wrap:function(E){return this.each(function(){o(this).wrapAll(E)})},append:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.appendChild(E)}})},prepend:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.insertBefore(E,this.firstChild)}})},before:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this)})},after:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this.nextSibling)})},end:function(){return this.prevObject||o([])},push:[].push,sort:[].sort,splice:[].splice,find:function(E){if(this.length===1){var F=this.pushStack([],"find",E);F.length=0;o.find(E,this[0],F);return F}else{return this.pushStack(o.unique(o.map(this,function(G){return o.find(E,G)})),"find",E)}},clone:function(G){var E=this.map(function(){if(!o.support.noCloneEvent&&!o.isXMLDoc(this)){var I=this.outerHTML;if(!I){var J=this.ownerDocument.createElement("div");J.appendChild(this.cloneNode(true));I=J.innerHTML}return o.clean([I.replace(/ jQuery\d+="(?:\d+|null)"/g,"").replace(/^\s*/,"")])[0]}else{return this.cloneNode(true)}});if(G===true){var H=this.find("*").andSelf(),F=0;E.find("*").andSelf().each(function(){if(this.nodeName!==H[F].nodeName){return}var I=o.data(H[F],"events");for(var K in I){for(var J in I[K]){o.event.add(this,K,I[K][J],I[K][J].data)}}F++})}return E},filter:function(E){return this.pushStack(o.isFunction(E)&&o.grep(this,function(G,F){return E.call(G,F)})||o.multiFilter(E,o.grep(this,function(F){return F.nodeType===1})),"filter",E)},closest:function(E){var G=o.expr.match.POS.test(E)?o(E):null,F=0;return this.map(function(){var H=this;while(H&&H.ownerDocument){if(G?G.index(H)>-1:o(H).is(E)){o.data(H,"closest",F);return H}H=H.parentNode;F++}})},not:function(E){if(typeof E==="string"){if(f.test(E)){return this.pushStack(o.multiFilter(E,this,true),"not",E)}else{E=o.multiFilter(E,this)}}var F=E.length&&E[E.length-1]!==g&&!E.nodeType;return this.filter(function(){return F?o.inArray(this,E)<0:this!=E})},add:function(E){return this.pushStack(o.unique(o.merge(this.get(),typeof E==="string"?o(E):o.makeArray(E))))},is:function(E){return !!E&&o.multiFilter(E,this).length>0},hasClass:function(E){return !!E&&this.is("."+E)},val:function(K){if(K===g){var E=this[0];if(E){if(o.nodeName(E,"option")){return(E.attributes.value||{}).specified?E.value:E.text}if(o.nodeName(E,"select")){var I=E.selectedIndex,L=[],M=E.options,H=E.type=="select-one";if(I<0){return null}for(var F=H?I:0,J=H?I+1:M.length;F<J;F++){var G=M[F];if(G.selected){K=o(G).val();if(H){return K}L.push(K)}}return L}return(E.value||"").replace(/\r/g,"")}return g}if(typeof K==="number"){K+=""}return this.each(function(){if(this.nodeType!=1){return}if(o.isArray(K)&&/radio|checkbox/.test(this.type)){this.checked=(o.inArray(this.value,K)>=0||o.inArray(this.name,K)>=0)}else{if(o.nodeName(this,"select")){var N=o.makeArray(K);o("option",this).each(function(){this.selected=(o.inArray(this.value,N)>=0||o.inArray(this.text,N)>=0)});if(!N.length){this.selectedIndex=-1}}else{this.value=K}}})},html:function(E){return E===g?(this[0]?this[0].innerHTML.replace(/ jQuery\d+="(?:\d+|null)"/g,""):null):this.empty().append(E)},replaceWith:function(E){return this.after(E).remove()},eq:function(E){return this.slice(E,+E+1)},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments),"slice",Array.prototype.slice.call(arguments).join(","))},map:function(E){return this.pushStack(o.map(this,function(G,F){return E.call(G,F,G)}))},andSelf:function(){return this.add(this.prevObject)},domManip:function(J,M,L){if(this[0]){var I=(this[0].ownerDocument||this[0]).createDocumentFragment(),F=o.clean(J,(this[0].ownerDocument||this[0]),I),H=I.firstChild;if(H){for(var G=0,E=this.length;G<E;G++){L.call(K(this[G],H),this.length>1||G>0?I.cloneNode(true):I)}}if(F){o.each(F,z)}}return this;function K(N,O){return M&&o.nodeName(N,"table")&&o.nodeName(O,"tr")?(N.getElementsByTagName("tbody")[0]||N.appendChild(N.ownerDocument.createElement("tbody"))):N}}};o.fn.init.prototype=o.fn;function z(E,F){if(F.src){o.ajax({url:F.src,async:false,dataType:"script"})}else{o.globalEval(F.text||F.textContent||F.innerHTML||"")}if(F.parentNode){F.parentNode.removeChild(F)}}function e(){return +new Date}o.extend=o.fn.extend=function(){var J=arguments[0]||{},H=1,I=arguments.length,E=false,G;if(typeof J==="boolean"){E=J;J=arguments[1]||{};H=2}if(typeof J!=="object"&&!o.isFunction(J)){J={}}if(I==H){J=this;--H}for(;H<I;H++){if((G=arguments[H])!=null){for(var F in G){var K=J[F],L=G[F];if(J===L){continue}if(E&&L&&typeof L==="object"&&!L.nodeType){J[F]=o.extend(E,K||(L.length!=null?[]:{}),L)}else{if(L!==g){J[F]=L}}}}}return J};var b=/z-?index|font-?weight|opacity|zoom|line-?height/i,q=document.defaultView||{},s=Object.prototype.toString;o.extend({noConflict:function(E){l.$=p;if(E){l.jQuery=y}return o},isFunction:function(E){return s.call(E)==="[object Function]"},isArray:function(E){return s.call(E)==="[object Array]"},isXMLDoc:function(E){return E.nodeType===9&&E.documentElement.nodeName!=="HTML"||!!E.ownerDocument&&o.isXMLDoc(E.ownerDocument)},globalEval:function(G){if(G&&/\S/.test(G)){var F=document.getElementsByTagName("head")[0]||document.documentElement,E=document.createElement("script");E.type="text/javascript";if(o.support.scriptEval){E.appendChild(document.createTextNode(G))}else{E.text=G}F.insertBefore(E,F.firstChild);F.removeChild(E)}},nodeName:function(F,E){return F.nodeName&&F.nodeName.toUpperCase()==E.toUpperCase()},each:function(G,K,F){var E,H=0,I=G.length;if(F){if(I===g){for(E in G){if(K.apply(G[E],F)===false){break}}}else{for(;H<I;){if(K.apply(G[H++],F)===false){break}}}}else{if(I===g){for(E in G){if(K.call(G[E],E,G[E])===false){break}}}else{for(var J=G[0];H<I&&K.call(J,H,J)!==false;J=G[++H]){}}}return G},prop:function(H,I,G,F,E){if(o.isFunction(I)){I=I.call(H,F)}return typeof I==="number"&&G=="curCSS"&&!b.test(E)?I+"px":I},className:{add:function(E,F){o.each((F||"").split(/\s+/),function(G,H){if(E.nodeType==1&&!o.className.has(E.className,H)){E.className+=(E.className?" ":"")+H}})},remove:function(E,F){if(E.nodeType==1){E.className=F!==g?o.grep(E.className.split(/\s+/),function(G){return !o.className.has(F,G)}).join(" "):""}},has:function(F,E){return F&&o.inArray(E,(F.className||F).toString().split(/\s+/))>-1}},swap:function(H,G,I){var E={};for(var F in G){E[F]=H.style[F];H.style[F]=G[F]}I.call(H);for(var F in G){H.style[F]=E[F]}},css:function(H,F,J,E){if(F=="width"||F=="height"){var L,G={position:"absolute",visibility:"hidden",display:"block"},K=F=="width"?["Left","Right"]:["Top","Bottom"];function I(){L=F=="width"?H.offsetWidth:H.offsetHeight;if(E==="border"){return}o.each(K,function(){if(!E){L-=parseFloat(o.curCSS(H,"padding"+this,true))||0}if(E==="margin"){L+=parseFloat(o.curCSS(H,"margin"+this,true))||0}else{L-=parseFloat(o.curCSS(H,"border"+this+"Width",true))||0}})}if(H.offsetWidth!==0){I()}else{o.swap(H,G,I)}return Math.max(0,Math.round(L))}return o.curCSS(H,F,J)},curCSS:function(I,F,G){var L,E=I.style;if(F=="opacity"&&!o.support.opacity){L=o.attr(E,"opacity");return L==""?"1":L}if(F.match(/float/i)){F=w}if(!G&&E&&E[F]){L=E[F]}else{if(q.getComputedStyle){if(F.match(/float/i)){F="float"}F=F.replace(/([A-Z])/g,"-$1").toLowerCase();var M=q.getComputedStyle(I,null);if(M){L=M.getPropertyValue(F)}if(F=="opacity"&&L==""){L="1"}}else{if(I.currentStyle){var J=F.replace(/\-(\w)/g,function(N,O){return O.toUpperCase()});L=I.currentStyle[F]||I.currentStyle[J];if(!/^\d+(px)?$/i.test(L)&&/^\d/.test(L)){var H=E.left,K=I.runtimeStyle.left;I.runtimeStyle.left=I.currentStyle.left;E.left=L||0;L=E.pixelLeft+"px";E.left=H;I.runtimeStyle.left=K}}}}return L},clean:function(F,K,I){K=K||document;if(typeof K.createElement==="undefined"){K=K.ownerDocument||K[0]&&K[0].ownerDocument||document}if(!I&&F.length===1&&typeof F[0]==="string"){var H=/^<(\w+)\s*\/?>$/.exec(F[0]);if(H){return[K.createElement(H[1])]}}var G=[],E=[],L=K.createElement("div");o.each(F,function(P,S){if(typeof S==="number"){S+=""}if(!S){return}if(typeof S==="string"){S=S.replace(/(<(\w+)[^>]*?)\/>/g,function(U,V,T){return T.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?U:V+"></"+T+">"});var O=S.replace(/^\s+/,"").substring(0,10).toLowerCase();var Q=!O.indexOf("<opt")&&[1,"<select multiple='multiple'>","</select>"]||!O.indexOf("<leg")&&[1,"<fieldset>","</fieldset>"]||O.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"<table>","</table>"]||!O.indexOf("<tr")&&[2,"<table><tbody>","</tbody></table>"]||(!O.indexOf("<td")||!O.indexOf("<th"))&&[3,"<table><tbody><tr>","</tr></tbody></table>"]||!O.indexOf("<col")&&[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"]||!o.support.htmlSerialize&&[1,"div<div>","</div>"]||[0,"",""];L.innerHTML=Q[1]+S+Q[2];while(Q[0]--){L=L.lastChild}if(!o.support.tbody){var R=/<tbody/i.test(S),N=!O.indexOf("<table")&&!R?L.firstChild&&L.firstChild.childNodes:Q[1]=="<table>"&&!R?L.childNodes:[];for(var M=N.length-1;M>=0;--M){if(o.nodeName(N[M],"tbody")&&!N[M].childNodes.length){N[M].parentNode.removeChild(N[M])}}}if(!o.support.leadingWhitespace&&/^\s/.test(S)){L.insertBefore(K.createTextNode(S.match(/^\s*/)[0]),L.firstChild)}S=o.makeArray(L.childNodes)}if(S.nodeType){G.push(S)}else{G=o.merge(G,S)}});if(I){for(var J=0;G[J];J++){if(o.nodeName(G[J],"script")&&(!G[J].type||G[J].type.toLowerCase()==="text/javascript")){E.push(G[J].parentNode?G[J].parentNode.removeChild(G[J]):G[J])}else{if(G[J].nodeType===1){G.splice.apply(G,[J+1,0].concat(o.makeArray(G[J].getElementsByTagName("script"))))}I.appendChild(G[J])}}return E}return G},attr:function(J,G,K){if(!J||J.nodeType==3||J.nodeType==8){return g}var H=!o.isXMLDoc(J),L=K!==g;G=H&&o.props[G]||G;if(J.tagName){var F=/href|src|style/.test(G);if(G=="selected"&&J.parentNode){J.parentNode.selectedIndex}if(G in J&&H&&!F){if(L){if(G=="type"&&o.nodeName(J,"input")&&J.parentNode){throw"type property can't be changed"}J[G]=K}if(o.nodeName(J,"form")&&J.getAttributeNode(G)){return J.getAttributeNode(G).nodeValue}if(G=="tabIndex"){var I=J.getAttributeNode("tabIndex");return I&&I.specified?I.value:J.nodeName.match(/(button|input|object|select|textarea)/i)?0:J.nodeName.match(/^(a|area)$/i)&&J.href?0:g}return J[G]}if(!o.support.style&&H&&G=="style"){return o.attr(J.style,"cssText",K)}if(L){J.setAttribute(G,""+K)}var E=!o.support.hrefNormalized&&H&&F?J.getAttribute(G,2):J.getAttribute(G);return E===null?g:E}if(!o.support.opacity&&G=="opacity"){if(L){J.zoom=1;J.filter=(J.filter||"").replace(/alpha\([^)]*\)/,"")+(parseInt(K)+""=="NaN"?"":"alpha(opacity="+K*100+")")}return J.filter&&J.filter.indexOf("opacity=")>=0?(parseFloat(J.filter.match(/opacity=([^)]*)/)[1])/100)+"":""}G=G.replace(/-([a-z])/ig,function(M,N){return N.toUpperCase()});if(L){J[G]=K}return J[G]},trim:function(E){return(E||"").replace(/^\s+|\s+$/g,"")},makeArray:function(G){var E=[];if(G!=null){var F=G.length;if(F==null||typeof G==="string"||o.isFunction(G)||G.setInterval){E[0]=G}else{while(F){E[--F]=G[F]}}}return E},inArray:function(G,H){for(var E=0,F=H.length;E<F;E++){if(H[E]===G){return E}}return -1},merge:function(H,E){var F=0,G,I=H.length;if(!o.support.getAll){while((G=E[F++])!=null){if(G.nodeType!=8){H[I++]=G}}}else{while((G=E[F++])!=null){H[I++]=G}}return H},unique:function(K){var F=[],E={};try{for(var G=0,H=K.length;G<H;G++){var J=o.data(K[G]);if(!E[J]){E[J]=true;F.push(K[G])}}}catch(I){F=K}return F},grep:function(F,J,E){var G=[];for(var H=0,I=F.length;H<I;H++){if(!E!=!J(F[H],H)){G.push(F[H])}}return G},map:function(E,J){var F=[];for(var G=0,H=E.length;G<H;G++){var I=J(E[G],G);if(I!=null){F[F.length]=I}}return F.concat.apply([],F)}});var C=navigator.userAgent.toLowerCase();o.browser={version:(C.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)||[0,"0"])[1],safari:/webkit/.test(C),opera:/opera/.test(C),msie:/msie/.test(C)&&!/opera/.test(C),mozilla:/mozilla/.test(C)&&!/(compatible|webkit)/.test(C)};o.each({parent:function(E){return E.parentNode},parents:function(E){return o.dir(E,"parentNode")},next:function(E){return o.nth(E,2,"nextSibling")},prev:function(E){return o.nth(E,2,"previousSibling")},nextAll:function(E){return o.dir(E,"nextSibling")},prevAll:function(E){return o.dir(E,"previousSibling")},siblings:function(E){return o.sibling(E.parentNode.firstChild,E)},children:function(E){return o.sibling(E.firstChild)},contents:function(E){return o.nodeName(E,"iframe")?E.contentDocument||E.contentWindow.document:o.makeArray(E.childNodes)}},function(E,F){o.fn[E]=function(G){var H=o.map(this,F);if(G&&typeof G=="string"){H=o.multiFilter(G,H)}return this.pushStack(o.unique(H),E,G)}});o.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(E,F){o.fn[E]=function(G){var J=[],L=o(G);for(var K=0,H=L.length;K<H;K++){var I=(K>0?this.clone(true):this).get();o.fn[F].apply(o(L[K]),I);J=J.concat(I)}return this.pushStack(J,E,G)}});o.each({removeAttr:function(E){o.attr(this,E,"");if(this.nodeType==1){this.removeAttribute(E)}},addClass:function(E){o.className.add(this,E)},removeClass:function(E){o.className.remove(this,E)},toggleClass:function(F,E){if(typeof E!=="boolean"){E=!o.className.has(this,F)}o.className[E?"add":"remove"](this,F)},remove:function(E){if(!E||o.filter(E,[this]).length){o("*",this).add([this]).each(function(){o.event.remove(this);o.removeData(this)});if(this.parentNode){this.parentNode.removeChild(this)}}},empty:function(){o(this).children().remove();while(this.firstChild){this.removeChild(this.firstChild)}}},function(E,F){o.fn[E]=function(){return this.each(F,arguments)}});function j(E,F){return E[0]&&parseInt(o.curCSS(E[0],F,true),10)||0}var h="jQuery"+e(),v=0,A={};o.extend({cache:{},data:function(F,E,G){F=F==l?A:F;var H=F[h];if(!H){H=F[h]=++v}if(E&&!o.cache[H]){o.cache[H]={}}if(G!==g){o.cache[H][E]=G}return E?o.cache[H][E]:H},removeData:function(F,E){F=F==l?A:F;var H=F[h];if(E){if(o.cache[H]){delete o.cache[H][E];E="";for(E in o.cache[H]){break}if(!E){o.removeData(F)}}}else{try{delete F[h]}catch(G){if(F.removeAttribute){F.removeAttribute(h)}}delete o.cache[H]}},queue:function(F,E,H){if(F){E=(E||"fx")+"queue";var G=o.data(F,E);if(!G||o.isArray(H)){G=o.data(F,E,o.makeArray(H))}else{if(H){G.push(H)}}}return G},dequeue:function(H,G){var E=o.queue(H,G),F=E.shift();if(!G||G==="fx"){F=E[0]}if(F!==g){F.call(H)}}});o.fn.extend({data:function(E,G){var H=E.split(".");H[1]=H[1]?"."+H[1]:"";if(G===g){var F=this.triggerHandler("getData"+H[1]+"!",[H[0]]);if(F===g&&this.length){F=o.data(this[0],E)}return F===g&&H[1]?this.data(H[0]):F}else{return this.trigger("setData"+H[1]+"!",[H[0],G]).each(function(){o.data(this,E,G)})}},removeData:function(E){return this.each(function(){o.removeData(this,E)})},queue:function(E,F){if(typeof E!=="string"){F=E;E="fx"}if(F===g){return o.queue(this[0],E)}return this.each(function(){var G=o.queue(this,E,F);if(E=="fx"&&G.length==1){G[0].call(this)}})},dequeue:function(E){return this.each(function(){o.dequeue(this,E)})}});
+/*
+ * Sizzle CSS Selector Engine - v0.9.3
+ * Copyright 2009, The Dojo Foundation
+ * Released under the MIT, BSD, and GPL Licenses.
+ * More information: http://sizzlejs.com/
+ */
+(function(){var R=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?/g,L=0,H=Object.prototype.toString;var F=function(Y,U,ab,ac){ab=ab||[];U=U||document;if(U.nodeType!==1&&U.nodeType!==9){return[]}if(!Y||typeof Y!=="string"){return ab}var Z=[],W,af,ai,T,ad,V,X=true;R.lastIndex=0;while((W=R.exec(Y))!==null){Z.push(W[1]);if(W[2]){V=RegExp.rightContext;break}}if(Z.length>1&&M.exec(Y)){if(Z.length===2&&I.relative[Z[0]]){af=J(Z[0]+Z[1],U)}else{af=I.relative[Z[0]]?[U]:F(Z.shift(),U);while(Z.length){Y=Z.shift();if(I.relative[Y]){Y+=Z.shift()}af=J(Y,af)}}}else{var ae=ac?{expr:Z.pop(),set:E(ac)}:F.find(Z.pop(),Z.length===1&&U.parentNode?U.parentNode:U,Q(U));af=F.filter(ae.expr,ae.set);if(Z.length>0){ai=E(af)}else{X=false}while(Z.length){var ah=Z.pop(),ag=ah;if(!I.relative[ah]){ah=""}else{ag=Z.pop()}if(ag==null){ag=U}I.relative[ah](ai,ag,Q(U))}}if(!ai){ai=af}if(!ai){throw"Syntax error, unrecognized expression: "+(ah||Y)}if(H.call(ai)==="[object Array]"){if(!X){ab.push.apply(ab,ai)}else{if(U.nodeType===1){for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&(ai[aa]===true||ai[aa].nodeType===1&&K(U,ai[aa]))){ab.push(af[aa])}}}else{for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&ai[aa].nodeType===1){ab.push(af[aa])}}}}}else{E(ai,ab)}if(V){F(V,U,ab,ac);if(G){hasDuplicate=false;ab.sort(G);if(hasDuplicate){for(var aa=1;aa<ab.length;aa++){if(ab[aa]===ab[aa-1]){ab.splice(aa--,1)}}}}}return ab};F.matches=function(T,U){return F(T,null,null,U)};F.find=function(aa,T,ab){var Z,X;if(!aa){return[]}for(var W=0,V=I.order.length;W<V;W++){var Y=I.order[W],X;if((X=I.match[Y].exec(aa))){var U=RegExp.leftContext;if(U.substr(U.length-1)!=="\\"){X[1]=(X[1]||"").replace(/\\/g,"");Z=I.find[Y](X,T,ab);if(Z!=null){aa=aa.replace(I.match[Y],"");break}}}}if(!Z){Z=T.getElementsByTagName("*")}return{set:Z,expr:aa}};F.filter=function(ad,ac,ag,W){var V=ad,ai=[],aa=ac,Y,T,Z=ac&&ac[0]&&Q(ac[0]);while(ad&&ac.length){for(var ab in I.filter){if((Y=I.match[ab].exec(ad))!=null){var U=I.filter[ab],ah,af;T=false;if(aa==ai){ai=[]}if(I.preFilter[ab]){Y=I.preFilter[ab](Y,aa,ag,ai,W,Z);if(!Y){T=ah=true}else{if(Y===true){continue}}}if(Y){for(var X=0;(af=aa[X])!=null;X++){if(af){ah=U(af,Y,X,aa);var ae=W^!!ah;if(ag&&ah!=null){if(ae){T=true}else{aa[X]=false}}else{if(ae){ai.push(af);T=true}}}}}if(ah!==g){if(!ag){aa=ai}ad=ad.replace(I.match[ab],"");if(!T){return[]}break}}}if(ad==V){if(T==null){throw"Syntax error, unrecognized expression: "+ad}else{break}}V=ad}return aa};var I=F.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF_-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF_-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*_-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF_-]|\\.)+)(?:\((['"]*)((?:\([^\)]+\)|[^\2\(\)]*)+)\2\))?/},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(T){return T.getAttribute("href")}},relative:{"+":function(aa,T,Z){var X=typeof T==="string",ab=X&&!/\W/.test(T),Y=X&&!ab;if(ab&&!Z){T=T.toUpperCase()}for(var W=0,V=aa.length,U;W<V;W++){if((U=aa[W])){while((U=U.previousSibling)&&U.nodeType!==1){}aa[W]=Y||U&&U.nodeName===T?U||false:U===T}}if(Y){F.filter(T,aa,true)}},">":function(Z,U,aa){var X=typeof U==="string";if(X&&!/\W/.test(U)){U=aa?U:U.toUpperCase();for(var V=0,T=Z.length;V<T;V++){var Y=Z[V];if(Y){var W=Y.parentNode;Z[V]=W.nodeName===U?W:false}}}else{for(var V=0,T=Z.length;V<T;V++){var Y=Z[V];if(Y){Z[V]=X?Y.parentNode:Y.parentNode===U}}if(X){F.filter(U,Z,true)}}},"":function(W,U,Y){var V=L++,T=S;if(!U.match(/\W/)){var X=U=Y?U:U.toUpperCase();T=P}T("parentNode",U,V,W,X,Y)},"~":function(W,U,Y){var V=L++,T=S;if(typeof U==="string"&&!U.match(/\W/)){var X=U=Y?U:U.toUpperCase();T=P}T("previousSibling",U,V,W,X,Y)}},find:{ID:function(U,V,W){if(typeof V.getElementById!=="undefined"&&!W){var T=V.getElementById(U[1]);return T?[T]:[]}},NAME:function(V,Y,Z){if(typeof Y.getElementsByName!=="undefined"){var U=[],X=Y.getElementsByName(V[1]);for(var W=0,T=X.length;W<T;W++){if(X[W].getAttribute("name")===V[1]){U.push(X[W])}}return U.length===0?null:U}},TAG:function(T,U){return U.getElementsByTagName(T[1])}},preFilter:{CLASS:function(W,U,V,T,Z,aa){W=" "+W[1].replace(/\\/g,"")+" ";if(aa){return W}for(var X=0,Y;(Y=U[X])!=null;X++){if(Y){if(Z^(Y.className&&(" "+Y.className+" ").indexOf(W)>=0)){if(!V){T.push(Y)}}else{if(V){U[X]=false}}}}return false},ID:function(T){return T[1].replace(/\\/g,"")},TAG:function(U,T){for(var V=0;T[V]===false;V++){}return T[V]&&Q(T[V])?U[1]:U[1].toUpperCase()},CHILD:function(T){if(T[1]=="nth"){var U=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(T[2]=="even"&&"2n"||T[2]=="odd"&&"2n+1"||!/\D/.test(T[2])&&"0n+"+T[2]||T[2]);T[2]=(U[1]+(U[2]||1))-0;T[3]=U[3]-0}T[0]=L++;return T},ATTR:function(X,U,V,T,Y,Z){var W=X[1].replace(/\\/g,"");if(!Z&&I.attrMap[W]){X[1]=I.attrMap[W]}if(X[2]==="~="){X[4]=" "+X[4]+" "}return X},PSEUDO:function(X,U,V,T,Y){if(X[1]==="not"){if(X[3].match(R).length>1||/^\w/.test(X[3])){X[3]=F(X[3],null,null,U)}else{var W=F.filter(X[3],U,V,true^Y);if(!V){T.push.apply(T,W)}return false}}else{if(I.match.POS.test(X[0])||I.match.CHILD.test(X[0])){return true}}return X},POS:function(T){T.unshift(true);return T}},filters:{enabled:function(T){return T.disabled===false&&T.type!=="hidden"},disabled:function(T){return T.disabled===true},checked:function(T){return T.checked===true},selected:function(T){T.parentNode.selectedIndex;return T.selected===true},parent:function(T){return !!T.firstChild},empty:function(T){return !T.firstChild},has:function(V,U,T){return !!F(T[3],V).length},header:function(T){return/h\d/i.test(T.nodeName)},text:function(T){return"text"===T.type},radio:function(T){return"radio"===T.type},checkbox:function(T){return"checkbox"===T.type},file:function(T){return"file"===T.type},password:function(T){return"password"===T.type},submit:function(T){return"submit"===T.type},image:function(T){return"image"===T.type},reset:function(T){return"reset"===T.type},button:function(T){return"button"===T.type||T.nodeName.toUpperCase()==="BUTTON"},input:function(T){return/input|select|textarea|button/i.test(T.nodeName)}},setFilters:{first:function(U,T){return T===0},last:function(V,U,T,W){return U===W.length-1},even:function(U,T){return T%2===0},odd:function(U,T){return T%2===1},lt:function(V,U,T){return U<T[3]-0},gt:function(V,U,T){return U>T[3]-0},nth:function(V,U,T){return T[3]-0==U},eq:function(V,U,T){return T[3]-0==U}},filter:{PSEUDO:function(Z,V,W,aa){var U=V[1],X=I.filters[U];if(X){return X(Z,W,V,aa)}else{if(U==="contains"){return(Z.textContent||Z.innerText||"").indexOf(V[3])>=0}else{if(U==="not"){var Y=V[3];for(var W=0,T=Y.length;W<T;W++){if(Y[W]===Z){return false}}return true}}}},CHILD:function(T,W){var Z=W[1],U=T;switch(Z){case"only":case"first":while(U=U.previousSibling){if(U.nodeType===1){return false}}if(Z=="first"){return true}U=T;case"last":while(U=U.nextSibling){if(U.nodeType===1){return false}}return true;case"nth":var V=W[2],ac=W[3];if(V==1&&ac==0){return true}var Y=W[0],ab=T.parentNode;if(ab&&(ab.sizcache!==Y||!T.nodeIndex)){var X=0;for(U=ab.firstChild;U;U=U.nextSibling){if(U.nodeType===1){U.nodeIndex=++X}}ab.sizcache=Y}var aa=T.nodeIndex-ac;if(V==0){return aa==0}else{return(aa%V==0&&aa/V>=0)}}},ID:function(U,T){return U.nodeType===1&&U.getAttribute("id")===T},TAG:function(U,T){return(T==="*"&&U.nodeType===1)||U.nodeName===T},CLASS:function(U,T){return(" "+(U.className||U.getAttribute("class"))+" ").indexOf(T)>-1},ATTR:function(Y,W){var V=W[1],T=I.attrHandle[V]?I.attrHandle[V](Y):Y[V]!=null?Y[V]:Y.getAttribute(V),Z=T+"",X=W[2],U=W[4];return T==null?X==="!=":X==="="?Z===U:X==="*="?Z.indexOf(U)>=0:X==="~="?(" "+Z+" ").indexOf(U)>=0:!U?Z&&T!==false:X==="!="?Z!=U:X==="^="?Z.indexOf(U)===0:X==="$="?Z.substr(Z.length-U.length)===U:X==="|="?Z===U||Z.substr(0,U.length+1)===U+"-":false},POS:function(X,U,V,Y){var T=U[2],W=I.setFilters[T];if(W){return W(X,V,U,Y)}}}};var M=I.match.POS;for(var O in I.match){I.match[O]=RegExp(I.match[O].source+/(?![^\[]*\])(?![^\(]*\))/.source)}var E=function(U,T){U=Array.prototype.slice.call(U);if(T){T.push.apply(T,U);return T}return U};try{Array.prototype.slice.call(document.documentElement.childNodes)}catch(N){E=function(X,W){var U=W||[];if(H.call(X)==="[object Array]"){Array.prototype.push.apply(U,X)}else{if(typeof X.length==="number"){for(var V=0,T=X.length;V<T;V++){U.push(X[V])}}else{for(var V=0;X[V];V++){U.push(X[V])}}}return U}}var G;if(document.documentElement.compareDocumentPosition){G=function(U,T){var V=U.compareDocumentPosition(T)&4?-1:U===T?0:1;if(V===0){hasDuplicate=true}return V}}else{if("sourceIndex" in document.documentElement){G=function(U,T){var V=U.sourceIndex-T.sourceIndex;if(V===0){hasDuplicate=true}return V}}else{if(document.createRange){G=function(W,U){var V=W.ownerDocument.createRange(),T=U.ownerDocument.createRange();V.selectNode(W);V.collapse(true);T.selectNode(U);T.collapse(true);var X=V.compareBoundaryPoints(Range.START_TO_END,T);if(X===0){hasDuplicate=true}return X}}}}(function(){var U=document.createElement("form"),V="script"+(new Date).getTime();U.innerHTML="<input name='"+V+"'/>";var T=document.documentElement;T.insertBefore(U,T.firstChild);if(!!document.getElementById(V)){I.find.ID=function(X,Y,Z){if(typeof Y.getElementById!=="undefined"&&!Z){var W=Y.getElementById(X[1]);return W?W.id===X[1]||typeof W.getAttributeNode!=="undefined"&&W.getAttributeNode("id").nodeValue===X[1]?[W]:g:[]}};I.filter.ID=function(Y,W){var X=typeof Y.getAttributeNode!=="undefined"&&Y.getAttributeNode("id");return Y.nodeType===1&&X&&X.nodeValue===W}}T.removeChild(U)})();(function(){var T=document.createElement("div");T.appendChild(document.createComment(""));if(T.getElementsByTagName("*").length>0){I.find.TAG=function(U,Y){var X=Y.getElementsByTagName(U[1]);if(U[1]==="*"){var W=[];for(var V=0;X[V];V++){if(X[V].nodeType===1){W.push(X[V])}}X=W}return X}}T.innerHTML="<a href='#'></a>";if(T.firstChild&&typeof T.firstChild.getAttribute!=="undefined"&&T.firstChild.getAttribute("href")!=="#"){I.attrHandle.href=function(U){return U.getAttribute("href",2)}}})();if(document.querySelectorAll){(function(){var T=F,U=document.createElement("div");U.innerHTML="<p class='TEST'></p>";if(U.querySelectorAll&&U.querySelectorAll(".TEST").length===0){return}F=function(Y,X,V,W){X=X||document;if(!W&&X.nodeType===9&&!Q(X)){try{return E(X.querySelectorAll(Y),V)}catch(Z){}}return T(Y,X,V,W)};F.find=T.find;F.filter=T.filter;F.selectors=T.selectors;F.matches=T.matches})()}if(document.getElementsByClassName&&document.documentElement.getElementsByClassName){(function(){var T=document.createElement("div");T.innerHTML="<div class='test e'></div><div class='test'></div>";if(T.getElementsByClassName("e").length===0){return}T.lastChild.className="e";if(T.getElementsByClassName("e").length===1){return}I.order.splice(1,0,"CLASS");I.find.CLASS=function(U,V,W){if(typeof V.getElementsByClassName!=="undefined"&&!W){return V.getElementsByClassName(U[1])}}})()}function P(U,Z,Y,ad,aa,ac){var ab=U=="previousSibling"&&!ac;for(var W=0,V=ad.length;W<V;W++){var T=ad[W];if(T){if(ab&&T.nodeType===1){T.sizcache=Y;T.sizset=W}T=T[U];var X=false;while(T){if(T.sizcache===Y){X=ad[T.sizset];break}if(T.nodeType===1&&!ac){T.sizcache=Y;T.sizset=W}if(T.nodeName===Z){X=T;break}T=T[U]}ad[W]=X}}}function S(U,Z,Y,ad,aa,ac){var ab=U=="previousSibling"&&!ac;for(var W=0,V=ad.length;W<V;W++){var T=ad[W];if(T){if(ab&&T.nodeType===1){T.sizcache=Y;T.sizset=W}T=T[U];var X=false;while(T){if(T.sizcache===Y){X=ad[T.sizset];break}if(T.nodeType===1){if(!ac){T.sizcache=Y;T.sizset=W}if(typeof Z!=="string"){if(T===Z){X=true;break}}else{if(F.filter(Z,[T]).length>0){X=T;break}}}T=T[U]}ad[W]=X}}}var K=document.compareDocumentPosition?function(U,T){return U.compareDocumentPosition(T)&16}:function(U,T){return U!==T&&(U.contains?U.contains(T):true)};var Q=function(T){return T.nodeType===9&&T.documentElement.nodeName!=="HTML"||!!T.ownerDocument&&Q(T.ownerDocument)};var J=function(T,aa){var W=[],X="",Y,V=aa.nodeType?[aa]:aa;while((Y=I.match.PSEUDO.exec(T))){X+=Y[0];T=T.replace(I.match.PSEUDO,"")}T=I.relative[T]?T+"*":T;for(var Z=0,U=V.length;Z<U;Z++){F(T,V[Z],W)}return F.filter(X,W)};o.find=F;o.filter=F.filter;o.expr=F.selectors;o.expr[":"]=o.expr.filters;F.selectors.filters.hidden=function(T){return T.offsetWidth===0||T.offsetHeight===0};F.selectors.filters.visible=function(T){return T.offsetWidth>0||T.offsetHeight>0};F.selectors.filters.animated=function(T){return o.grep(o.timers,function(U){return T===U.elem}).length};o.multiFilter=function(V,T,U){if(U){V=":not("+V+")"}return F.matches(V,T)};o.dir=function(V,U){var T=[],W=V[U];while(W&&W!=document){if(W.nodeType==1){T.push(W)}W=W[U]}return T};o.nth=function(X,T,V,W){T=T||1;var U=0;for(;X;X=X[V]){if(X.nodeType==1&&++U==T){break}}return X};o.sibling=function(V,U){var T=[];for(;V;V=V.nextSibling){if(V.nodeType==1&&V!=U){T.push(V)}}return T};return;l.Sizzle=F})();o.event={add:function(I,F,H,K){if(I.nodeType==3||I.nodeType==8){return}if(I.setInterval&&I!=l){I=l}if(!H.guid){H.guid=this.guid++}if(K!==g){var G=H;H=this.proxy(G);H.data=K}var E=o.data(I,"events")||o.data(I,"events",{}),J=o.data(I,"handle")||o.data(I,"handle",function(){return typeof o!=="undefined"&&!o.event.triggered?o.event.handle.apply(arguments.callee.elem,arguments):g});J.elem=I;o.each(F.split(/\s+/),function(M,N){var O=N.split(".");N=O.shift();H.type=O.slice().sort().join(".");var L=E[N];if(o.event.specialAll[N]){o.event.specialAll[N].setup.call(I,K,O)}if(!L){L=E[N]={};if(!o.event.special[N]||o.event.special[N].setup.call(I,K,O)===false){if(I.addEventListener){I.addEventListener(N,J,false)}else{if(I.attachEvent){I.attachEvent("on"+N,J)}}}}L[H.guid]=H;o.event.global[N]=true});I=null},guid:1,global:{},remove:function(K,H,J){if(K.nodeType==3||K.nodeType==8){return}var G=o.data(K,"events"),F,E;if(G){if(H===g||(typeof H==="string"&&H.charAt(0)==".")){for(var I in G){this.remove(K,I+(H||""))}}else{if(H.type){J=H.handler;H=H.type}o.each(H.split(/\s+/),function(M,O){var Q=O.split(".");O=Q.shift();var N=RegExp("(^|\\.)"+Q.slice().sort().join(".*\\.")+"(\\.|$)");if(G[O]){if(J){delete G[O][J.guid]}else{for(var P in G[O]){if(N.test(G[O][P].type)){delete G[O][P]}}}if(o.event.specialAll[O]){o.event.specialAll[O].teardown.call(K,Q)}for(F in G[O]){break}if(!F){if(!o.event.special[O]||o.event.special[O].teardown.call(K,Q)===false){if(K.removeEventListener){K.removeEventListener(O,o.data(K,"handle"),false)}else{if(K.detachEvent){K.detachEvent("on"+O,o.data(K,"handle"))}}}F=null;delete G[O]}}})}for(F in G){break}if(!F){var L=o.data(K,"handle");if(L){L.elem=null}o.removeData(K,"events");o.removeData(K,"handle")}}},trigger:function(I,K,H,E){var G=I.type||I;if(!E){I=typeof I==="object"?I[h]?I:o.extend(o.Event(G),I):o.Event(G);if(G.indexOf("!")>=0){I.type=G=G.slice(0,-1);I.exclusive=true}if(!H){I.stopPropagation();if(this.global[G]){o.each(o.cache,function(){if(this.events&&this.events[G]){o.event.trigger(I,K,this.handle.elem)}})}}if(!H||H.nodeType==3||H.nodeType==8){return g}I.result=g;I.target=H;K=o.makeArray(K);K.unshift(I)}I.currentTarget=H;var J=o.data(H,"handle");if(J){J.apply(H,K)}if((!H[G]||(o.nodeName(H,"a")&&G=="click"))&&H["on"+G]&&H["on"+G].apply(H,K)===false){I.result=false}if(!E&&H[G]&&!I.isDefaultPrevented()&&!(o.nodeName(H,"a")&&G=="click")){this.triggered=true;try{H[G]()}catch(L){}}this.triggered=false;if(!I.isPropagationStopped()){var F=H.parentNode||H.ownerDocument;if(F){o.event.trigger(I,K,F,true)}}},handle:function(K){var J,E;K=arguments[0]=o.event.fix(K||l.event);K.currentTarget=this;var L=K.type.split(".");K.type=L.shift();J=!L.length&&!K.exclusive;var I=RegExp("(^|\\.)"+L.slice().sort().join(".*\\.")+"(\\.|$)");E=(o.data(this,"events")||{})[K.type];for(var G in E){var H=E[G];if(J||I.test(H.type)){K.handler=H;K.data=H.data;var F=H.apply(this,arguments);if(F!==g){K.result=F;if(F===false){K.preventDefault();K.stopPropagation()}}if(K.isImmediatePropagationStopped()){break}}}},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),fix:function(H){if(H[h]){return H}var F=H;H=o.Event(F);for(var G=this.props.length,J;G;){J=this.props[--G];H[J]=F[J]}if(!H.target){H.target=H.srcElement||document}if(H.target.nodeType==3){H.target=H.target.parentNode}if(!H.relatedTarget&&H.fromElement){H.relatedTarget=H.fromElement==H.target?H.toElement:H.fromElement}if(H.pageX==null&&H.clientX!=null){var I=document.documentElement,E=document.body;H.pageX=H.clientX+(I&&I.scrollLeft||E&&E.scrollLeft||0)-(I.clientLeft||0);H.pageY=H.clientY+(I&&I.scrollTop||E&&E.scrollTop||0)-(I.clientTop||0)}if(!H.which&&((H.charCode||H.charCode===0)?H.charCode:H.keyCode)){H.which=H.charCode||H.keyCode}if(!H.metaKey&&H.ctrlKey){H.metaKey=H.ctrlKey}if(!H.which&&H.button){H.which=(H.button&1?1:(H.button&2?3:(H.button&4?2:0)))}return H},proxy:function(F,E){E=E||function(){return F.apply(this,arguments)};E.guid=F.guid=F.guid||E.guid||this.guid++;return E},special:{ready:{setup:B,teardown:function(){}}},specialAll:{live:{setup:function(E,F){o.event.add(this,F[0],c)},teardown:function(G){if(G.length){var E=0,F=RegExp("(^|\\.)"+G[0]+"(\\.|$)");o.each((o.data(this,"events").live||{}),function(){if(F.test(this.type)){E++}});if(E<1){o.event.remove(this,G[0],c)}}}}}};o.Event=function(E){if(!this.preventDefault){return new o.Event(E)}if(E&&E.type){this.originalEvent=E;this.type=E.type}else{this.type=E}this.timeStamp=e();this[h]=true};function k(){return false}function u(){return true}o.Event.prototype={preventDefault:function(){this.isDefaultPrevented=u;var E=this.originalEvent;if(!E){return}if(E.preventDefault){E.preventDefault()}E.returnValue=false},stopPropagation:function(){this.isPropagationStopped=u;var E=this.originalEvent;if(!E){return}if(E.stopPropagation){E.stopPropagation()}E.cancelBubble=true},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=u;this.stopPropagation()},isDefaultPrevented:k,isPropagationStopped:k,isImmediatePropagationStopped:k};var a=function(F){var E=F.relatedTarget;while(E&&E!=this){try{E=E.parentNode}catch(G){E=this}}if(E!=this){F.type=F.data;o.event.handle.apply(this,arguments)}};o.each({mouseover:"mouseenter",mouseout:"mouseleave"},function(F,E){o.event.special[E]={setup:function(){o.event.add(this,F,a,E)},teardown:function(){o.event.remove(this,F,a)}}});o.fn.extend({bind:function(F,G,E){return F=="unload"?this.one(F,G,E):this.each(function(){o.event.add(this,F,E||G,E&&G)})},one:function(G,H,F){var E=o.event.proxy(F||H,function(I){o(this).unbind(I,E);return(F||H).apply(this,arguments)});return this.each(function(){o.event.add(this,G,E,F&&H)})},unbind:function(F,E){return this.each(function(){o.event.remove(this,F,E)})},trigger:function(E,F){return this.each(function(){o.event.trigger(E,F,this)})},triggerHandler:function(E,G){if(this[0]){var F=o.Event(E);F.preventDefault();F.stopPropagation();o.event.trigger(F,G,this[0]);return F.result}},toggle:function(G){var E=arguments,F=1;while(F<E.length){o.event.proxy(G,E[F++])}return this.click(o.event.proxy(G,function(H){this.lastToggle=(this.lastToggle||0)%F;H.preventDefault();return E[this.lastToggle++].apply(this,arguments)||false}))},hover:function(E,F){return this.mouseenter(E).mouseleave(F)},ready:function(E){B();if(o.isReady){E.call(document,o)}else{o.readyList.push(E)}return this},live:function(G,F){var E=o.event.proxy(F);E.guid+=this.selector+G;o(document).bind(i(G,this.selector),this.selector,E);return this},die:function(F,E){o(document).unbind(i(F,this.selector),E?{guid:E.guid+this.selector+F}:null);return this}});function c(H){var E=RegExp("(^|\\.)"+H.type+"(\\.|$)"),G=true,F=[];o.each(o.data(this,"events").live||[],function(I,J){if(E.test(J.type)){var K=o(H.target).closest(J.data)[0];if(K){F.push({elem:K,fn:J})}}});F.sort(function(J,I){return o.data(J.elem,"closest")-o.data(I.elem,"closest")});o.each(F,function(){if(this.fn.call(this.elem,H,this.fn.data)===false){return(G=false)}});return G}function i(F,E){return["live",F,E.replace(/\./g,"`").replace(/ /g,"|")].join(".")}o.extend({isReady:false,readyList:[],ready:function(){if(!o.isReady){o.isReady=true;if(o.readyList){o.each(o.readyList,function(){this.call(document,o)});o.readyList=null}o(document).triggerHandler("ready")}}});var x=false;function B(){if(x){return}x=true;if(document.addEventListener){document.addEventListener("DOMContentLoaded",function(){document.removeEventListener("DOMContentLoaded",arguments.callee,false);o.ready()},false)}else{if(document.attachEvent){document.attachEvent("onreadystatechange",function(){if(document.readyState==="complete"){document.detachEvent("onreadystatechange",arguments.callee);o.ready()}});if(document.documentElement.doScroll&&l==l.top){(function(){if(o.isReady){return}try{document.documentElement.doScroll("left")}catch(E){setTimeout(arguments.callee,0);return}o.ready()})()}}}o.event.add(l,"load",o.ready)}o.each(("blur,focus,load,resize,scroll,unload,click,dblclick,mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave,change,select,submit,keydown,keypress,keyup,error").split(","),function(F,E){o.fn[E]=function(G){return G?this.bind(E,G):this.trigger(E)}});o(l).bind("unload",function(){for(var E in o.cache){if(E!=1&&o.cache[E].handle){o.event.remove(o.cache[E].handle.elem)}}});(function(){o.support={};var F=document.documentElement,G=document.createElement("script"),K=document.createElement("div"),J="script"+(new Date).getTime();K.style.display="none";K.innerHTML=' <link/><table></table><a href="/a" style="color:red;float:left;opacity:.5;">a</a><select><option>text</option></select><object><param/></object>';var H=K.getElementsByTagName("*"),E=K.getElementsByTagName("a")[0];if(!H||!H.length||!E){return}o.support={leadingWhitespace:K.firstChild.nodeType==3,tbody:!K.getElementsByTagName("tbody").length,objectAll:!!K.getElementsByTagName("object")[0].getElementsByTagName("*").length,htmlSerialize:!!K.getElementsByTagName("link").length,style:/red/.test(E.getAttribute("style")),hrefNormalized:E.getAttribute("href")==="/a",opacity:E.style.opacity==="0.5",cssFloat:!!E.style.cssFloat,scriptEval:false,noCloneEvent:true,boxModel:null};G.type="text/javascript";try{G.appendChild(document.createTextNode("window."+J+"=1;"))}catch(I){}F.insertBefore(G,F.firstChild);if(l[J]){o.support.scriptEval=true;delete l[J]}F.removeChild(G);if(K.attachEvent&&K.fireEvent){K.attachEvent("onclick",function(){o.support.noCloneEvent=false;K.detachEvent("onclick",arguments.callee)});K.cloneNode(true).fireEvent("onclick")}o(function(){var L=document.createElement("div");L.style.width=L.style.paddingLeft="1px";document.body.appendChild(L);o.boxModel=o.support.boxModel=L.offsetWidth===2;document.body.removeChild(L).style.display="none"})})();var w=o.support.cssFloat?"cssFloat":"styleFloat";o.props={"for":"htmlFor","class":"className","float":w,cssFloat:w,styleFloat:w,readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",tabindex:"tabIndex"};o.fn.extend({_load:o.fn.load,load:function(G,J,K){if(typeof G!=="string"){return this._load(G)}var I=G.indexOf(" ");if(I>=0){var E=G.slice(I,G.length);G=G.slice(0,I)}var H="GET";if(J){if(o.isFunction(J)){K=J;J=null}else{if(typeof J==="object"){J=o.param(J);H="POST"}}}var F=this;o.ajax({url:G,type:H,dataType:"html",data:J,complete:function(M,L){if(L=="success"||L=="notmodified"){F.html(E?o("<div/>").append(M.responseText.replace(/<script(.|\s)*?\/script>/g,"")).find(E):M.responseText)}if(K){F.each(K,[M.responseText,L,M])}}});return this},serialize:function(){return o.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?o.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password|search/i.test(this.type))}).map(function(E,F){var G=o(this).val();return G==null?null:o.isArray(G)?o.map(G,function(I,H){return{name:F.name,value:I}}):{name:F.name,value:G}}).get()}});o.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(E,F){o.fn[F]=function(G){return this.bind(F,G)}});var r=e();o.extend({get:function(E,G,H,F){if(o.isFunction(G)){H=G;G=null}return o.ajax({type:"GET",url:E,data:G,success:H,dataType:F})},getScript:function(E,F){return o.get(E,null,F,"script")},getJSON:function(E,F,G){return o.get(E,F,G,"json")},post:function(E,G,H,F){if(o.isFunction(G)){H=G;G={}}return o.ajax({type:"POST",url:E,data:G,success:H,dataType:F})},ajaxSetup:function(E){o.extend(o.ajaxSettings,E)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:function(){return l.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest()},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},ajax:function(M){M=o.extend(true,M,o.extend(true,{},o.ajaxSettings,M));var W,F=/=\?(&|$)/g,R,V,G=M.type.toUpperCase();if(M.data&&M.processData&&typeof M.data!=="string"){M.data=o.param(M.data)}if(M.dataType=="jsonp"){if(G=="GET"){if(!M.url.match(F)){M.url+=(M.url.match(/\?/)?"&":"?")+(M.jsonp||"callback")+"=?"}}else{if(!M.data||!M.data.match(F)){M.data=(M.data?M.data+"&":"")+(M.jsonp||"callback")+"=?"}}M.dataType="json"}if(M.dataType=="json"&&(M.data&&M.data.match(F)||M.url.match(F))){W="jsonp"+r++;if(M.data){M.data=(M.data+"").replace(F,"="+W+"$1")}M.url=M.url.replace(F,"="+W+"$1");M.dataType="script";l[W]=function(X){V=X;I();L();l[W]=g;try{delete l[W]}catch(Y){}if(H){H.removeChild(T)}}}if(M.dataType=="script"&&M.cache==null){M.cache=false}if(M.cache===false&&G=="GET"){var E=e();var U=M.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+E+"$2");M.url=U+((U==M.url)?(M.url.match(/\?/)?"&":"?")+"_="+E:"")}if(M.data&&G=="GET"){M.url+=(M.url.match(/\?/)?"&":"?")+M.data;M.data=null}if(M.global&&!o.active++){o.event.trigger("ajaxStart")}var Q=/^(\w+:)?\/\/([^\/?#]+)/.exec(M.url);if(M.dataType=="script"&&G=="GET"&&Q&&(Q[1]&&Q[1]!=location.protocol||Q[2]!=location.host)){var H=document.getElementsByTagName("head")[0];var T=document.createElement("script");T.src=M.url;if(M.scriptCharset){T.charset=M.scriptCharset}if(!W){var O=false;T.onload=T.onreadystatechange=function(){if(!O&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){O=true;I();L();T.onload=T.onreadystatechange=null;H.removeChild(T)}}}H.appendChild(T);return g}var K=false;var J=M.xhr();if(M.username){J.open(G,M.url,M.async,M.username,M.password)}else{J.open(G,M.url,M.async)}try{if(M.data){J.setRequestHeader("Content-Type",M.contentType)}if(M.ifModified){J.setRequestHeader("If-Modified-Since",o.lastModified[M.url]||"Thu, 01 Jan 1970 00:00:00 GMT")}J.setRequestHeader("X-Requested-With","XMLHttpRequest");J.setRequestHeader("Accept",M.dataType&&M.accepts[M.dataType]?M.accepts[M.dataType]+", */*":M.accepts._default)}catch(S){}if(M.beforeSend&&M.beforeSend(J,M)===false){if(M.global&&!--o.active){o.event.trigger("ajaxStop")}J.abort();return false}if(M.global){o.event.trigger("ajaxSend",[J,M])}var N=function(X){if(J.readyState==0){if(P){clearInterval(P);P=null;if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}}else{if(!K&&J&&(J.readyState==4||X=="timeout")){K=true;if(P){clearInterval(P);P=null}R=X=="timeout"?"timeout":!o.httpSuccess(J)?"error":M.ifModified&&o.httpNotModified(J,M.url)?"notmodified":"success";if(R=="success"){try{V=o.httpData(J,M.dataType,M)}catch(Z){R="parsererror"}}if(R=="success"){var Y;try{Y=J.getResponseHeader("Last-Modified")}catch(Z){}if(M.ifModified&&Y){o.lastModified[M.url]=Y}if(!W){I()}}else{o.handleError(M,J,R)}L();if(X){J.abort()}if(M.async){J=null}}}};if(M.async){var P=setInterval(N,13);if(M.timeout>0){setTimeout(function(){if(J&&!K){N("timeout")}},M.timeout)}}try{J.send(M.data)}catch(S){o.handleError(M,J,null,S)}if(!M.async){N()}function I(){if(M.success){M.success(V,R)}if(M.global){o.event.trigger("ajaxSuccess",[J,M])}}function L(){if(M.complete){M.complete(J,R)}if(M.global){o.event.trigger("ajaxComplete",[J,M])}if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}return J},handleError:function(F,H,E,G){if(F.error){F.error(H,E,G)}if(F.global){o.event.trigger("ajaxError",[H,F,G])}},active:0,httpSuccess:function(F){try{return !F.status&&location.protocol=="file:"||(F.status>=200&&F.status<300)||F.status==304||F.status==1223}catch(E){}return false},httpNotModified:function(G,E){try{var H=G.getResponseHeader("Last-Modified");return G.status==304||H==o.lastModified[E]}catch(F){}return false},httpData:function(J,H,G){var F=J.getResponseHeader("content-type"),E=H=="xml"||!H&&F&&F.indexOf("xml")>=0,I=E?J.responseXML:J.responseText;if(E&&I.documentElement.tagName=="parsererror"){throw"parsererror"}if(G&&G.dataFilter){I=G.dataFilter(I,H)}if(typeof I==="string"){if(H=="script"){o.globalEval(I)}if(H=="json"){I=l["eval"]("("+I+")")}}return I},param:function(E){var G=[];function H(I,J){G[G.length]=encodeURIComponent(I)+"="+encodeURIComponent(J)}if(o.isArray(E)||E.jquery){o.each(E,function(){H(this.name,this.value)})}else{for(var F in E){if(o.isArray(E[F])){o.each(E[F],function(){H(F,this)})}else{H(F,o.isFunction(E[F])?E[F]():E[F])}}}return G.join("&").replace(/%20/g,"+")}});var m={},n,d=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];function t(F,E){var G={};o.each(d.concat.apply([],d.slice(0,E)),function(){G[this]=F});return G}o.fn.extend({show:function(J,L){if(J){return this.animate(t("show",3),J,L)}else{for(var H=0,F=this.length;H<F;H++){var E=o.data(this[H],"olddisplay");this[H].style.display=E||"";if(o.css(this[H],"display")==="none"){var G=this[H].tagName,K;if(m[G]){K=m[G]}else{var I=o("<"+G+" />").appendTo("body");K=I.css("display");if(K==="none"){K="block"}I.remove();m[G]=K}o.data(this[H],"olddisplay",K)}}for(var H=0,F=this.length;H<F;H++){this[H].style.display=o.data(this[H],"olddisplay")||""}return this}},hide:function(H,I){if(H){return this.animate(t("hide",3),H,I)}else{for(var G=0,F=this.length;G<F;G++){var E=o.data(this[G],"olddisplay");if(!E&&E!=="none"){o.data(this[G],"olddisplay",o.css(this[G],"display"))}}for(var G=0,F=this.length;G<F;G++){this[G].style.display="none"}return this}},_toggle:o.fn.toggle,toggle:function(G,F){var E=typeof G==="boolean";return o.isFunction(G)&&o.isFunction(F)?this._toggle.apply(this,arguments):G==null||E?this.each(function(){var H=E?G:o(this).is(":hidden");o(this)[H?"show":"hide"]()}):this.animate(t("toggle",3),G,F)},fadeTo:function(E,G,F){return this.animate({opacity:G},E,F)},animate:function(I,F,H,G){var E=o.speed(F,H,G);return this[E.queue===false?"each":"queue"](function(){var K=o.extend({},E),M,L=this.nodeType==1&&o(this).is(":hidden"),J=this;for(M in I){if(I[M]=="hide"&&L||I[M]=="show"&&!L){return K.complete.call(this)}if((M=="height"||M=="width")&&this.style){K.display=o.css(this,"display");K.overflow=this.style.overflow}}if(K.overflow!=null){this.style.overflow="hidden"}K.curAnim=o.extend({},I);o.each(I,function(O,S){var R=new o.fx(J,K,O);if(/toggle|show|hide/.test(S)){R[S=="toggle"?L?"show":"hide":S](I)}else{var Q=S.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),T=R.cur(true)||0;if(Q){var N=parseFloat(Q[2]),P=Q[3]||"px";if(P!="px"){J.style[O]=(N||1)+P;T=((N||1)/R.cur(true))*T;J.style[O]=T+P}if(Q[1]){N=((Q[1]=="-="?-1:1)*N)+T}R.custom(T,N,P)}else{R.custom(T,S,"")}}});return true})},stop:function(F,E){var G=o.timers;if(F){this.queue([])}this.each(function(){for(var H=G.length-1;H>=0;H--){if(G[H].elem==this){if(E){G[H](true)}G.splice(H,1)}}});if(!E){this.dequeue()}return this}});o.each({slideDown:t("show",1),slideUp:t("hide",1),slideToggle:t("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(E,F){o.fn[E]=function(G,H){return this.animate(F,G,H)}});o.extend({speed:function(G,H,F){var E=typeof G==="object"?G:{complete:F||!F&&H||o.isFunction(G)&&G,duration:G,easing:F&&H||H&&!o.isFunction(H)&&H};E.duration=o.fx.off?0:typeof E.duration==="number"?E.duration:o.fx.speeds[E.duration]||o.fx.speeds._default;E.old=E.complete;E.complete=function(){if(E.queue!==false){o(this).dequeue()}if(o.isFunction(E.old)){E.old.call(this)}};return E},easing:{linear:function(G,H,E,F){return E+F*G},swing:function(G,H,E,F){return((-Math.cos(G*Math.PI)/2)+0.5)*F+E}},timers:[],fx:function(F,E,G){this.options=E;this.elem=F;this.prop=G;if(!E.orig){E.orig={}}}});o.fx.prototype={update:function(){if(this.options.step){this.options.step.call(this.elem,this.now,this)}(o.fx.step[this.prop]||o.fx.step._default)(this);if((this.prop=="height"||this.prop=="width")&&this.elem.style){this.elem.style.display="block"}},cur:function(F){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null)){return this.elem[this.prop]}var E=parseFloat(o.css(this.elem,this.prop,F));return E&&E>-10000?E:parseFloat(o.curCSS(this.elem,this.prop))||0},custom:function(I,H,G){this.startTime=e();this.start=I;this.end=H;this.unit=G||this.unit||"px";this.now=this.start;this.pos=this.state=0;var E=this;function F(J){return E.step(J)}F.elem=this.elem;if(F()&&o.timers.push(F)&&!n){n=setInterval(function(){var K=o.timers;for(var J=0;J<K.length;J++){if(!K[J]()){K.splice(J--,1)}}if(!K.length){clearInterval(n);n=g}},13)}},show:function(){this.options.orig[this.prop]=o.attr(this.elem.style,this.prop);this.options.show=true;this.custom(this.prop=="width"||this.prop=="height"?1:0,this.cur());o(this.elem).show()},hide:function(){this.options.orig[this.prop]=o.attr(this.elem.style,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(H){var G=e();if(H||G>=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var E=true;for(var F in this.options.curAnim){if(this.options.curAnim[F]!==true){E=false}}if(E){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(o.css(this.elem,"display")=="none"){this.elem.style.display="block"}}if(this.options.hide){o(this.elem).hide()}if(this.options.hide||this.options.show){for(var I in this.options.curAnim){o.attr(this.elem.style,I,this.options.orig[I])}}this.options.complete.call(this.elem)}return false}else{var J=G-this.startTime;this.state=J/this.options.duration;this.pos=o.easing[this.options.easing||(o.easing.swing?"swing":"linear")](this.state,J,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update()}return true}};o.extend(o.fx,{speeds:{slow:600,fast:200,_default:400},step:{opacity:function(E){o.attr(E.elem.style,"opacity",E.now)},_default:function(E){if(E.elem.style&&E.elem.style[E.prop]!=null){E.elem.style[E.prop]=E.now+E.unit}else{E.elem[E.prop]=E.now}}}});if(document.documentElement.getBoundingClientRect){o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}var G=this[0].getBoundingClientRect(),J=this[0].ownerDocument,F=J.body,E=J.documentElement,L=E.clientTop||F.clientTop||0,K=E.clientLeft||F.clientLeft||0,I=G.top+(self.pageYOffset||o.boxModel&&E.scrollTop||F.scrollTop)-L,H=G.left+(self.pageXOffset||o.boxModel&&E.scrollLeft||F.scrollLeft)-K;return{top:I,left:H}}}else{o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}o.offset.initialized||o.offset.initialize();var J=this[0],G=J.offsetParent,F=J,O=J.ownerDocument,M,H=O.documentElement,K=O.body,L=O.defaultView,E=L.getComputedStyle(J,null),N=J.offsetTop,I=J.offsetLeft;while((J=J.parentNode)&&J!==K&&J!==H){M=L.getComputedStyle(J,null);N-=J.scrollTop,I-=J.scrollLeft;if(J===G){N+=J.offsetTop,I+=J.offsetLeft;if(o.offset.doesNotAddBorder&&!(o.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(J.tagName))){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}F=G,G=J.offsetParent}if(o.offset.subtractsBorderForOverflowNotVisible&&M.overflow!=="visible"){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}E=M}if(E.position==="relative"||E.position==="static"){N+=K.offsetTop,I+=K.offsetLeft}if(E.position==="fixed"){N+=Math.max(H.scrollTop,K.scrollTop),I+=Math.max(H.scrollLeft,K.scrollLeft)}return{top:N,left:I}}}o.offset={initialize:function(){if(this.initialized){return}var L=document.body,F=document.createElement("div"),H,G,N,I,M,E,J=L.style.marginTop,K='<div style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;"><div></div></div><table style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;" cellpadding="0" cellspacing="0"><tr><td></td></tr></table>';M={position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"};for(E in M){F.style[E]=M[E]}F.innerHTML=K;L.insertBefore(F,L.firstChild);H=F.firstChild,G=H.firstChild,I=H.nextSibling.firstChild.firstChild;this.doesNotAddBorder=(G.offsetTop!==5);this.doesAddBorderForTableAndCells=(I.offsetTop===5);H.style.overflow="hidden",H.style.position="relative";this.subtractsBorderForOverflowNotVisible=(G.offsetTop===-5);L.style.marginTop="1px";this.doesNotIncludeMarginInBodyOffset=(L.offsetTop===0);L.style.marginTop=J;L.removeChild(F);this.initialized=true},bodyOffset:function(E){o.offset.initialized||o.offset.initialize();var G=E.offsetTop,F=E.offsetLeft;if(o.offset.doesNotIncludeMarginInBodyOffset){G+=parseInt(o.curCSS(E,"marginTop",true),10)||0,F+=parseInt(o.curCSS(E,"marginLeft",true),10)||0}return{top:G,left:F}}};o.fn.extend({position:function(){var I=0,H=0,F;if(this[0]){var G=this.offsetParent(),J=this.offset(),E=/^body|html$/i.test(G[0].tagName)?{top:0,left:0}:G.offset();J.top-=j(this,"marginTop");J.left-=j(this,"marginLeft");E.top+=j(G,"borderTopWidth");E.left+=j(G,"borderLeftWidth");F={top:J.top-E.top,left:J.left-E.left}}return F},offsetParent:function(){var E=this[0].offsetParent||document.body;while(E&&(!/^body|html$/i.test(E.tagName)&&o.css(E,"position")=="static")){E=E.offsetParent}return o(E)}});o.each(["Left","Top"],function(F,E){var G="scroll"+E;o.fn[G]=function(H){if(!this[0]){return null}return H!==g?this.each(function(){this==l||this==document?l.scrollTo(!F?H:o(l).scrollLeft(),F?H:o(l).scrollTop()):this[G]=H}):this[0]==l||this[0]==document?self[F?"pageYOffset":"pageXOffset"]||o.boxModel&&document.documentElement[G]||document.body[G]:this[0][G]}});o.each(["Height","Width"],function(I,G){var E=I?"Left":"Top",H=I?"Right":"Bottom",F=G.toLowerCase();o.fn["inner"+G]=function(){return this[0]?o.css(this[0],F,false,"padding"):null};o.fn["outer"+G]=function(K){return this[0]?o.css(this[0],F,false,K?"margin":"border"):null};var J=G.toLowerCase();o.fn[J]=function(K){return this[0]==l?document.compatMode=="CSS1Compat"&&document.documentElement["client"+G]||document.body["client"+G]:this[0]==document?Math.max(document.documentElement["client"+G],document.body["scroll"+G],document.documentElement["scroll"+G],document.body["offset"+G],document.documentElement["offset"+G]):K===g?(this.length?o.css(this[0],J):null):this.css(J,typeof K==="string"?K:K+"px")}})})();
\ No newline at end of file
diff --git a/src/server/public/stylesheets/main.css b/src/server/public/stylesheets/main.css
new file mode 100644
index 0000000..4fc7cbb
--- /dev/null
+++ b/src/server/public/stylesheets/main.css
@@ -0,0 +1,68 @@
+body {
+ background: #fff;
+ color: #000;
+ margin: 0px;
+ padding: 0px;
+ color: #333;
+ font-weight:bold;
+ font-family: serif;
+}
+
+#container {
+ padding: 2px;
+ margin: auto;
+ width: 900px;
+}
+
+#header {
+ width: 100%;
+ margin: 0px;
+ height: 95px;
+ background: #333;
+ border-bottom: solid 6px #000;
+ color:#fff;
+}
+
+#logo {
+ position: absolute;
+ padding-top: 20px;
+ padding-left: 45px;
+ font-weight:bold;
+ font-size: 55px;
+ color: #fff;
+}
+
+#search {
+ text-align: right;
+ padding-top: 20px;
+ padding-right: 50px;
+}
+
+.searchbox {
+ background: #663366;
+ border: 1px solid #000;
+ color: #fff;
+ font-size: 20px;
+ padding: 2px;
+ font-weight: none;
+}
+
+#main {
+ min-height: 500px;
+ _height: 500px; /* IE min-height hack */
+}
+
+#footer {
+ text-align: center;
+ width: 900px;
+}
+
+.adendem {
+ font-size: 14px;
+ font-weight: normal;
+}
+
+.in20 {
+ padding-left: 20px;
+ padding-right: 20px;
+}
\ No newline at end of file
diff --git a/src/server/test/functional/collection_daemon.rb b/src/server/test/functional/collection_daemon.rb
deleted file mode 100644
index 7e3c13a..0000000
--- a/src/server/test/functional/collection_daemon.rb
+++ /dev/null
@@ -1,8 +0,0 @@
-require 'test_helper'
-
-class LogCollectorTest < EventsControllerTest
- # Replace this with your real tests.
- test "the truth" do
- assert true
- end
-end
\ No newline at end of file
diff --git a/src/server/test/functional/collection_daemon_test.rb b/src/server/test/functional/collection_daemon_test.rb
new file mode 100644
index 0000000..77b740b
--- /dev/null
+++ b/src/server/test/functional/collection_daemon_test.rb
@@ -0,0 +1,10 @@
+require 'test_helper'
+require RAILS_ROOT + '/lib/modules/collection_server.rb'
+include CollectionServer
+
+class LogCollectorTest < ActionController::TestCase
+ test "the truth" do
+ assert true
+ end
+
+end
\ No newline at end of file
|
parabuzzle/cistern
|
8a50774d149bc964178f189d9a3f537d9f245c8c
|
started on the frontend
|
diff --git a/src/server/app/controllers/events_controller.rb b/src/server/app/controllers/events_controller.rb
new file mode 100644
index 0000000..5175242
--- /dev/null
+++ b/src/server/app/controllers/events_controller.rb
@@ -0,0 +1,2 @@
+class EventsController < ApplicationController
+end
diff --git a/src/server/app/helpers/events_helper.rb b/src/server/app/helpers/events_helper.rb
new file mode 100644
index 0000000..8a9a878
--- /dev/null
+++ b/src/server/app/helpers/events_helper.rb
@@ -0,0 +1,2 @@
+module EventsHelper
+end
diff --git a/src/server/test/functional/collection_daemon.rb b/src/server/test/functional/collection_daemon.rb
new file mode 100644
index 0000000..7e3c13a
--- /dev/null
+++ b/src/server/test/functional/collection_daemon.rb
@@ -0,0 +1,8 @@
+require 'test_helper'
+
+class LogCollectorTest < EventsControllerTest
+ # Replace this with your real tests.
+ test "the truth" do
+ assert true
+ end
+end
\ No newline at end of file
diff --git a/src/server/test/functional/events_controller_test.rb b/src/server/test/functional/events_controller_test.rb
new file mode 100644
index 0000000..313df4b
--- /dev/null
+++ b/src/server/test/functional/events_controller_test.rb
@@ -0,0 +1,8 @@
+require 'test_helper'
+
+class EventsControllerTest < ActionController::TestCase
+ # Replace this with your real tests.
+ test "the truth" do
+ assert true
+ end
+end
diff --git a/src/server/test/unit/helpers/events_helper_test.rb b/src/server/test/unit/helpers/events_helper_test.rb
new file mode 100644
index 0000000..2e7567e
--- /dev/null
+++ b/src/server/test/unit/helpers/events_helper_test.rb
@@ -0,0 +1,4 @@
+require 'test_helper'
+
+class EventsHelperTest < ActionView::TestCase
+end
|
parabuzzle/cistern
|
6687195cb1e88d336188f65df794ef585118796c
|
Refactored some stuff in the log collection module. Also made packet checksum validations work along with agent key checks
|
diff --git a/src/agent/logsender.rb b/src/agent/logsender.rb
index e1dd34f..0b438f0 100644
--- a/src/agent/logsender.rb
+++ b/src/agent/logsender.rb
@@ -1,25 +1,60 @@
require 'socket'
require 'yaml'
+require 'digest/md5'
include Socket::Constants
+@break = "__1_BB"
+@value = "__1_VV"
+@checksum = "__1_CC"
+
+
def close_tx(socket)
socket.write("__1_EE")
end
+def newvalbr(socket)
+ socket.write("__1_BB")
+end
+def valbr(socket)
+ socket.write("__1_VV")
+end
+def checkbr(socket)
+ socket.write("__1_CC")
+end
socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
sockaddr = Socket.pack_sockaddr_in( 9845, '127.0.0.1' )
socket.connect( sockaddr )
-#Write staticentry
+#Things you need...
+#data - static data
+#logtype_id - logtype
+#loglevel - The log level of the event
+#time - the original time of the event
+#payload - The dynamic data for the event (format - NAME=value)
+#agent_id - The reporting agent's id
+#
+#The entire sting should have a checksum or it will be thrown out
+
+event = Hash.new
+event.store("key", "123456")
+event.store("data","This is a log entry for <<<NAME>>>")
+event.store("logtype_id", 1)
+event.store("loglevel", 0)
+event.store("time", Time.now.to_f)
+event.store("payload", "NAME=TesterApp")
+event.store("agent_id", 1)
+
+e = String.new
+event.each do |key, val|
+ e = e + key.to_s + @value + val.to_s + @break
+end
+puts e
+e = e + @checksum + Digest::MD5.hexdigest(e) + "__1_EE"
+puts e
+socket.write(e)
+socket.write(e)
+socket.write(e)
+
-socket.write( "data=this is a log entry for <<NAME>>__1_B agent=1__1_Blogtype=apache__1_B" )
-socket.write("level=0__1_Btime=1248931696__1_Bpayload=PrimeTime__1_B")
-close_tx(socket)
-socket.write( "data=this is a log entry for <<NAME>>__1_B agent=1__1_Blogtype=apache__1_B" )
-socket.write("level=0__1_Btime=1248931890__1_Bpayload=PrimeTime__1_B ")
-close_tx(socket)
-socket.write( "data=this is a log entry for <<NAME>>__1_Bagent=0__1_Blogtype=apache__1_B" )
-socket.write("level=0__1_Btime=1248931698__1_Bpayload=Builder__1_B ")
-close_tx(socket)
\ No newline at end of file
diff --git a/src/server/config/initializers/extended_modules.rb b/src/server/config/initializers/extended_modules.rb
index bd8bf65..621f733 100644
--- a/src/server/config/initializers/extended_modules.rb
+++ b/src/server/config/initializers/extended_modules.rb
@@ -1,4 +1,16 @@
#This initializer is used to pull in modules and extentions in other directories. (The include functions in envrionment.rb is crap)
require 'digest/md5'
-require 'lib/modules/collection_server'
-require 'lib/modules/command_server'
\ No newline at end of file
+require RAILS_ROOT + '/lib/modules/collection_server.rb'
+require RAILS_ROOT + '/lib/modules/command_server.rb'
+
+#Mixin for the string class to add a validity check for log events based on the checksum appended to buffered received data
+class String
+ def valid?
+ part = self.split('__1_CC')
+ if Digest::MD5.hexdigest(part[0]) == part[1]
+ return true
+ else
+ return false
+ end
+ end
+end
\ No newline at end of file
diff --git a/src/server/lib/daemons/commandserver.rb b/src/server/lib/daemons/commandserver.rb
index 1149e0a..d811055 100755
--- a/src/server/lib/daemons/commandserver.rb
+++ b/src/server/lib/daemons/commandserver.rb
@@ -1,21 +1,20 @@
#!/usr/bin/env ruby
-# TODO: Change this stuff
ENV["RAILS_ENV"] ||= "production"
require 'yaml'
config = YAML::load(File.open(File.dirname(__FILE__) + "/../../config/collectors.yml"))['commandlistener']
port = config['port']
bindip = config['listenip']
require File.dirname(__FILE__) + "/../../config/environment.rb"
ActiveRecord::Base.logger.info "Starting command server :: listening on #{bindip}:#{port}"
Signal.trap("TERM") do
ActiveRecord::Base.logger.info "-- Stopping command server"
EventMachine::stop_event_loop
end
EventMachine::run {
EventMachine::start_server bindip, port, CommandServer
}
\ No newline at end of file
diff --git a/src/server/lib/daemons/tcpcollector.rb b/src/server/lib/daemons/tcpcollector.rb
index 81982a3..a46ff11 100755
--- a/src/server/lib/daemons/tcpcollector.rb
+++ b/src/server/lib/daemons/tcpcollector.rb
@@ -1,21 +1,20 @@
#!/usr/bin/env ruby
-# TODO: Change this stuff
ENV["RAILS_ENV"] ||= "production"
require 'yaml'
config = YAML::load(File.open(File.dirname(__FILE__) + "/../../config/collectors.yml"))['tcpcollector']
port = config['port']
bindip = config['listenip']
require File.dirname(__FILE__) + "/../../config/environment.rb"
ActiveRecord::Base.logger.info "Starting TCP log collector :: listening on #{bindip}:#{port}"
Signal.trap("TERM") do
ActiveRecord::Base.logger.info "-- Stopping TCP collector"
EventMachine::stop_event_loop
end
EventMachine::run {
EventMachine::start_server bindip, port, CollectionServer
}
\ No newline at end of file
diff --git a/src/server/lib/daemons/udpcollector.rb b/src/server/lib/daemons/udpcollector.rb
index 23c2076..476a350 100755
--- a/src/server/lib/daemons/udpcollector.rb
+++ b/src/server/lib/daemons/udpcollector.rb
@@ -1,21 +1,20 @@
#!/usr/bin/env ruby
-# TODO: Change this stuff
ENV["RAILS_ENV"] ||= "production"
require 'yaml'
config = YAML::load(File.open(File.dirname(__FILE__) + "/../../config/collectors.yml"))['udpcollector']
port = config['port']
bindip = config['listenip']
require File.dirname(__FILE__) + "/../../config/environment.rb"
ActiveRecord::Base.logger.info "Starting UDP log collector :: listening on #{bindip}:#{port}"
Signal.trap("TERM") do
ActiveRecord::Base.logger.info "-- Stopping UDP collector"
EventMachine::stop_event_loop
end
EventMachine::run {
EventMachine::open_datagram_socket bindip, port, CollectionServer
}
\ No newline at end of file
diff --git a/src/server/lib/modules/collection_server.rb b/src/server/lib/modules/collection_server.rb
index 888efa3..78a96b8 100644
--- a/src/server/lib/modules/collection_server.rb
+++ b/src/server/lib/modules/collection_server.rb
@@ -1,47 +1,72 @@
-
module CollectionServer
- #TODO: Checksum check should be wrapped in to an exception and then and handled that way
-
- def post_init
+ #TODO: Checksum check should be wrapped in to an exception and then and handled that way in receive_data
+
+ #Set buffer delimiters
+ @@break = '__1_BB'
+ @@value = '__1_VV'
+ @@finish = '__1_EE'
+
+ def check_key(agent, key)
+ if agent.key != key
+ return false
+ else
+ return true
+ end
+ end
+
+ #Write a log entry
+ def log_entry(line)
+ raw = line.split(@@break)
+ map = Hash.new
+ raw.each do |keys|
+ parts = keys.split(@@value)
+ map.store(parts[0],parts[1])
+ end
+ static = Logtype.find(map['logtype_id']).staticentries.new
+ static.data = map['data']
+ static.save
+ static = Staticentry.find_by_id(Digest::MD5.hexdigest(map['data']))
+ event = static.events.new
+ event.time = map['time']
+ event.loglevel = map['loglevel']
+ event.payload = map['payload']
+ event.agent_id = map['agent_id']
+ if check_key(Agent.find(map['agent_id']), map['key'])
+ event.save
+ else
+ ActiveRecord::Base.logger.debug "Event dropped -- invalid agent key sent"
+ end
port, ip = Socket.unpack_sockaddr_in(get_peername)
- ActiveRecord::Base.logger.info "-- Collector connection established from #{ip}"
- end
-
- def receive_data(data)
- (@buffer ||= BufferedTokenizer.new(delimiter = "__1_EE")).extract(data).each do |line|
- checkintegrity = line.split('__1_CC')
- if checkintegrity[1] == Digest::MD5.hexdigest(checkintegrity[0])
- raw = line.split('__1_BB')
- map = Hash.new
- raw.each do |keys|
- parts = keys.split('__1_VV')
- map.store(parts[0],parts[1])
- end
- static = Logtype.find_by_name(map['logtype']).staticentries.new
- static.data = map['data']
- static.save
- static = Staticentry.find_by_id(Digest::MD5.hexdigest(map['data']))
- event = static.events.new
- event.time = map['time']
- event.loglevel = map['level']
- event.payload = map['payload']
- event.save
- puts "done #{Time.now.to_f - start}"
- port, ip = Socket.unpack_sockaddr_in(get_peername)
- puts "from host #{ip}"
- else
- port, ip = Socket.unpack_sockaddr_in(get_peername)
- ActiveRecord::Base.logger.error "Dropped log entry from #{ip} - checksum invalid"
- end
- end
- end
-
-
- def unbind
- ActiveRecord::Base.logger.info "-- Collector connection closed by a peer"
- end
+ host = Socket.getaddrinfo(ip, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME)[0][2]
+ ActiveRecord::Base.logger.debug "New event logged from #{host} \n -- Log data: #{line}"
+ end
+
+ #Do this when a connection is initialized
+ def post_init
+ port, ip = Socket.unpack_sockaddr_in(get_peername)
+ host = Socket.getaddrinfo(ip, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME)[0][2]
+ ActiveRecord::Base.logger.info "-- Collector connection established from #{host}"
+ end
+
+ #Do this when data is received
+ def receive_data(data)
+ (@buffer ||= BufferedTokenizer.new(delimiter = "__1_EE")).extract(data).each do |line|
+ if line.valid?
+ log_entry(line)
+ else
+ port, ip = Socket.unpack_sockaddr_in(get_peername)
+ host = Socket.getaddrinfo(ip, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME)[0][2]
+ ActiveRecord::Base.logger.error "Dropped log entry from #{host} - checksum invalid"
+ end
+ end
+ end
+
+ #Do this when a connection is closed by a peer
+ def unbind
+ ActiveRecord::Base.logger.info "-- Collector connection closed by a peer"
+ end
end
\ No newline at end of file
|
parabuzzle/cistern
|
e43e13b766e07f9e460fcb1e8f9d45b3913f27f5
|
didn't like the eventmachine modules being loaded in the initializers directory. I moved the modules to lib/modules and use an initializers file to init the modules... cleaner is better
|
diff --git a/src/server/config/initializers/collector.rb b/src/server/config/initializers/collector.rb
deleted file mode 100644
index 45bd48f..0000000
--- a/src/server/config/initializers/collector.rb
+++ /dev/null
@@ -1,56 +0,0 @@
-require 'digest/md5'
-module CollectionServer
-
- def post_init
- port, ip = Socket.unpack_sockaddr_in(get_peername)
- ActiveRecord::Base.logger.info "-- Collector connection established from #{ip}"
- end
-
- def receive_data(data)
- (@buffer ||= BufferedTokenizer.new(delimiter = "__1_EE")).extract(data).each do |line|
- start = Time.now.to_f
- raw = line.split('__1_B')
- map = Hash.new
- raw.each do |keys|
- parts = keys.split('=')
- map.store(parts[0],parts[1])
- end
- static = Logtype.find_by_name(map['logtype']).staticentries.new
- static.data = map['data']
- static.save
- static = Staticentry.find_by_id(Digest::MD5.hexdigest(map['data']))
- event = static.events.new
- event.time = map['time']
- event.loglevel = map['level']
- event.payload = map['payload']
- event.save
- puts "done #{Time.now.to_f - start}"
- port, ip = Socket.unpack_sockaddr_in(get_peername)
- puts "from host #{ip}"
-
- end
- end
-
-
- def unbind
- ActiveRecord::Base.logger.info "-- Collector connection closed by a peer"
- end
-end
-
-module CommandServer
- def post_init
- port, ip = Socket.unpack_sockaddr_in(get_peername)
- ActiveRecord::Base.logger.info "-- Command connection established from #{ip}"
- end
-
- def receive_data data
- # Do something with the log data
- ActiveRecord::Base.logger.info "#{data}"
- end
-
- def unbind
- ActiveRecord::Base.logger.info "-- Command connection closed by a peer"
- end
-end
-
-
\ No newline at end of file
diff --git a/src/server/config/initializers/extended_modules.rb b/src/server/config/initializers/extended_modules.rb
new file mode 100644
index 0000000..bd8bf65
--- /dev/null
+++ b/src/server/config/initializers/extended_modules.rb
@@ -0,0 +1,4 @@
+#This initializer is used to pull in modules and extentions in other directories. (The include functions in envrionment.rb is crap)
+require 'digest/md5'
+require 'lib/modules/collection_server'
+require 'lib/modules/command_server'
\ No newline at end of file
diff --git a/src/server/lib/modules/collection_server.rb b/src/server/lib/modules/collection_server.rb
new file mode 100644
index 0000000..888efa3
--- /dev/null
+++ b/src/server/lib/modules/collection_server.rb
@@ -0,0 +1,47 @@
+
+module CollectionServer
+
+ #TODO: Checksum check should be wrapped in to an exception and then and handled that way
+
+ def post_init
+ port, ip = Socket.unpack_sockaddr_in(get_peername)
+ ActiveRecord::Base.logger.info "-- Collector connection established from #{ip}"
+ end
+
+ def receive_data(data)
+ (@buffer ||= BufferedTokenizer.new(delimiter = "__1_EE")).extract(data).each do |line|
+ checkintegrity = line.split('__1_CC')
+ if checkintegrity[1] == Digest::MD5.hexdigest(checkintegrity[0])
+ raw = line.split('__1_BB')
+ map = Hash.new
+ raw.each do |keys|
+ parts = keys.split('__1_VV')
+ map.store(parts[0],parts[1])
+ end
+ static = Logtype.find_by_name(map['logtype']).staticentries.new
+ static.data = map['data']
+ static.save
+ static = Staticentry.find_by_id(Digest::MD5.hexdigest(map['data']))
+ event = static.events.new
+ event.time = map['time']
+ event.loglevel = map['level']
+ event.payload = map['payload']
+ event.save
+ puts "done #{Time.now.to_f - start}"
+ port, ip = Socket.unpack_sockaddr_in(get_peername)
+ puts "from host #{ip}"
+ else
+ port, ip = Socket.unpack_sockaddr_in(get_peername)
+ ActiveRecord::Base.logger.error "Dropped log entry from #{ip} - checksum invalid"
+ end
+ end
+ end
+
+
+ def unbind
+ ActiveRecord::Base.logger.info "-- Collector connection closed by a peer"
+ end
+
+end
+
+
\ No newline at end of file
diff --git a/src/server/lib/modules/command_server.rb b/src/server/lib/modules/command_server.rb
new file mode 100644
index 0000000..c36bc7c
--- /dev/null
+++ b/src/server/lib/modules/command_server.rb
@@ -0,0 +1,15 @@
+module CommandServer
+ def post_init
+ port, ip = Socket.unpack_sockaddr_in(get_peername)
+ ActiveRecord::Base.logger.info "-- Command connection established from #{ip}"
+ end
+
+ def receive_data data
+ # Do something with the log data
+ ActiveRecord::Base.logger.info "#{data}"
+ end
+
+ def unbind
+ ActiveRecord::Base.logger.info "-- Command connection closed by a peer"
+ end
+end
\ No newline at end of file
|
parabuzzle/cistern
|
a4d21ae411153810e148e74769561903775dfca3
|
Added a bunch of unit tests and validations
|
diff --git a/src/server/app/models/agent.rb b/src/server/app/models/agent.rb
index e4bc055..ea89f0c 100644
--- a/src/server/app/models/agent.rb
+++ b/src/server/app/models/agent.rb
@@ -1,4 +1,11 @@
class Agent < ActiveRecord::Base
+
has_and_belongs_to_many :logtypes, :join_table => :agents_logtypes
has_many :events
+
+ #Validations
+ validates_presence_of :hostname, :port
+ validates_format_of :hostname, :with => /([A-Z0-9-]+\.)+[A-Z]{2,4}$/i
+
+
end
diff --git a/src/server/app/models/event.rb b/src/server/app/models/event.rb
index 9d26980..d6e5ba8 100644
--- a/src/server/app/models/event.rb
+++ b/src/server/app/models/event.rb
@@ -1,4 +1,8 @@
class Event < ActiveRecord::Base
belongs_to :staticentry
belongs_to :agent
+
+ #Validations
+ validates_presence_of :agent_id, :loglevel, :time
+
end
diff --git a/src/server/app/models/logtype.rb b/src/server/app/models/logtype.rb
index 4e22999..4ae4493 100644
--- a/src/server/app/models/logtype.rb
+++ b/src/server/app/models/logtype.rb
@@ -1,11 +1,14 @@
class Logtype < ActiveRecord::Base
has_and_belongs_to_many :agents
has_many :staticentries
has_many :events, :through => :staticentries
+
+ #Validations
+ validates_presence_of :name
def add(agent)
ActiveRecord::Base.connection.execute("insert into agents_logtypes (logtype_id,agent_id)values('#{self.id}','#{agent.id}')")
return agent
end
end
diff --git a/src/server/app/models/staticentry.rb b/src/server/app/models/staticentry.rb
index c8b6e2a..f449e6f 100644
--- a/src/server/app/models/staticentry.rb
+++ b/src/server/app/models/staticentry.rb
@@ -1,13 +1,14 @@
class Staticentry < ActiveRecord::Base
has_many :events
belongs_to :logtype
+ #TODO: Make the id include the logtype to prevent hash collision cross logtypes
def before_create
if Staticentry.find_by_id(Digest::MD5.hexdigest(self.data)) != nil
return false
end
self.id = Digest::MD5.hexdigest(self.data)
end
end
diff --git a/src/server/config/database.yml b/src/server/config/database.yml
index bbd3ae9..427ce83 100644
--- a/src/server/config/database.yml
+++ b/src/server/config/database.yml
@@ -1,22 +1,24 @@
# SQLite version 3.x
# gem install sqlite3-ruby (not necessary on OS X Leopard)
development:
adapter: sqlite3
database: db/development.sqlite3
pool: 5
timeout: 5000
# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
- adapter: sqlite3
- database: db/test.sqlite3
+ adapter: mysql
+ database: cistern
pool: 5
+ user: root
+ password:
timeout: 5000
production:
adapter: sqlite3
database: db/development.sqlite3
pool: 5
timeout: 5000
diff --git a/src/server/db/migrate/20090721233433_create_events.rb b/src/server/db/migrate/20090721233433_create_events.rb
index 20cfe74..efeec71 100644
--- a/src/server/db/migrate/20090721233433_create_events.rb
+++ b/src/server/db/migrate/20090721233433_create_events.rb
@@ -1,17 +1,16 @@
class CreateEvents < ActiveRecord::Migration
def self.up
create_table :events do |t|
t.column :payload, :string
t.column :staticentry_id, :string
t.column :agent_id, :int
- t.column :type_id, :int
t.column :loglevel, :int
t.column :time, :int
t.timestamps
end
end
def self.down
drop_table :events
end
end
diff --git a/src/server/db/migrate/20090730025541_create_staticentries.rb b/src/server/db/migrate/20090730025541_create_staticentries.rb
index 61d4b02..224b745 100644
--- a/src/server/db/migrate/20090730025541_create_staticentries.rb
+++ b/src/server/db/migrate/20090730025541_create_staticentries.rb
@@ -1,21 +1,20 @@
class CreateStaticentries < ActiveRecord::Migration
def self.up
create_table :staticentries, :id => false do |t|
t.column :id, :string, :null => false
#t.column :hash_key, :string, :null => false
t.column :logtype_id, :int
t.column :data, :text
- t.column :agent_id, :int
t.timestamps
end
#add_index :staticentries, :hash_key
#add_index :staticentries, :agent_id
#unless ActiveRecord::Base.configurations[ENV['RAILS_ENV']]['adapter'] != 'mysql'
# execute "ALTER TABLE staticentries ADD PRIMARY KEY (id)"
#end
end
def self.down
drop_table :staticentries
end
end
diff --git a/src/server/test/fixtures/agents.yml b/src/server/test/fixtures/agents.yml
index 3fe96e0..3980eb1 100644
--- a/src/server/test/fixtures/agents.yml
+++ b/src/server/test/fixtures/agents.yml
@@ -1,18 +1,20 @@
# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
# one:
# column: value
#
# two:
# column: value
-valid:
- name: validagent
+agent:
+ id: 1
+ name: agent
hostname: agent1.corp.cistern.com
port: 9845
key: unused
-invalidhostname:
- name: invalidagent
- hostname: agent1.corp
- port: 9845
- key: unused
+#invalidhostname:
+# id: 2
+# name: invalidagent
+# hostname: agent1.corp
+# port: 9845
+# key: unused
diff --git a/src/server/test/fixtures/agents_logtypes.yml b/src/server/test/fixtures/agents_logtypes.yml
new file mode 100644
index 0000000..216258c
--- /dev/null
+++ b/src/server/test/fixtures/agents_logtypes.yml
@@ -0,0 +1,4 @@
+
+agent1:
+ logtype_id: 1
+ agent_id: 1
\ No newline at end of file
diff --git a/src/server/test/fixtures/events.yml b/src/server/test/fixtures/events.yml
index 01325ef..aa8cf76 100644
--- a/src/server/test/fixtures/events.yml
+++ b/src/server/test/fixtures/events.yml
@@ -1,39 +1,38 @@
# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
# one:
# column: value
#
# two:
# column: value
-validevent:
+event1:
payload: agent1
- staticentry_id:
+ staticentry_id: 85d229332bf72d4539372498264300d6
agent_id: 1
- type_id:
loglevel: 0
time: 1249062105.06911
-invalidmissingagent:
- payload: agent1
- staticentry_id:
- agent_id:
- type_id:
- loglevel: 0
- time: 1249062105.06911
-
-invalidmissingloglevel:
- payload: agent1
- staticentry_id:
- agent_id: 1
- type_id:
- loglevel:
- time: 1249062105.06911
-
-invalidmissingtime:
- payload: agent1
- staticentry_id:
- agent_id: 1
- type_id:
- loglevel: 0
- time:
\ No newline at end of file
+#invalidmissingagent:
+# payload: agent1
+# staticentry_id:
+# agent_id:
+# type_id:
+# loglevel: 0
+# time: 1249062105.06911
+#
+#invalidmissingloglevel:
+# payload: agent1
+# staticentry_id:
+# agent_id: 1
+# type_id:
+# loglevel:
+# time: 1249062105.06911
+#
+#invalidmissingtime:
+# payload: agent1
+# staticentry_id:
+# agent_id: 1
+# type_id:
+# loglevel: 0
+# time:
\ No newline at end of file
diff --git a/src/server/test/fixtures/logtypes.yml b/src/server/test/fixtures/logtypes.yml
index 5bf0293..b834624 100644
--- a/src/server/test/fixtures/logtypes.yml
+++ b/src/server/test/fixtures/logtypes.yml
@@ -1,7 +1,11 @@
# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
# one:
# column: value
#
# two:
# column: value
+
+apache:
+ id: 1
+ name: apache
diff --git a/src/server/test/fixtures/staticentries.yml b/src/server/test/fixtures/staticentries.yml
index 5bf0293..1d5af73 100644
--- a/src/server/test/fixtures/staticentries.yml
+++ b/src/server/test/fixtures/staticentries.yml
@@ -1,7 +1,12 @@
# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
# one:
# column: value
#
# two:
# column: value
+
+apachetrace:
+ id: 85d229332bf72d4539372498264300d6
+ logtype_id: 1
+ data: static data
\ No newline at end of file
diff --git a/src/server/test/unit/agent_test.rb b/src/server/test/unit/agent_test.rb
index 0e33310..9e98b60 100644
--- a/src/server/test/unit/agent_test.rb
+++ b/src/server/test/unit/agent_test.rb
@@ -1,8 +1,36 @@
require 'test_helper'
class AgentTest < ActiveSupport::TestCase
# Replace this with your real tests.
test "the truth" do
assert true
end
+
+ test "valid agent creation" do
+ a = Agent.new
+ a.name = "valid"
+ a.hostname = "agent2.corp.cistern.com"
+ a.port = "9845"
+ a.key = "unused"
+ assert a.save
+ end
+
+ test "invalid agent creation - bad hostname" do
+ a = Agent.new
+ a.name = "valid"
+ a.hostname = "agent2.corp.cistern"
+ a.port = "9845"
+ a.key = "unused"
+ assert !a.save
+ end
+
+ test "invalid agent creation - missing port" do
+ a = Agent.new
+ a.name = "valid"
+ a.hostname = "agent3.corp.cistern.com"
+ a.port = ""
+ a.key = "unused"
+ assert !a.save
+ end
+
end
diff --git a/src/server/test/unit/event_test.rb b/src/server/test/unit/event_test.rb
index c2b9b78..cc9641a 100644
--- a/src/server/test/unit/event_test.rb
+++ b/src/server/test/unit/event_test.rb
@@ -1,8 +1,49 @@
require 'test_helper'
class EventTest < ActiveSupport::TestCase
# Replace this with your real tests.
test "the truth" do
assert true
end
+
+ test "new event" do
+ e = Event.new
+ e.payload = "agent3"
+ e.staticentry_id = "85d229332bf72d4539372498264300d6"
+ e.agent_id = 1
+ e.loglevel = 0
+ e.time = 1249062105.06911
+ assert e.save
+ end
+
+ test "invalid new event - missing agent_id" do
+ e = Event.new
+ e.payload = "agent3"
+ e.staticentry_id = "85d229332bf72d4539372498264300d6"
+ e.agent_id = nil
+ e.loglevel = 0
+ e.time = 1249062105.06911
+ assert !e.save
+ end
+
+ test "invalid new event - missing loglevel" do
+ e = Event.new
+ e.payload = "agent3"
+ e.staticentry_id = "85d229332bf72d4539372498264300d6"
+ e.agent_id = 1
+ e.loglevel = nil
+ e.time = 1249062105.06911
+ assert !e.save
+ end
+
+ test "invalid new event - missing time" do
+ e = Event.new
+ e.payload = "agent3"
+ e.staticentry_id = "85d229332bf72d4539372498264300d6"
+ e.agent_id = 1
+ e.loglevel = 0
+ e.time = nil
+ assert !e.save
+ end
+
end
diff --git a/src/server/test/unit/logtype_test.rb b/src/server/test/unit/logtype_test.rb
index b9c3e77..032163f 100644
--- a/src/server/test/unit/logtype_test.rb
+++ b/src/server/test/unit/logtype_test.rb
@@ -1,8 +1,33 @@
require 'test_helper'
class LogtypeTest < ActiveSupport::TestCase
# Replace this with your real tests.
test "the truth" do
assert true
end
+
+ test "new logtype" do
+ l = Logtype.new
+ l.name = "jboss"
+ assert l.save
+ end
+
+ test "add logtype to an agent" do
+ a = Agent.first
+ l = Logtype.first
+ l.add(a)
+ a.reload
+ c = a.logtypes.empty?
+ if c != true
+ assert true
+ else
+ assert false
+ end
+ end
+
+ test "missing name" do
+ l = Logtype.new
+ assert !l.save
+ end
+
end
diff --git a/src/server/test/unit/staticentry_test.rb b/src/server/test/unit/staticentry_test.rb
index 4ccfdc3..4d5b6d2 100644
--- a/src/server/test/unit/staticentry_test.rb
+++ b/src/server/test/unit/staticentry_test.rb
@@ -1,8 +1,33 @@
require 'test_helper'
+require 'digest/md5'
class StaticentryTest < ActiveSupport::TestCase
# Replace this with your real tests.
test "the truth" do
assert true
end
+
+ test "new static entry" do
+ s = Staticentry.new
+ s.logtype_id = 1
+ s.data = "new entry"
+ assert s.save
+ end
+
+ #This test is broken... probably lack of understanding of fixtures... :(
+ #test "duplicate key handling" do
+ # s = Staticentry.new
+ # s.id = "264e11eb5153fe6bff62a68a2e51d48c"
+ # s.logtype_id = 1
+ # s.data = "newest entry"
+ # s.save
+ # d = Staticentry.new
+ # d.id = "264e11eb5153fe6bff62a68a2e51d48c"
+ # d.logtype_id = 1
+ # d.data = "newest entry"
+ # d.save
+ # f = Staticentry.find("264e11eb5153fe6bff62a68a2e51d48c").count
+ # if f == 1 then assert true end
+ #end
+
end
|
parabuzzle/cistern
|
6e0e739456fb9b8f92d54029ca2c6660b05531d5
|
incomplete tests. reference checkin.
|
diff --git a/src/server/test/fixtures/agents.yml b/src/server/test/fixtures/agents.yml
index 5bf0293..3fe96e0 100644
--- a/src/server/test/fixtures/agents.yml
+++ b/src/server/test/fixtures/agents.yml
@@ -1,7 +1,18 @@
# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
# one:
# column: value
#
# two:
# column: value
+valid:
+ name: validagent
+ hostname: agent1.corp.cistern.com
+ port: 9845
+ key: unused
+
+invalidhostname:
+ name: invalidagent
+ hostname: agent1.corp
+ port: 9845
+ key: unused
diff --git a/src/server/test/fixtures/events.yml b/src/server/test/fixtures/events.yml
index 5bf0293..01325ef 100644
--- a/src/server/test/fixtures/events.yml
+++ b/src/server/test/fixtures/events.yml
@@ -1,7 +1,39 @@
# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
# one:
# column: value
#
# two:
# column: value
+
+validevent:
+ payload: agent1
+ staticentry_id:
+ agent_id: 1
+ type_id:
+ loglevel: 0
+ time: 1249062105.06911
+
+invalidmissingagent:
+ payload: agent1
+ staticentry_id:
+ agent_id:
+ type_id:
+ loglevel: 0
+ time: 1249062105.06911
+
+invalidmissingloglevel:
+ payload: agent1
+ staticentry_id:
+ agent_id: 1
+ type_id:
+ loglevel:
+ time: 1249062105.06911
+
+invalidmissingtime:
+ payload: agent1
+ staticentry_id:
+ agent_id: 1
+ type_id:
+ loglevel: 0
+ time:
\ No newline at end of file
|
parabuzzle/cistern
|
84361fe57b2d9b4bc1460b3a8d6c5b9a3fa0b306
|
Added the peer ip to log entries... will be useful for future security optimizations
|
diff --git a/src/agent/logsender.rb b/src/agent/logsender.rb
index 2ea9f8d..e1dd34f 100644
--- a/src/agent/logsender.rb
+++ b/src/agent/logsender.rb
@@ -1,27 +1,25 @@
require 'socket'
require 'yaml'
include Socket::Constants
def close_tx(socket)
socket.write("__1_EE")
end
socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
sockaddr = Socket.pack_sockaddr_in( 9845, '127.0.0.1' )
socket.connect( sockaddr )
#Write staticentry
-loop do
+
socket.write( "data=this is a log entry for <<NAME>>__1_B agent=1__1_Blogtype=apache__1_B" )
socket.write("level=0__1_Btime=1248931696__1_Bpayload=PrimeTime__1_B")
close_tx(socket)
socket.write( "data=this is a log entry for <<NAME>>__1_B agent=1__1_Blogtype=apache__1_B" )
socket.write("level=0__1_Btime=1248931890__1_Bpayload=PrimeTime__1_B ")
close_tx(socket)
socket.write( "data=this is a log entry for <<NAME>>__1_Bagent=0__1_Blogtype=apache__1_B" )
socket.write("level=0__1_Btime=1248931698__1_Bpayload=Builder__1_B ")
-close_tx(socket)
-
-end
\ No newline at end of file
+close_tx(socket)
\ No newline at end of file
diff --git a/src/server/config/database.yml b/src/server/config/database.yml
index 7a21f42..bbd3ae9 100644
--- a/src/server/config/database.yml
+++ b/src/server/config/database.yml
@@ -1,26 +1,22 @@
# SQLite version 3.x
# gem install sqlite3-ruby (not necessary on OS X Leopard)
development:
- adapter: mysql
- database: cistern
- pool: 50
+ adapter: sqlite3
+ database: db/development.sqlite3
+ pool: 5
timeout: 5000
- username: root
- password:
# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
adapter: sqlite3
database: db/test.sqlite3
pool: 5
timeout: 5000
production:
- adapter: mysql
- database: cistern
- pool: 50
+ adapter: sqlite3
+ database: db/development.sqlite3
+ pool: 5
timeout: 5000
- username: root
- password:
diff --git a/src/server/config/initializers/collector.rb b/src/server/config/initializers/collector.rb
index 9cbc938..45bd48f 100644
--- a/src/server/config/initializers/collector.rb
+++ b/src/server/config/initializers/collector.rb
@@ -1,52 +1,56 @@
require 'digest/md5'
module CollectionServer
def post_init
- ActiveRecord::Base.logger.info "-- someone connected to the collector"
+ port, ip = Socket.unpack_sockaddr_in(get_peername)
+ ActiveRecord::Base.logger.info "-- Collector connection established from #{ip}"
end
def receive_data(data)
- n = 1
(@buffer ||= BufferedTokenizer.new(delimiter = "__1_EE")).extract(data).each do |line|
- start = Time.now.to_i
+ start = Time.now.to_f
raw = line.split('__1_B')
map = Hash.new
raw.each do |keys|
parts = keys.split('=')
map.store(parts[0],parts[1])
end
static = Logtype.find_by_name(map['logtype']).staticentries.new
static.data = map['data']
static.save
static = Staticentry.find_by_id(Digest::MD5.hexdigest(map['data']))
event = static.events.new
event.time = map['time']
event.loglevel = map['level']
event.payload = map['payload']
event.save
- puts "done #{Time.now.to_i - start} #{n + 1}"
+ puts "done #{Time.now.to_f - start}"
+ port, ip = Socket.unpack_sockaddr_in(get_peername)
+ puts "from host #{ip}"
+
end
end
def unbind
- ActiveRecord::Base.logger.info "-- someone disconnected from the collector"
+ ActiveRecord::Base.logger.info "-- Collector connection closed by a peer"
end
end
module CommandServer
def post_init
- ActiveRecord::Base.logger.info "-- someone connected to the command server"
+ port, ip = Socket.unpack_sockaddr_in(get_peername)
+ ActiveRecord::Base.logger.info "-- Command connection established from #{ip}"
end
def receive_data data
# Do something with the log data
ActiveRecord::Base.logger.info "#{data}"
end
def unbind
- ActiveRecord::Base.logger.info "-- someone disconnected from the command server"
+ ActiveRecord::Base.logger.info "-- Command connection closed by a peer"
end
end
\ No newline at end of file
|
parabuzzle/cistern
|
bbeb86b4e1b02d533a48cb9950acb2aa34d22b2f
|
Changed the models a little so that you can find events based on logtype or agent or the combination. Translation: you can find all events from all logtypes for a specific agent or you can find all events from all agents for a specific logtype or you can find all events for a specific logtype and specific agent. neato
|
diff --git a/src/server/app/models/agent.rb b/src/server/app/models/agent.rb
index 8914e9c..e4bc055 100644
--- a/src/server/app/models/agent.rb
+++ b/src/server/app/models/agent.rb
@@ -1,3 +1,4 @@
class Agent < ActiveRecord::Base
- has_many :logtypes
+ has_and_belongs_to_many :logtypes, :join_table => :agents_logtypes
+ has_many :events
end
diff --git a/src/server/app/models/event.rb b/src/server/app/models/event.rb
index d387e40..9d26980 100644
--- a/src/server/app/models/event.rb
+++ b/src/server/app/models/event.rb
@@ -1,3 +1,4 @@
class Event < ActiveRecord::Base
belongs_to :staticentry
+ belongs_to :agent
end
diff --git a/src/server/app/models/logtype.rb b/src/server/app/models/logtype.rb
index fe561e0..4e22999 100644
--- a/src/server/app/models/logtype.rb
+++ b/src/server/app/models/logtype.rb
@@ -1,4 +1,11 @@
class Logtype < ActiveRecord::Base
+ has_and_belongs_to_many :agents
has_many :staticentries
has_many :events, :through => :staticentries
+
+
+ def add(agent)
+ ActiveRecord::Base.connection.execute("insert into agents_logtypes (logtype_id,agent_id)values('#{self.id}','#{agent.id}')")
+ return agent
+ end
end
diff --git a/src/server/db/migrate/20090721233433_create_events.rb b/src/server/db/migrate/20090721233433_create_events.rb
index c0913ed..20cfe74 100644
--- a/src/server/db/migrate/20090721233433_create_events.rb
+++ b/src/server/db/migrate/20090721233433_create_events.rb
@@ -1,16 +1,17 @@
class CreateEvents < ActiveRecord::Migration
def self.up
create_table :events do |t|
t.column :payload, :string
t.column :staticentry_id, :string
+ t.column :agent_id, :int
t.column :type_id, :int
t.column :loglevel, :int
t.column :time, :int
t.timestamps
end
end
def self.down
drop_table :events
end
end
diff --git a/src/server/db/migrate/20090730025618_create_logtypes.rb b/src/server/db/migrate/20090730025618_create_logtypes.rb
index 39e5ddd..5f92c15 100644
--- a/src/server/db/migrate/20090730025618_create_logtypes.rb
+++ b/src/server/db/migrate/20090730025618_create_logtypes.rb
@@ -1,13 +1,12 @@
class CreateLogtypes < ActiveRecord::Migration
def self.up
create_table :logtypes do |t|
t.column :name, :string
- t.column :agent_id, :int
t.timestamps
end
end
def self.down
drop_table :logtypes
end
end
diff --git a/src/server/db/migrate/20090730154024_create_agents_logtype_map.rb b/src/server/db/migrate/20090730154024_create_agents_logtype_map.rb
new file mode 100644
index 0000000..5194900
--- /dev/null
+++ b/src/server/db/migrate/20090730154024_create_agents_logtype_map.rb
@@ -0,0 +1,13 @@
+class CreateAgentsLogtypeMap < ActiveRecord::Migration
+ def self.up
+ create_table :agents_logtypes do |t|
+ t.column :logtype_id, :int
+ t.column :agent_id, :int
+ t.timestamps
+ end
+ end
+
+ def self.down
+ drop_table :events
+ end
+end
diff --git a/src/server/db/schema.rb b/src/server/db/schema.rb
index d3234f4..368312d 100644
--- a/src/server/db/schema.rb
+++ b/src/server/db/schema.rb
@@ -1,48 +1,55 @@
# This file is auto-generated from the current state of the database. Instead of editing this file,
# please use the migrations feature of Active Record to incrementally modify your database, and
# then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your database schema. If you need
# to create the application database on another system, you should be using db:schema:load, not running
# all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended to check this file into your version control system.
-ActiveRecord::Schema.define(:version => 20090730025618) do
+ActiveRecord::Schema.define(:version => 20090730154024) do
create_table "agents", :force => true do |t|
t.string "name"
t.string "hostname"
t.string "port"
t.string "key"
t.datetime "created_at"
t.datetime "updated_at"
end
+ create_table "agents_logtypes", :force => true do |t|
+ t.integer "logtype_id"
+ t.integer "agent_id"
+ t.datetime "created_at"
+ t.datetime "updated_at"
+ end
+
create_table "events", :force => true do |t|
t.string "payload"
t.string "staticentry_id"
+ t.integer "agent_id"
t.integer "type_id"
t.integer "loglevel"
t.integer "time"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "logtypes", :force => true do |t|
t.string "name"
- t.integer "agent_id"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "staticentries", :force => true do |t|
t.integer "logtype_id"
t.text "data"
t.integer "agent_id"
t.datetime "created_at"
t.datetime "updated_at"
end
end
|
parabuzzle/cistern
|
ac18880974d0aec15613807fd9b24a2faf17188b
|
Proof of concept on the log collector and the database schema. Need to make better delimiters and better concurrent handling
|
diff --git a/src/server/app/models/logtype.rb b/src/server/app/models/logtype.rb
index b64f5a6..fe561e0 100644
--- a/src/server/app/models/logtype.rb
+++ b/src/server/app/models/logtype.rb
@@ -1,4 +1,4 @@
class Logtype < ActiveRecord::Base
has_many :staticentries
-
+ has_many :events, :through => :staticentries
end
diff --git a/src/server/config/database.yml b/src/server/config/database.yml
index 2c35ea4..7a21f42 100644
--- a/src/server/config/database.yml
+++ b/src/server/config/database.yml
@@ -1,26 +1,26 @@
# SQLite version 3.x
# gem install sqlite3-ruby (not necessary on OS X Leopard)
development:
adapter: mysql
database: cistern
- pool: 5
+ pool: 50
timeout: 5000
username: root
password:
# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
adapter: sqlite3
database: db/test.sqlite3
pool: 5
timeout: 5000
production:
adapter: mysql
database: cistern
- pool: 5
+ pool: 50
timeout: 5000
username: root
password:
diff --git a/src/server/config/initializers/collector.rb b/src/server/config/initializers/collector.rb
index d6ef0fc..9cbc938 100644
--- a/src/server/config/initializers/collector.rb
+++ b/src/server/config/initializers/collector.rb
@@ -1,36 +1,52 @@
require 'digest/md5'
module CollectionServer
-
+
def post_init
ActiveRecord::Base.logger.info "-- someone connected to the collector"
end
def receive_data(data)
+ n = 1
(@buffer ||= BufferedTokenizer.new(delimiter = "__1_EE")).extract(data).each do |line|
- #receive_line(line)
- puts line
+ start = Time.now.to_i
+ raw = line.split('__1_B')
+ map = Hash.new
+ raw.each do |keys|
+ parts = keys.split('=')
+ map.store(parts[0],parts[1])
+ end
+ static = Logtype.find_by_name(map['logtype']).staticentries.new
+ static.data = map['data']
+ static.save
+ static = Staticentry.find_by_id(Digest::MD5.hexdigest(map['data']))
+ event = static.events.new
+ event.time = map['time']
+ event.loglevel = map['level']
+ event.payload = map['payload']
+ event.save
+ puts "done #{Time.now.to_i - start} #{n + 1}"
end
end
def unbind
ActiveRecord::Base.logger.info "-- someone disconnected from the collector"
end
end
module CommandServer
def post_init
ActiveRecord::Base.logger.info "-- someone connected to the command server"
end
def receive_data data
# Do something with the log data
ActiveRecord::Base.logger.info "#{data}"
end
def unbind
ActiveRecord::Base.logger.info "-- someone disconnected from the command server"
end
end
\ No newline at end of file
|
parabuzzle/cistern
|
452bb106b2cbb98491889f2a6085a2c2f1e848f4
|
Created the models and still hacking away at the log collection
|
diff --git a/src/server/app/models/agent.rb b/src/server/app/models/agent.rb
new file mode 100644
index 0000000..8914e9c
--- /dev/null
+++ b/src/server/app/models/agent.rb
@@ -0,0 +1,3 @@
+class Agent < ActiveRecord::Base
+ has_many :logtypes
+end
diff --git a/src/server/app/models/event.rb b/src/server/app/models/event.rb
index 3a829fd..d387e40 100644
--- a/src/server/app/models/event.rb
+++ b/src/server/app/models/event.rb
@@ -1,2 +1,3 @@
class Event < ActiveRecord::Base
+ belongs_to :staticentry
end
diff --git a/src/server/app/models/logtype.rb b/src/server/app/models/logtype.rb
new file mode 100644
index 0000000..b64f5a6
--- /dev/null
+++ b/src/server/app/models/logtype.rb
@@ -0,0 +1,4 @@
+class Logtype < ActiveRecord::Base
+ has_many :staticentries
+
+end
diff --git a/src/server/app/models/staticentry.rb b/src/server/app/models/staticentry.rb
new file mode 100644
index 0000000..c8b6e2a
--- /dev/null
+++ b/src/server/app/models/staticentry.rb
@@ -0,0 +1,13 @@
+class Staticentry < ActiveRecord::Base
+ has_many :events
+ belongs_to :logtype
+
+
+ def before_create
+ if Staticentry.find_by_id(Digest::MD5.hexdigest(self.data)) != nil
+ return false
+ end
+ self.id = Digest::MD5.hexdigest(self.data)
+ end
+
+end
diff --git a/src/server/config/collectors.yml b/src/server/config/collectors.yml
index 0f97992..234890d 100644
--- a/src/server/config/collectors.yml
+++ b/src/server/config/collectors.yml
@@ -1,26 +1,26 @@
#should contain all the collector config params
#UDP log collection configuration
udpcollector:
#The UDP port to listen on
port: 22222
#The ip address to bind to
#0.0.0.0 will bind to all available interfaces
listenip: 0.0.0.0
#TCP log collection configuration
tcpcollector:
#The TCP port to listen on
port: 9845
#The ip address to bind to
#0.0.0.0 will bind to all available interfaces
listenip: 0.0.0.0
#Admin server configuration
# -- used for agent checkin and configuration
-adminlistener:
+commandlistener:
#The TCP port to listen on
port: 9850
#The ip address to bind to
#0.0.0.0 will bind to all available interfaces
listenip: 0.0.0.0
\ No newline at end of file
diff --git a/src/server/config/database.yml b/src/server/config/database.yml
index 025d62a..2c35ea4 100644
--- a/src/server/config/database.yml
+++ b/src/server/config/database.yml
@@ -1,22 +1,26 @@
# SQLite version 3.x
# gem install sqlite3-ruby (not necessary on OS X Leopard)
development:
- adapter: sqlite3
- database: db/development.sqlite3
+ adapter: mysql
+ database: cistern
pool: 5
timeout: 5000
+ username: root
+ password:
# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
adapter: sqlite3
database: db/test.sqlite3
pool: 5
timeout: 5000
production:
- adapter: sqlite3
- database: db/production.sqlite3
+ adapter: mysql
+ database: cistern
pool: 5
timeout: 5000
+ username: root
+ password:
diff --git a/src/server/config/initializers/collector.rb b/src/server/config/initializers/collector.rb
index 71ffe91..d6ef0fc 100644
--- a/src/server/config/initializers/collector.rb
+++ b/src/server/config/initializers/collector.rb
@@ -1,14 +1,36 @@
+require 'digest/md5'
module CollectionServer
+
def post_init
ActiveRecord::Base.logger.info "-- someone connected to the collector"
end
- def receive_data data
- # Do something with the log data
- ActiveRecord::Base.logger.info "New Event - #{data}"
- end
+ def receive_data(data)
+ (@buffer ||= BufferedTokenizer.new(delimiter = "__1_EE")).extract(data).each do |line|
+ #receive_line(line)
+ puts line
+ end
+ end
+
def unbind
- ActiveRecord::Base.logger.info "-- someone disconnected to the collector"
+ ActiveRecord::Base.logger.info "-- someone disconnected from the collector"
end
- end
\ No newline at end of file
+end
+
+module CommandServer
+ def post_init
+ ActiveRecord::Base.logger.info "-- someone connected to the command server"
+ end
+
+ def receive_data data
+ # Do something with the log data
+ ActiveRecord::Base.logger.info "#{data}"
+ end
+
+ def unbind
+ ActiveRecord::Base.logger.info "-- someone disconnected from the command server"
+ end
+end
+
+
\ No newline at end of file
diff --git a/src/server/db/migrate/20090721233433_create_events.rb b/src/server/db/migrate/20090721233433_create_events.rb
index 7887cbb..c0913ed 100644
--- a/src/server/db/migrate/20090721233433_create_events.rb
+++ b/src/server/db/migrate/20090721233433_create_events.rb
@@ -1,12 +1,16 @@
class CreateEvents < ActiveRecord::Migration
def self.up
create_table :events do |t|
-
+ t.column :payload, :string
+ t.column :staticentry_id, :string
+ t.column :type_id, :int
+ t.column :loglevel, :int
+ t.column :time, :int
t.timestamps
end
end
def self.down
drop_table :events
end
end
diff --git a/src/server/db/migrate/20090730025541_create_staticentries.rb b/src/server/db/migrate/20090730025541_create_staticentries.rb
new file mode 100644
index 0000000..61d4b02
--- /dev/null
+++ b/src/server/db/migrate/20090730025541_create_staticentries.rb
@@ -0,0 +1,21 @@
+class CreateStaticentries < ActiveRecord::Migration
+ def self.up
+ create_table :staticentries, :id => false do |t|
+ t.column :id, :string, :null => false
+ #t.column :hash_key, :string, :null => false
+ t.column :logtype_id, :int
+ t.column :data, :text
+ t.column :agent_id, :int
+ t.timestamps
+ end
+ #add_index :staticentries, :hash_key
+ #add_index :staticentries, :agent_id
+ #unless ActiveRecord::Base.configurations[ENV['RAILS_ENV']]['adapter'] != 'mysql'
+ # execute "ALTER TABLE staticentries ADD PRIMARY KEY (id)"
+ #end
+ end
+
+ def self.down
+ drop_table :staticentries
+ end
+end
diff --git a/src/server/db/migrate/20090730025548_create_agents.rb b/src/server/db/migrate/20090730025548_create_agents.rb
new file mode 100644
index 0000000..7a1a271
--- /dev/null
+++ b/src/server/db/migrate/20090730025548_create_agents.rb
@@ -0,0 +1,15 @@
+class CreateAgents < ActiveRecord::Migration
+ def self.up
+ create_table :agents do |t|
+ t.column :name, :string
+ t.column :hostname, :string
+ t.column :port, :string
+ t.column :key, :string
+ t.timestamps
+ end
+ end
+
+ def self.down
+ drop_table :agents
+ end
+end
diff --git a/src/server/db/migrate/20090730025618_create_logtypes.rb b/src/server/db/migrate/20090730025618_create_logtypes.rb
new file mode 100644
index 0000000..39e5ddd
--- /dev/null
+++ b/src/server/db/migrate/20090730025618_create_logtypes.rb
@@ -0,0 +1,13 @@
+class CreateLogtypes < ActiveRecord::Migration
+ def self.up
+ create_table :logtypes do |t|
+ t.column :name, :string
+ t.column :agent_id, :int
+ t.timestamps
+ end
+ end
+
+ def self.down
+ drop_table :logtypes
+ end
+end
diff --git a/src/server/db/schema.rb b/src/server/db/schema.rb
new file mode 100644
index 0000000..d3234f4
--- /dev/null
+++ b/src/server/db/schema.rb
@@ -0,0 +1,48 @@
+# This file is auto-generated from the current state of the database. Instead of editing this file,
+# please use the migrations feature of Active Record to incrementally modify your database, and
+# then regenerate this schema definition.
+#
+# Note that this schema.rb definition is the authoritative source for your database schema. If you need
+# to create the application database on another system, you should be using db:schema:load, not running
+# all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations
+# you'll amass, the slower it'll run and the greater likelihood for issues).
+#
+# It's strongly recommended to check this file into your version control system.
+
+ActiveRecord::Schema.define(:version => 20090730025618) do
+
+ create_table "agents", :force => true do |t|
+ t.string "name"
+ t.string "hostname"
+ t.string "port"
+ t.string "key"
+ t.datetime "created_at"
+ t.datetime "updated_at"
+ end
+
+ create_table "events", :force => true do |t|
+ t.string "payload"
+ t.string "staticentry_id"
+ t.integer "type_id"
+ t.integer "loglevel"
+ t.integer "time"
+ t.datetime "created_at"
+ t.datetime "updated_at"
+ end
+
+ create_table "logtypes", :force => true do |t|
+ t.string "name"
+ t.integer "agent_id"
+ t.datetime "created_at"
+ t.datetime "updated_at"
+ end
+
+ create_table "staticentries", :force => true do |t|
+ t.integer "logtype_id"
+ t.text "data"
+ t.integer "agent_id"
+ t.datetime "created_at"
+ t.datetime "updated_at"
+ end
+
+end
diff --git a/src/server/lib/daemons/commandserver.rb b/src/server/lib/daemons/commandserver.rb
new file mode 100755
index 0000000..1149e0a
--- /dev/null
+++ b/src/server/lib/daemons/commandserver.rb
@@ -0,0 +1,21 @@
+#!/usr/bin/env ruby
+
+# TODO: Change this stuff
+ENV["RAILS_ENV"] ||= "production"
+require 'yaml'
+config = YAML::load(File.open(File.dirname(__FILE__) + "/../../config/collectors.yml"))['commandlistener']
+port = config['port']
+bindip = config['listenip']
+
+require File.dirname(__FILE__) + "/../../config/environment.rb"
+ActiveRecord::Base.logger.info "Starting command server :: listening on #{bindip}:#{port}"
+
+
+Signal.trap("TERM") do
+ ActiveRecord::Base.logger.info "-- Stopping command server"
+ EventMachine::stop_event_loop
+end
+
+EventMachine::run {
+ EventMachine::start_server bindip, port, CommandServer
+}
\ No newline at end of file
diff --git a/src/server/lib/daemons/commandserver_ctl b/src/server/lib/daemons/commandserver_ctl
new file mode 100755
index 0000000..0c01916
--- /dev/null
+++ b/src/server/lib/daemons/commandserver_ctl
@@ -0,0 +1,25 @@
+#!/usr/bin/env ruby
+require 'rubygems'
+require "daemons"
+require 'yaml'
+require 'erb'
+
+file_name = File.dirname(__FILE__) + "/../../vendor/rails/activesupport/lib/active_support.rb"
+
+if(File.exists?(file_name))
+ require file_name
+else
+rails_version = File.new(File.dirname(__FILE__)+ "/../../config/environment.rb").read.scan(/^ *RAILS_GEM_VERSION.*=.*['|"](.*)['|"]/)[0].to_s
+
+gem 'activesupport', rails_version
+require 'active_support'
+end
+
+options = YAML.load(
+ ERB.new(
+ IO.read(
+ File.dirname(__FILE__) + "/../../config/daemons.yml"
+ )).result).with_indifferent_access
+options[:dir_mode] = options[:dir_mode].to_sym
+
+Daemons.run File.dirname(__FILE__) + '/commandserver.rb', options
diff --git a/src/server/test/fixtures/agents.yml b/src/server/test/fixtures/agents.yml
new file mode 100644
index 0000000..5bf0293
--- /dev/null
+++ b/src/server/test/fixtures/agents.yml
@@ -0,0 +1,7 @@
+# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
+
+# one:
+# column: value
+#
+# two:
+# column: value
diff --git a/src/server/test/fixtures/logtypes.yml b/src/server/test/fixtures/logtypes.yml
new file mode 100644
index 0000000..5bf0293
--- /dev/null
+++ b/src/server/test/fixtures/logtypes.yml
@@ -0,0 +1,7 @@
+# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
+
+# one:
+# column: value
+#
+# two:
+# column: value
diff --git a/src/server/test/fixtures/staticentries.yml b/src/server/test/fixtures/staticentries.yml
new file mode 100644
index 0000000..5bf0293
--- /dev/null
+++ b/src/server/test/fixtures/staticentries.yml
@@ -0,0 +1,7 @@
+# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
+
+# one:
+# column: value
+#
+# two:
+# column: value
diff --git a/src/server/test/unit/agent_test.rb b/src/server/test/unit/agent_test.rb
new file mode 100644
index 0000000..0e33310
--- /dev/null
+++ b/src/server/test/unit/agent_test.rb
@@ -0,0 +1,8 @@
+require 'test_helper'
+
+class AgentTest < ActiveSupport::TestCase
+ # Replace this with your real tests.
+ test "the truth" do
+ assert true
+ end
+end
diff --git a/src/server/test/unit/logtype_test.rb b/src/server/test/unit/logtype_test.rb
new file mode 100644
index 0000000..b9c3e77
--- /dev/null
+++ b/src/server/test/unit/logtype_test.rb
@@ -0,0 +1,8 @@
+require 'test_helper'
+
+class LogtypeTest < ActiveSupport::TestCase
+ # Replace this with your real tests.
+ test "the truth" do
+ assert true
+ end
+end
diff --git a/src/server/test/unit/staticentry_test.rb b/src/server/test/unit/staticentry_test.rb
new file mode 100644
index 0000000..4ccfdc3
--- /dev/null
+++ b/src/server/test/unit/staticentry_test.rb
@@ -0,0 +1,8 @@
+require 'test_helper'
+
+class StaticentryTest < ActiveSupport::TestCase
+ # Replace this with your real tests.
+ test "the truth" do
+ assert true
+ end
+end
|
parabuzzle/cistern
|
fc950646cb55f74dc747972a61eba4e83960bf88
|
generated the event model stubs
|
diff --git a/src/server/app/models/event.rb b/src/server/app/models/event.rb
new file mode 100644
index 0000000..3a829fd
--- /dev/null
+++ b/src/server/app/models/event.rb
@@ -0,0 +1,2 @@
+class Event < ActiveRecord::Base
+end
diff --git a/src/server/db/migrate/20090721233433_create_events.rb b/src/server/db/migrate/20090721233433_create_events.rb
new file mode 100644
index 0000000..7887cbb
--- /dev/null
+++ b/src/server/db/migrate/20090721233433_create_events.rb
@@ -0,0 +1,12 @@
+class CreateEvents < ActiveRecord::Migration
+ def self.up
+ create_table :events do |t|
+
+ t.timestamps
+ end
+ end
+
+ def self.down
+ drop_table :events
+ end
+end
diff --git a/src/server/test/fixtures/events.yml b/src/server/test/fixtures/events.yml
new file mode 100644
index 0000000..5bf0293
--- /dev/null
+++ b/src/server/test/fixtures/events.yml
@@ -0,0 +1,7 @@
+# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
+
+# one:
+# column: value
+#
+# two:
+# column: value
diff --git a/src/server/test/unit/event_test.rb b/src/server/test/unit/event_test.rb
new file mode 100644
index 0000000..c2b9b78
--- /dev/null
+++ b/src/server/test/unit/event_test.rb
@@ -0,0 +1,8 @@
+require 'test_helper'
+
+class EventTest < ActiveSupport::TestCase
+ # Replace this with your real tests.
+ test "the truth" do
+ assert true
+ end
+end
|
parabuzzle/cistern
|
cee1544d094d3e7e71a7bd0c579973a990d05b11
|
commented the collector config file
|
diff --git a/src/server/config/collectors.yml b/src/server/config/collectors.yml
index c42c2b0..0f97992 100644
--- a/src/server/config/collectors.yml
+++ b/src/server/config/collectors.yml
@@ -1,9 +1,26 @@
#should contain all the collector config params
+#UDP log collection configuration
udpcollector:
+ #The UDP port to listen on
port: 22222
+ #The ip address to bind to
+ #0.0.0.0 will bind to all available interfaces
listenip: 0.0.0.0
-
+
+#TCP log collection configuration
tcpcollector:
+ #The TCP port to listen on
port: 9845
+ #The ip address to bind to
+ #0.0.0.0 will bind to all available interfaces
+ listenip: 0.0.0.0
+
+#Admin server configuration
+# -- used for agent checkin and configuration
+adminlistener:
+ #The TCP port to listen on
+ port: 9850
+ #The ip address to bind to
+ #0.0.0.0 will bind to all available interfaces
listenip: 0.0.0.0
\ No newline at end of file
|
parabuzzle/cistern
|
8524387d2cc9ceb3507dcfbd90322ae933d39ee3
|
log collectors use yaml config file in the config directory now
|
diff --git a/src/server/config/collectors.yml b/src/server/config/collectors.yml
index 34d47d0..c42c2b0 100644
--- a/src/server/config/collectors.yml
+++ b/src/server/config/collectors.yml
@@ -1 +1,9 @@
-#should contain all the collector config params
\ No newline at end of file
+#should contain all the collector config params
+
+udpcollector:
+ port: 22222
+ listenip: 0.0.0.0
+
+tcpcollector:
+ port: 9845
+ listenip: 0.0.0.0
\ No newline at end of file
diff --git a/src/server/lib/daemons/tcpcollector.rb b/src/server/lib/daemons/tcpcollector.rb
index 55003e6..81982a3 100755
--- a/src/server/lib/daemons/tcpcollector.rb
+++ b/src/server/lib/daemons/tcpcollector.rb
@@ -1,22 +1,21 @@
#!/usr/bin/env ruby
# TODO: Change this stuff
ENV["RAILS_ENV"] ||= "production"
-#require 'socket'
-port = 9845
-bindip = "0.0.0.0"
-#server = UDPSocket.open
-#server.bind(nil, port)
+require 'yaml'
+config = YAML::load(File.open(File.dirname(__FILE__) + "/../../config/collectors.yml"))['tcpcollector']
+port = config['port']
+bindip = config['listenip']
require File.dirname(__FILE__) + "/../../config/environment.rb"
ActiveRecord::Base.logger.info "Starting TCP log collector :: listening on #{bindip}:#{port}"
Signal.trap("TERM") do
ActiveRecord::Base.logger.info "-- Stopping TCP collector"
EventMachine::stop_event_loop
end
EventMachine::run {
EventMachine::start_server bindip, port, CollectionServer
}
\ No newline at end of file
diff --git a/src/server/lib/daemons/udpcollector.rb b/src/server/lib/daemons/udpcollector.rb
index 0e7f92e..23c2076 100755
--- a/src/server/lib/daemons/udpcollector.rb
+++ b/src/server/lib/daemons/udpcollector.rb
@@ -1,23 +1,21 @@
#!/usr/bin/env ruby
# TODO: Change this stuff
ENV["RAILS_ENV"] ||= "production"
-#require 'socket'
-port = 12000
-bindip = "0.0.0.0"
-#server = UDPSocket.open
-#server.bind(nil, port)
+require 'yaml'
+config = YAML::load(File.open(File.dirname(__FILE__) + "/../../config/collectors.yml"))['udpcollector']
+port = config['port']
+bindip = config['listenip']
require File.dirname(__FILE__) + "/../../config/environment.rb"
ActiveRecord::Base.logger.info "Starting UDP log collector :: listening on #{bindip}:#{port}"
-#require 'collector.rb'
Signal.trap("TERM") do
ActiveRecord::Base.logger.info "-- Stopping UDP collector"
EventMachine::stop_event_loop
end
EventMachine::run {
EventMachine::open_datagram_socket bindip, port, CollectionServer
}
\ No newline at end of file
|
parabuzzle/cistern
|
bc246f04be1f12db53043774fd62082c690a39dd
|
added license
|
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..3383483
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+The MIT License
+
+Copyright (c) 2009 Michael Heijmans
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
\ No newline at end of file
diff --git a/README b/README
index 028b6d0..a2658c7 100644
--- a/README
+++ b/README
@@ -1,9 +1,10 @@
-Cistern
+Cistern - [http://parabuzzle.github.com/cistern]
DEFINED: A receptacle for holding water or other liquid, especially a tank for catching and storing rainwater.
Cistern is a log collection application.
Cistern is a lightweight server that collects log events and displays them in a useful way. The application collects events from many different sources and allows viewing and graphing of that data for admins and developers.
Cistern was born out of need for a place to allow developers to view logs on production machines without a need for the developer to have access to the production environment.
+Cistern is licensed under the MIT license. Please see the LICENSE file provided in the latest source tree for latest license terms and usage.
diff --git a/src/collectors/udpcollector.rb b/src/collectors/udpcollector.rb
index 5af4791..a034ecc 100644
--- a/src/collectors/udpcollector.rb
+++ b/src/collectors/udpcollector.rb
@@ -1,14 +1,16 @@
# Cistern UDP Collector application
-# This application is part of the Cistern Application
+# This file is part of the Cistern Application
#
# Author - Mike Heijmans (parabuzzle@yahoo.com)
#
+# Licensed under the MIT License
+# Copyright (c) 2009 Michael Heijmans
require 'socket'
-port = 12000
+port = 11111
server = UDPSocket.open
server.bind(nil, port)
loop do
text,sender = server.recvfrom(1024)
puts text
end
|
jstorimer/sinatra-shopify
|
696673fb6ca2d47d1aeed10918fb4605540e06c5
|
Cleaning up the documentation so it looks pretty on github
|
diff --git a/README.md b/README.md
index bd2b970..4d2ba06 100644
--- a/README.md
+++ b/README.md
@@ -1,45 +1,45 @@
Sinatra-Shopify: A classy shopify_app
-====================================
+------------------------------------
-This is a Sinatra extension that allows you to work with the "Shopify API":http://shopify.com/developers. It's basically just a port of the "shopify_app":http://github.com/Shopify/shopify_app rails plugin to sinatra.
+This is a Sinatra extension that allows you to work with the [Shopify API](http://shopify.com/developers). It's basically just a port of the [shopify_app](http://github.com/Shopify/shopify_app) rails plugin to sinatra.
-== Why?
+## Why? ##
-I have been "having fun working on Shopify apps":http://www.jstorimer.com/blogs/my-blog/1133402-shopify-api-extensions lately, but I needed a simpler way than always generating a new rails app, new controllers, etc., for every little idea.
+I have been [having fun working on Shopify apps](http://www.jstorimer.com/blogs/my-blog/1133402-shopify-api-extensions) lately, but I needed a simpler way than always generating a new rails app, new controllers, etc., for every little idea.
-Rails is great, but most of the "Shopify apps":http://apps.shopify.com that I have come up with are one page apps, maybe two or three pages. The point is, I don't need a controller for that, I don't need the 63 files or however many the rails generator generates for me.
+Rails is great, but most of the [Shopify apps](http://apps.shopify.com) that I have come up with are one page apps, maybe two or three pages. The point is, I don't need a controller for that, I don't need the 63 files or however many the rails generator generates for me.
Sinatra is most awesome when you are working on a small app with just a few routes. You can clone this app and use it as a starting point for a shopify_app. All of the authentication logic/routes are in the lib folder, so they don't pollute the code of your app.
So in app.rb, you just have to worry about the functionality of your app.
-== Usage
+## Usage ##
-Installable from rubygems as 'sinatra-shopify'.
+Installable from rubygems as `sinatra-shopify` or you can add it to your gemfile as `gem 'sinatra-shopify'`.
-The current implementation for authentication is to add the @authorize!@ method at the top of any routes that you want to be authenticated, like so:
+The current implementation for authentication is to add the `authorize!` method at the top of any routes that you want to be authenticated, like so:
```ruby
get '/sensitive_data' do
authorize!
# then do the sensitive stuff
end
```
Example
-======
+--------
This repo includes an example Sinatra app. The fastest way to get it running:
-* @git clone git://github.com/jstorimer/sinatra-shopify@
-* @cd sinatra-shopify@
-* @heroku create@ (make sure that you remember the name of your app as you will need that later)
-* visit the "Shopify Partners area":http://app.shopify.com/services/partners
+* `git clone git://github.com/jstorimer/sinatra-shopify`
+* `cd sinatra-shopify`
+* `heroku create` (make sure that you remember the name of your app as you will need that later)
+* visit the [Shopify Partners area](http://app.shopify.com/services/partners)
* Sign up for an account if you don't already have one
* Log in to your Shopify partners account
* Create a new application.
-* Make sure that the Callback URL is set to http://_yourapp_.heroku.com/login/finalize
-* In the lib/sinatra/shopify.yml file replace API_KEY and SECRET with the Api Key and Secret that you just got from the Shopify Partners area
-* @git push heroku master@
-* @heroku open@
+* Make sure that the Callback URL is set to `http://_yourapp_.heroku.com/login/finalize`
+* In the `lib/sinatra/shopify.yml` file replace API_KEY and SECRET with the Api Key and Secret that you just got from the Shopify Partners area
+* `git push heroku master`
+* `heroku open`
|
jstorimer/sinatra-shopify
|
8aad7d7a4b436f14d332375f5572c6fb07927214
|
Add warning if you don't set your API creds
|
diff --git a/lib/sinatra/shopify.rb b/lib/sinatra/shopify.rb
index 5d0f374..5b8cee2 100644
--- a/lib/sinatra/shopify.rb
+++ b/lib/sinatra/shopify.rb
@@ -1,78 +1,81 @@
require 'sinatra/base'
require 'shopify_api'
module Sinatra
module Shopify
module Helpers
def current_shop
session[:shopify]
end
def authorize!
redirect '/login' unless current_shop
ShopifyAPI::Base.site = session[:shopify].site
end
def logout!
session[:shopify] = nil
end
end
def self.registered(app)
app.helpers Shopify::Helpers
app.enable :sessions
app.template :login do
<<-SRC
<h1>Login</h1>
<p>
First you have to register this app with a shop to allow access to its private admin data.
</p>
<form action='/login/authenticate' method='post'>
<label for='shop'><strong>The URL of the Shop</strong>
<span class="hint">(or just the subdomain if it's at myshopify.com)</span>
</label>
<p>
<input type='text' name='shop' />
</p>
<input type='submit' value='Authenticate' />
</form>
SRC
end
+ unless ENV['SHOPIFY_API_KEY'] && ENV['SHOPIFY_API_SECRET']
+ puts "Set your Shopify api_key and secret via ENV['SHOPIFY_API_KEY'] and ENV['SHOPIFY_API_SECRET']"
+ end
ShopifyAPI::Session.setup(:api_key => ENV['SHOPIFY_API_KEY'], :secret => ENV['SHOPIFY_API_SECRET'])
app.get '/login' do
erb :login
end
app.get '/logout' do
logout!
redirect '/'
end
app.post '/login/authenticate' do
redirect ShopifyAPI::Session.new(params[:shop]).create_permission_url
end
app.get '/login/finalize' do
shopify_session = ShopifyAPI::Session.new(params[:shop], params[:t])
if shopify_session.valid?
session[:shopify] = shopify_session
return_address = session[:return_to] || '/'
session[:return_to] = nil
redirect return_address
else
redirect '/login'
end
end
end
end
register Shopify
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.