<commit_before>#include "data-course.hpp"
using namespace std;

void Course::init(string identifier) {
	// cout << identifier << endl;
	copy(getCourse(identifier));
}
void Course::copy(const Course& c) {
	id = c.id;
	number = c.number;
	title = c.title;
	description = c.description;
	section = c.section;
	majors = c.majors;
	department = c.department;
	concentrations = c.concentrations;
	conversations = c.conversations;
	professor = c.professor;

	half_semester = c.half_semester;
	pass_fail = c.pass_fail;
	credits = c.credits;
	location = c.location;

	lab = c.lab;
	geneds = c.geneds;

	for (int i = 0; i < 7; ++i){
		days[i] = c.days[i];
		time[i] = c.time[i];
	}
}

Course::Course() {

}

Course::Course(string str) {
	init(str);
}

Course::Course(const Course& c) {
	copy(c);
}

Course& Course::operator = (const Course &c) {
	if (this == &c) return *this;
	copy(c);
	return *this;
}

Course::Course(istream &is) {
	// cout << "Now indise Course()" << endl;
	if (!is) return;
	// cout << "Now inside Course(after return)" << endl;

	string tmpLine;
	getline(is, tmpLine); // read in so we can do things with it.

	vector<string> record = split(tmpLine, ',');
	for (vector<string>::iterator i=record.begin(); i != record.end(); ++i) {
		*i = removeAllQuotes(*i);
		*i = removeTrailingSlashes(*i);
	}

	// printEntireRecord(record);

	// Ignore the first column;
	// record.at(0);

	// so, the *first* column (that we care about) has the course id,
	id = record.at(1);
	parseID(id);

	// Second column has the section,
	section = record.at(2);

	// Third holds the lab boolean,
	if (record.at(3).empty()) lab = false;
	else                      lab = true;

	// while Fourth contains the title of the course;
	title = record.at(4);

	// Fifth hands over the length (half semester or not)
	// it's actually an int that tells us how many times the course is offered per semester.
	half_semester = stringToInt(record.at(5));
	if (half_semester != 0 && half_semester != 1 && half_semester != 2)
		half_semester = 0;

	// Sixth tells us the number of credits,
	credits = stringToFloat(record.at(6));

	// Seventh shows us if it can be taken pass/no-pass,
	if (record.at(7) == "Y")
		pass_fail = true;
	else
		pass_fail = false;

	// while Eighth gives us the GEs of the course,
	// GEreqs = record.at(8);

	// and Nine spits out the days and times;
	// Times = record.at(9);

	// Ten holds the location,
	location = record.at(10);
	location = deDoubleString(location);

	// and Eleven knows who teaches.
	if (record.size() == 13) {
		string profLastName = record.at(11);
		string profFirstName = record.at(12);
		profFirstName.erase(0, 1); // remove the extra space from the start of the name
		professor = profFirstName + " " + profLastName;
	}
	else {
		professor = record.at(11);
	}

	updateID();
	title = cleanTitle(title);
	record.clear();
}

bool operator== (Course &c1, Course &c2) {
    return (c1.id == c2.id);
}

bool operator!= (Course &c1, Course &c2) {
    return !(c1 == c2);
}

string Course::cleanTitle(string title) {
	vector<string> badEndings, badBeginnings;

	badEndings.push_back(" Closed");
	badEndings.push_back(" During course submission process");
	badEndings.push_back(" Especially for ");
	badEndings.push_back(" Film screenings");
	badEndings.push_back(" First-Year Students may register only");
	badEndings.push_back(" New course");
	badEndings.push_back(" Not open to first-year students.");
	badEndings.push_back(" Open only to ");
	badEndings.push_back(" Open to ");
	badEndings.push_back(" Permission of ");
	badEndings.push_back(" Prereq");
	badEndings.push_back(" Registration");
	badEndings.push_back(" Taught in English.");
	badEndings.push_back(" This course");
	badEndings.push_back(" This lab has been canceled.");
	badEndings.push_back(" Students in ");

	badBeginnings.push_back("Top: ");
	badBeginnings.push_back("Sem: ");
	badBeginnings.push_back("Res: ");

	for (vector<string>::iterator i=badEndings.begin(); i != badEndings.end(); ++i)
		title = removeTrailingText(title, *i);
	for (vector<string>::iterator i=badBeginnings.begin(); i != badBeginnings.end(); ++i)
		title = removeStartingText(title, *i);

	return title;
}

string Course::getProfessor() {
	return professor;
}

void Course::parseID(string str) {
	// Get the number of the course, aka the last three slots.
	stringstream(str.substr(str.size() - 3)) >> number;

	// Check if it's one of those dastardly "split courses".
	string dept = str.substr(0,str.size()-3);

	if (str.find('/') != string::npos) {
		department.push_back(Department(dept.substr(0,2)));
		department.push_back(Department(dept.substr(3,2)));
	}
	else {
		department.push_back(Department(dept));
	}
}

void Course::updateID() {
	string dept;
	for (std::vector<Department>::iterator i = department.begin(); i != department.end(); ++i) {
		dept += i->getName();
		if (i != department.end()-1)
			dept += "/";
	}
	id = dept + " " + tostring(number) + section;
}

string Course::getID() {
	return id;
}

ostream& Course::getData(ostream &os) {
	os << id;
	if (lab) os << " L";
	os << " - ";
	os << title << " | ";
	if (professor.length() > 0 && professor != " ")
		os << professor;
	return os;
}

void Course::showAll() {
	cout << id << section << endl;
	cout << "Title: " << title << endl;
	cout << "Professor: " << professor << endl;
	cout << "Lab? " << lab << endl;
	cout << "Half-semester? " << half_semester << endl;
	cout << "Credits: " << credits << endl;
	cout << "Pass/Fail? " << pass_fail << endl;
	cout << "Location: " << location << endl;
	cout << endl;
}

ostream &operator<<(ostream &os, Course &item) {
	return item.getData(os);
}

void Course::display() {
	cout << *this << endl;
}

void Course::displayMany() {
	cout << id;
	if (lab) cout << " L";
	cout << "\t- ";
	cout << title << " | ";
	if (professor.length() > 0 && professor != " ")
		cout << professor;
	cout << endl;
}

Course getCourse(string identifier) {
	// cout << "Before cleanup: " << identifier << endl;
	// Make sure everything is uppercase
	std::transform(identifier.begin(), identifier.end(), identifier.begin(), ::toupper);

	// Remove a possible space at the front
	if (identifier[0] == ' ')
		identifier.erase(0, 1);

	// add a space into the course id, if there isn't one already
	// find the first digit in the string
	int firstDigit = identifier.find_first_of("0123456789");

	if (identifier.find(" ") == string::npos)
			identifier.insert(firstDigit, 1, ' ');

	// cout << "After cleanup: " << identifier << endl;

	for (vector<Course>::iterator i = all_courses.begin(); i != all_courses.end(); ++i)
		if (i->getID() == identifier)
			return *i;

	// If no match, return a blank course.
	Course c;
	return c;
}
<commit_msg>Add more TODOs<commit_after>#include "data-course.hpp"
using namespace std;

void Course::init(string identifier) {
	// cout << identifier << endl;
	copy(getCourse(identifier));
}
void Course::copy(const Course& c) {
	id = c.id;
	number = c.number;
	title = c.title;
	description = c.description;
	section = c.section;
	majors = c.majors;
	department = c.department;
	concentrations = c.concentrations;
	conversations = c.conversations;
	professor = c.professor;

	half_semester = c.half_semester;
	pass_fail = c.pass_fail;
	credits = c.credits;
	location = c.location;

	lab = c.lab;
	geneds = c.geneds;

	for (int i = 0; i < 7; ++i){
		days[i] = c.days[i];
		time[i] = c.time[i];
	}
}

Course::Course() {

}

Course::Course(string str) {
	init(str);
}

Course::Course(const Course& c) {
	copy(c);
}

Course& Course::operator = (const Course &c) {
	if (this == &c) return *this;
	copy(c);
	return *this;
}

Course::Course(istream &is) {
	// cout << "Now indise Course()" << endl;
	if (!is) return;
	// cout << "Now inside Course(after return)" << endl;

	string tmpLine;
	getline(is, tmpLine); // read in so we can do things with it.

	vector<string> record = split(tmpLine, ',');
	for (vector<string>::iterator i=record.begin(); i != record.end(); ++i) {
		*i = removeAllQuotes(*i);
		*i = removeTrailingSlashes(*i);
	}

	// printEntireRecord(record);

	// Ignore the first column;
	// record.at(0);

	// so, the *first* column (that we care about) has the course id,
	id = record.at(1);
	parseID(id);

	// Second column has the section,
	section = record.at(2);

	// Third holds the lab boolean,
	if (record.at(3).empty()) lab = false;
	else                      lab = true;

	// while Fourth contains the title of the course;
	title = record.at(4);

	// Fifth hands over the length (half semester or not)
	// it's actually an int that tells us how many times the course is offered per semester.
	half_semester = stringToInt(record.at(5));
	if (half_semester != 0 && half_semester != 1 && half_semester != 2)
		half_semester = 0;

	// Sixth tells us the number of credits,
	credits = stringToFloat(record.at(6));

	// Seventh shows us if it can be taken pass/no-pass,
	if (record.at(7) == "Y")
		pass_fail = true;
	else
		pass_fail = false;

	// while Eighth gives us the GEs of the course,
	// GEreqs = record.at(8);

	// and Nine spits out the days and times;
	// Times = record.at(9);

	// Ten holds the location,
	location = record.at(10);
	location = deDoubleString(location);

	// and Eleven knows who teaches.
	if (record.size() == 13) {
		string profLastName = record.at(11);
		string profFirstName = record.at(12);
		profFirstName.erase(0, 1); // remove the extra space from the start of the name
		professor = profFirstName + " " + profLastName;
	}
	else {
		professor = record.at(11);
	}

	updateID();
	title = cleanTitle(title);
	record.clear();
}

bool operator== (Course &c1, Course &c2) {
    return (c1.id == c2.id);
}

bool operator!= (Course &c1, Course &c2) {
    return !(c1 == c2);
}

string Course::cleanTitle(string title) {
	vector<string> badEndings, badBeginnings;

	badEndings.push_back(" Closed");
	badEndings.push_back(" During course submission process");
	badEndings.push_back(" Especially for ");
	badEndings.push_back(" Film screenings");
	badEndings.push_back(" First-Year Students may register only");
	badEndings.push_back(" New course");
	badEndings.push_back(" Not open to first-year students.");
	badEndings.push_back(" Open only to ");
	badEndings.push_back(" Open to ");
	badEndings.push_back(" Permission of ");
	badEndings.push_back(" Prereq");
	badEndings.push_back(" Registration");
	badEndings.push_back(" Taught in English.");
	badEndings.push_back(" This course");
	badEndings.push_back(" This lab has been canceled.");
	badEndings.push_back(" Students in ");

	badBeginnings.push_back("Top: ");
	badBeginnings.push_back("Sem: ");
	badBeginnings.push_back("Res: ");

	for (vector<string>::iterator i=badEndings.begin(); i != badEndings.end(); ++i)
		title = removeTrailingText(title, *i);
	for (vector<string>::iterator i=badBeginnings.begin(); i != badBeginnings.end(); ++i)
		title = removeStartingText(title, *i);

	return title;
}

string Course::getProfessor() {
	return professor;
}

void Course::parseID(string str) {
	// Get the number of the course, aka the last three slots.
	stringstream(str.substr(str.size() - 3)) >> number;

	// Check if it's one of those dastardly "split courses".
	string dept = str.substr(0,str.size()-3);

	if (str.find('/') != string::npos) {
		department.push_back(Department(dept.substr(0,2)));
		department.push_back(Department(dept.substr(3,2)));
	}
	else {
		department.push_back(Department(dept));
	}
}

void Course::updateID() {
	string dept;
	for (std::vector<Department>::iterator i = department.begin(); i != department.end(); ++i) {
		dept += i->getName();
		if (i != department.end()-1)
			dept += "/";
	}
	id = dept + " " + tostring(number) + section;
}

string Course::getID() {
	return id;
}

ostream& Course::getData(ostream &os) {
	os << id;
	if (lab) os << " L";
	os << " - ";
	os << title << " | ";
	if (professor.length() > 0 && professor != " ")
		os << professor;
	return os;
}

void Course::showAll() {
	cout << id << section << endl;
	cout << "Title: " << title << endl;
	cout << "Professor: " << professor << endl;
	cout << "Lab? " << lab << endl;
	cout << "Half-semester? " << half_semester << endl;
	cout << "Credits: " << credits << endl;
	cout << "Pass/Fail? " << pass_fail << endl;
	cout << "Location: " << location << endl;
	cout << endl;
}

ostream &operator<<(ostream &os, Course &item) {
	return item.getData(os);
}

void Course::display() {
	cout << *this << endl;
}

void Course::displayMany() {
	cout << id;
	if (lab) cout << " L";
	cout << "\t- ";
	cout << title << " | ";
	if (professor.length() > 0 && professor != " ")
		cout << professor;
	cout << endl;
}

Course getCourse(string identifier) {
	// TODO: Merge the two ways of parsing IDs
	// TODO: Add lab support.

	// cout << "Before cleanup: " << identifier << endl;
	// Make sure everything is uppercase
	std::transform(identifier.begin(), identifier.end(), identifier.begin(), ::toupper);

	// Remove a possible space at the front
	if (identifier[0] == ' ')
		identifier.erase(0, 1);

	// add a space into the course id, if there isn't one already
	// find the first digit in the string
	int firstDigit = identifier.find_first_of("0123456789");

	if (identifier.find(" ") == string::npos)
			identifier.insert(firstDigit, 1, ' ');

	// cout << "After cleanup: " << identifier << endl;

	for (vector<Course>::iterator i = all_courses.begin(); i != all_courses.end(); ++i)
		if (i->getID() == identifier)
			return *i;

	// If no match, return a blank course.
	Course c;
	return c;
}
<|endoftext|>


<commit_before>/*****************************************************************************
 * vlcshell.cpp: a VLC plugin for Mozilla
 *****************************************************************************
 * Copyright (C) 2002-2009 the VideoLAN team
 * $Id$
 *
 * Authors: Samuel Hocevar <sam@zoy.org>
 *          Jean-Paul Saman <jpsaman@videolan.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

/*****************************************************************************
 * Preamble
 *****************************************************************************/

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "vlcplugin.h"
#include "vlcshell.h"

/******************************************************************************
 * UNIX-only API calls
 *****************************************************************************/
NPP_GET_MIME_CONST char * NPP_GetMIMEDescription( void )
{
    return mimetype;
}

NPError NPP_GetValue( NPP instance, NPPVariable variable, void *value )
{
    static char psz_name[] = PLUGIN_NAME;
    static char psz_desc[1000];

    /* plugin class variables */
    switch( variable )
    {
        case NPPVpluginNameString:
            *((char **)value) = psz_name;
            return NPERR_NO_ERROR;

        case NPPVpluginDescriptionString:
            snprintf( psz_desc, sizeof(psz_desc), PLUGIN_DESCRIPTION,
                      libvlc_get_version() );
            *((char **)value) = psz_desc;
            return NPERR_NO_ERROR;

#if defined(XP_UNIX)
        case NPPVpluginNeedsXEmbed:
            *((bool *)value) = true;
            return NPERR_NO_ERROR;
#endif

        default:
            /* move on to instance variables ... */
            ;
    }

    if( instance == NULL )
    {
        return NPERR_INVALID_INSTANCE_ERROR;
    }

    /* plugin instance variables */

    VlcPluginBase *p_plugin = reinterpret_cast<VlcPluginBase *>(instance->pdata);
    if( NULL == p_plugin )
    {
        /* plugin has not been initialized yet ! */
        return NPERR_INVALID_INSTANCE_ERROR;
    }

    switch( variable )
    {
        case NPPVpluginScriptableNPObject:
        {
            /* retrieve plugin root class */
            NPClass *scriptClass = p_plugin->getScriptClass();
            if( scriptClass )
            {
                /* create an instance and return it */
                *(NPObject**)value = NPN_CreateObject(instance, scriptClass);
                return NPERR_NO_ERROR;
            }
            break;
        }

        default:
            ;
    }
    return NPERR_GENERIC_ERROR;
}

/*
 * there is some confusion in gecko headers regarding definition of this API
 * NPPVariable is wrongly defined as NPNVariable, which sounds incorrect.
 */

NPError NPP_SetValue( NPP, NPNVariable, void * )
{
    return NPERR_GENERIC_ERROR;
}

/******************************************************************************
 * Mac-only API calls
 *****************************************************************************/
#ifdef XP_MACOSX
int16_t NPP_HandleEvent( NPP instance, void * event )
{
    static UInt32 lastMouseUp = 0;
    if( instance == NULL )
    {
        return false;
    }

    VlcPluginBase *p_plugin = reinterpret_cast<VlcPluginBase *>(instance->pdata);
    if( p_plugin == NULL )
    {
        return false;
    }

// FIXME: implement Cocoa event model, by porting this legacy code:
/*
    EventRecord *myEvent = (EventRecord*)event;

    switch( myEvent->what )
    {
        case nullEvent:
            return true;
        case mouseDown:
        {
            if( (myEvent->when - lastMouseUp) < GetDblTime() )
            {
                // double click
                p_plugin->toggle_fullscreen();
            }
            return true;
        }
        case mouseUp:
            lastMouseUp = myEvent->when;
            return true;
        case keyUp:
        case keyDown:
        case autoKey:
            return true;
        case updateEvt:
        {
            const NPWindow& npwindow = p_plugin->getWindow();
            if( npwindow.window )
            {
                bool hasVout = false;

                if( p_plugin->playlist_isplaying() )
                {
                    hasVout = p_plugin->player_has_vout();
#if 0
                    if( hasVout )
                    {
                        libvlc_rectangle_t area;
                        area.left = 0;
                        area.top = 0;
                        area.right = npwindow.width;
                        area.bottom = npwindow.height;
                        libvlc_video_redraw_rectangle(p_plugin->getMD(), &area, NULL);
                    }
#else
#warning disabled code
#endif
                }

                if( ! hasVout )
                {
                    // draw the text from get_bg_text()
                    ForeColor(blackColor);
                    PenMode( patCopy );

                    // seems that firefox forgets to set the following
                    // on occasion (reload)
                    SetOrigin(((NP_Port *)npwindow.window)->portx,
                              ((NP_Port *)npwindow.window)->porty);

                    Rect rect;
                    rect.left = 0;
                    rect.top = 0;
                    rect.right = npwindow.width;
                    rect.bottom = npwindow.height;
                    PaintRect( &rect );

                    ForeColor(whiteColor);
                    MoveTo( (npwindow.width-80)/ 2  , npwindow.height / 2 );
                    if( !p_plugin->get_bg_text().empty() )
                        DrawText( p_plugin->get_bg_text().c_str(), 0, p_plugin->get_bg_text().length() );
                }
            }
            return true;
        }
        case activateEvt:
            return false;
        case NPEventType_GetFocusEvent:
        case NPEventType_LoseFocusEvent:
            return true;
        case NPEventType_AdjustCursorEvent:
            return false;
        case NPEventType_MenuCommandEvent:
            return false;
        case NPEventType_ClippingChangedEvent:
            return false;
        case NPEventType_ScrollingBeginsEvent:
            return true;
        case NPEventType_ScrollingEndsEvent:
            return true;
        default:
            ;
    }
*/
    return false;
}
#endif /* XP_MACOSX */

/******************************************************************************
 * General Plug-in Calls
 *****************************************************************************/
NPError NPP_Initialize( void )
{
#ifdef XP_UNIX
    NPError err = NPERR_NO_ERROR;
    bool supportsXEmbed = false;

    err = NPN_GetValue( NULL, NPNVSupportsXEmbedBool,
                        (void *)&supportsXEmbed );

    if ( err != NPERR_NO_ERROR || supportsXEmbed != true )
        return NPERR_INCOMPATIBLE_VERSION_ERROR;
#endif

    return NPERR_NO_ERROR;
}

#ifdef OJI
jref NPP_GetJavaClass( void )
{
    return NULL;
}
#endif

void NPP_Shutdown( void )
{
    ;
}

NPError NPP_New( NPMIMEType, NPP instance,
                 NPuint16_t mode, NPint16_t argc,
                 char* argn[], char* argv[], NPSavedData* )
{
    NPError status;

    if( instance == NULL )
    {
        return NPERR_INVALID_INSTANCE_ERROR;
    }

    VlcPluginBase *p_plugin = new VlcPlugin( instance, mode );
    if( NULL == p_plugin )
    {
        return NPERR_OUT_OF_MEMORY_ERROR;
    }

    status = p_plugin->init(argc, argn, argv);
    if( NPERR_NO_ERROR == status )
    {
        instance->pdata = reinterpret_cast<void*>(p_plugin);
    }
    else
    {
        delete p_plugin;
    }
    return status;
}

NPError NPP_Destroy( NPP instance, NPSavedData** )
{
    if( NULL == instance )
        return NPERR_INVALID_INSTANCE_ERROR;

    VlcPluginBase *p_plugin = reinterpret_cast<VlcPluginBase *>(instance->pdata);
    if( NULL == p_plugin )
        return NPERR_NO_ERROR;

    instance->pdata = NULL;

    if( p_plugin->playlist_isplaying() )
        p_plugin->playlist_stop();

    delete p_plugin;

    return NPERR_NO_ERROR;
}

NPError NPP_SetWindow( NPP instance, NPWindow* window )
{
    if( ! instance )
    {
        return NPERR_INVALID_INSTANCE_ERROR;
    }

    /* NPP_SetWindow may be called before NPP_New (Opera) */
    VlcPluginBase *p_plugin = reinterpret_cast<VlcPluginBase *>(instance->pdata);
    if( NULL == p_plugin )
    {
        /* we should probably show a splash screen here */
        return NPERR_NO_ERROR;
    }

    p_plugin->getVLC();

    /*
     * PLUGIN DEVELOPERS:
     *  Before setting window to point to the
     *  new window, you may wish to compare the new window
     *  info to the previous window (if any) to note window
     *  size changes, etc.
     */

    /* retrieve current window */
    NPWindow& curr_window = p_plugin->getWindow();

    if (window/* && window->window */) {
    	::DebugStr((const unsigned char*)"vlcshell: received window object from browser");
        if (!curr_window.window) {
        	::DebugStr((const unsigned char*)"vlcshell: no current window");
            /* we've just been created */
            p_plugin->setWindow(*window);
            p_plugin->create_windows();
            p_plugin->resize_windows();
            p_plugin->set_player_window();

            /* now set plugin state to that requested in parameters */
            bool show_toolbar = p_plugin->get_options().get_show_toolbar();
            p_plugin->set_toolbar_visible( show_toolbar );

            /* handle streams properly */
            if( !p_plugin->b_stream )
            {
                if( p_plugin->psz_target )
                {
                    if( p_plugin->playlist_add( p_plugin->psz_target ) != -1 )
                    {
                        if( p_plugin->get_options().get_autoplay() )
                        {
                            p_plugin->playlist_play();
                        }
                    }
                    p_plugin->b_stream = true;
                }
            }

            p_plugin->update_controls();
        } else {
            if (window->window == curr_window.window) {
                ::DebugStr((const unsigned char*)"Already have current window, and new window is the same");
                /* resize / move notification */
                p_plugin->setWindow(*window);
                p_plugin->resize_windows();
            } else {
                /* plugin parent window was changed, notify plugin about it */
            	::DebugStr((const unsigned char*)"Already have current window, but new window is different");
                p_plugin->destroy_windows();
                p_plugin->setWindow(*window);
                p_plugin->create_windows();
                p_plugin->resize_windows();
            }
        }
    } else {
        /* NOTE: on Windows, Opera does not call NPP_SetWindow
         * on window destruction. */
    	::DebugStr((const unsigned char*)"vlcshell: received no window object from browser");
        if (curr_window.window) {
            /* we've been destroyed */
            p_plugin->destroy_windows();
        }
    }
    return NPERR_NO_ERROR;
}

NPError NPP_NewStream( NPP instance, NPMIMEType, NPStream *stream,
                       NPBool, NPuint16_t *stype )
{
    if( NULL == instance  )
    {
        return NPERR_INVALID_INSTANCE_ERROR;
    }

    VlcPluginBase *p_plugin = reinterpret_cast<VlcPluginBase *>(instance->pdata);
    if( NULL == p_plugin )
    {
        return NPERR_INVALID_INSTANCE_ERROR;
    }

   /*
   ** Firefox/Mozilla may decide to open a stream from the URL specified
   ** in the SRC parameter of the EMBED tag and pass it to us
   **
   ** since VLC will open the SRC URL as well, we're not interested in
   ** that stream. Otherwise, we'll take it and queue it up in the playlist
   */
    if( !p_plugin->psz_target || strcmp(stream->url, p_plugin->psz_target) )
    {
        /* TODO: use pipes !!!! */
        *stype = NP_ASFILEONLY;
        return NPERR_NO_ERROR;
    }
    return NPERR_GENERIC_ERROR;
}

NPint32_t NPP_WriteReady( NPP, NPStream *)
{
    /* TODO */
    return 8*1024;
}

NPint32_t NPP_Write( NPP, NPStream *, NPint32_t,
                 NPint32_t len, void * )
{
    /* TODO */
    return len;
}

NPError NPP_DestroyStream( NPP instance, NPStream *, NPError )
{
    if( instance == NULL )
    {
        return NPERR_INVALID_INSTANCE_ERROR;
    }
    return NPERR_NO_ERROR;
}

void NPP_StreamAsFile( NPP instance, NPStream *stream, const char* )
{
    if( instance == NULL )
    {
        return;
    }

    VlcPluginBase *p_plugin = reinterpret_cast<VlcPluginBase *>(instance->pdata);
    if( NULL == p_plugin )
    {
        return;
    }

    if( p_plugin->playlist_add( stream->url ) != -1 )
    {
        if( p_plugin->get_options().get_autoplay() )
        {
            p_plugin->playlist_play();
        }
    }
}

void NPP_URLNotify( NPP instance, const char* ,
                    NPReason, void* )
{
    /***** Insert NPP_URLNotify code here *****\
    PluginInstance* p_plugin;
    if (instance != NULL)
        p_plugin = (PluginInstance*) instance->pdata;
    \*********************************************/
}

void NPP_Print( NPP instance, NPPrint* printInfo )
{
    if( printInfo == NULL )
    {
        return;
    }

    if( instance != NULL )
    {
        /***** Insert NPP_Print code here *****\
        PluginInstance* p_plugin = (PluginInstance*) instance->pdata;
        \**************************************/

        if( printInfo->mode == NP_FULL )
        {
            /*
             * PLUGIN DEVELOPERS:
             *  If your plugin would like to take over
             *  printing completely when it is in full-screen mode,
             *  set printInfo->pluginPrinted to TRUE and print your
             *  plugin as you see fit.  If your plugin wants Netscape
             *  to handle printing in this case, set
             *  printInfo->pluginPrinted to FALSE (the default) and
             *  do nothing.  If you do want to handle printing
             *  yourself, printOne is true if the print button
             *  (as opposed to the print menu) was clicked.
             *  On the Macintosh, platformPrint is a THPrint; on
             *  Windows, platformPrint is a structure
             *  (defined in npapi.h) containing the printer name, port,
             *  etc.
             */

            /***** Insert NPP_Print code here *****\
            void* platformPrint =
                printInfo->print.fullPrint.platformPrint;
            NPBool printOne =
                printInfo->print.fullPrint.printOne;
            \**************************************/

            /* Do the default*/
            printInfo->print.fullPrint.pluginPrinted = false;
        }
        else
        {
            /* If not fullscreen, we must be embedded */
            /*
             * PLUGIN DEVELOPERS:
             *  If your plugin is embedded, or is full-screen
             *  but you returned false in pluginPrinted above, NPP_Print
             *  will be called with mode == NP_EMBED.  The NPWindow
             *  in the printInfo gives the location and dimensions of
             *  the embedded plugin on the printed page.  On the
             *  Macintosh, platformPrint is the printer port; on
             *  Windows, platformPrint is the handle to the printing
             *  device context.
             */

            /***** Insert NPP_Print code here *****\
            NPWindow* printWindow =
                &(printInfo->print.embedPrint.window);
            void* platformPrint =
                printInfo->print.embedPrint.platformPrint;
            \**************************************/
        }
    }
}
<commit_msg>Fix build<commit_after>/*****************************************************************************
 * vlcshell.cpp: a VLC plugin for Mozilla
 *****************************************************************************
 * Copyright (C) 2002-2009 the VideoLAN team
 * $Id$
 *
 * Authors: Samuel Hocevar <sam@zoy.org>
 *          Jean-Paul Saman <jpsaman@videolan.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

/*****************************************************************************
 * Preamble
 *****************************************************************************/

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "vlcplugin.h"
#include "vlcshell.h"

/******************************************************************************
 * UNIX-only API calls
 *****************************************************************************/
NPP_GET_MIME_CONST char * NPP_GetMIMEDescription( void )
{
    return mimetype;
}

NPError NPP_GetValue( NPP instance, NPPVariable variable, void *value )
{
    static char psz_name[] = PLUGIN_NAME;
    static char psz_desc[1000];

    /* plugin class variables */
    switch( variable )
    {
        case NPPVpluginNameString:
            *((char **)value) = psz_name;
            return NPERR_NO_ERROR;

        case NPPVpluginDescriptionString:
            snprintf( psz_desc, sizeof(psz_desc), PLUGIN_DESCRIPTION,
                      libvlc_get_version() );
            *((char **)value) = psz_desc;
            return NPERR_NO_ERROR;

#if defined(XP_UNIX)
        case NPPVpluginNeedsXEmbed:
            *((bool *)value) = true;
            return NPERR_NO_ERROR;
#endif

        default:
            /* move on to instance variables ... */
            ;
    }

    if( instance == NULL )
    {
        return NPERR_INVALID_INSTANCE_ERROR;
    }

    /* plugin instance variables */

    VlcPluginBase *p_plugin = reinterpret_cast<VlcPluginBase *>(instance->pdata);
    if( NULL == p_plugin )
    {
        /* plugin has not been initialized yet ! */
        return NPERR_INVALID_INSTANCE_ERROR;
    }

    switch( variable )
    {
        case NPPVpluginScriptableNPObject:
        {
            /* retrieve plugin root class */
            NPClass *scriptClass = p_plugin->getScriptClass();
            if( scriptClass )
            {
                /* create an instance and return it */
                *(NPObject**)value = NPN_CreateObject(instance, scriptClass);
                return NPERR_NO_ERROR;
            }
            break;
        }

        default:
            ;
    }
    return NPERR_GENERIC_ERROR;
}

/*
 * there is some confusion in gecko headers regarding definition of this API
 * NPPVariable is wrongly defined as NPNVariable, which sounds incorrect.
 */

NPError NPP_SetValue( NPP, NPNVariable, void * )
{
    return NPERR_GENERIC_ERROR;
}

/******************************************************************************
 * Mac-only API calls
 *****************************************************************************/
#ifdef XP_MACOSX
int16_t NPP_HandleEvent( NPP instance, void * event )
{
    static UInt32 lastMouseUp = 0;
    if( instance == NULL )
    {
        return false;
    }

    VlcPluginBase *p_plugin = reinterpret_cast<VlcPluginBase *>(instance->pdata);
    if( p_plugin == NULL )
    {
        return false;
    }

// FIXME: implement Cocoa event model, by porting this legacy code:
/*
    EventRecord *myEvent = (EventRecord*)event;

    switch( myEvent->what )
    {
        case nullEvent:
            return true;
        case mouseDown:
        {
            if( (myEvent->when - lastMouseUp) < GetDblTime() )
            {
                // double click
                p_plugin->toggle_fullscreen();
            }
            return true;
        }
        case mouseUp:
            lastMouseUp = myEvent->when;
            return true;
        case keyUp:
        case keyDown:
        case autoKey:
            return true;
        case updateEvt:
        {
            const NPWindow& npwindow = p_plugin->getWindow();
            if( npwindow.window )
            {
                bool hasVout = false;

                if( p_plugin->playlist_isplaying() )
                {
                    hasVout = p_plugin->player_has_vout();
#if 0
                    if( hasVout )
                    {
                        libvlc_rectangle_t area;
                        area.left = 0;
                        area.top = 0;
                        area.right = npwindow.width;
                        area.bottom = npwindow.height;
                        libvlc_video_redraw_rectangle(p_plugin->getMD(), &area, NULL);
                    }
#else
#warning disabled code
#endif
                }

                if( ! hasVout )
                {
                    // draw the text from get_bg_text()
                    ForeColor(blackColor);
                    PenMode( patCopy );

                    // seems that firefox forgets to set the following
                    // on occasion (reload)
                    SetOrigin(((NP_Port *)npwindow.window)->portx,
                              ((NP_Port *)npwindow.window)->porty);

                    Rect rect;
                    rect.left = 0;
                    rect.top = 0;
                    rect.right = npwindow.width;
                    rect.bottom = npwindow.height;
                    PaintRect( &rect );

                    ForeColor(whiteColor);
                    MoveTo( (npwindow.width-80)/ 2  , npwindow.height / 2 );
                    if( !p_plugin->get_bg_text().empty() )
                        DrawText( p_plugin->get_bg_text().c_str(), 0, p_plugin->get_bg_text().length() );
                }
            }
            return true;
        }
        case activateEvt:
            return false;
        case NPEventType_GetFocusEvent:
        case NPEventType_LoseFocusEvent:
            return true;
        case NPEventType_AdjustCursorEvent:
            return false;
        case NPEventType_MenuCommandEvent:
            return false;
        case NPEventType_ClippingChangedEvent:
            return false;
        case NPEventType_ScrollingBeginsEvent:
            return true;
        case NPEventType_ScrollingEndsEvent:
            return true;
        default:
            ;
    }
*/
    return false;
}
#endif /* XP_MACOSX */

/******************************************************************************
 * General Plug-in Calls
 *****************************************************************************/
NPError NPP_Initialize( void )
{
#ifdef XP_UNIX
    NPError err = NPERR_NO_ERROR;
    bool supportsXEmbed = false;

    err = NPN_GetValue( NULL, NPNVSupportsXEmbedBool,
                        (void *)&supportsXEmbed );

    if ( err != NPERR_NO_ERROR || supportsXEmbed != true )
        return NPERR_INCOMPATIBLE_VERSION_ERROR;
#endif

    return NPERR_NO_ERROR;
}

#ifdef OJI
jref NPP_GetJavaClass( void )
{
    return NULL;
}
#endif

void NPP_Shutdown( void )
{
    ;
}

NPError NPP_New( NPMIMEType, NPP instance,
                 NPuint16_t mode, NPint16_t argc,
                 char* argn[], char* argv[], NPSavedData* )
{
    NPError status;

    if( instance == NULL )
    {
        return NPERR_INVALID_INSTANCE_ERROR;
    }

    VlcPluginBase *p_plugin = new VlcPlugin( instance, mode );
    if( NULL == p_plugin )
    {
        return NPERR_OUT_OF_MEMORY_ERROR;
    }

    status = p_plugin->init(argc, argn, argv);
    if( NPERR_NO_ERROR == status )
    {
        instance->pdata = reinterpret_cast<void*>(p_plugin);
    }
    else
    {
        delete p_plugin;
    }
    return status;
}

NPError NPP_Destroy( NPP instance, NPSavedData** )
{
    if( NULL == instance )
        return NPERR_INVALID_INSTANCE_ERROR;

    VlcPluginBase *p_plugin = reinterpret_cast<VlcPluginBase *>(instance->pdata);
    if( NULL == p_plugin )
        return NPERR_NO_ERROR;

    instance->pdata = NULL;

    if( p_plugin->playlist_isplaying() )
        p_plugin->playlist_stop();

    delete p_plugin;

    return NPERR_NO_ERROR;
}

NPError NPP_SetWindow( NPP instance, NPWindow* window )
{
    if( ! instance )
    {
        return NPERR_INVALID_INSTANCE_ERROR;
    }

    /* NPP_SetWindow may be called before NPP_New (Opera) */
    VlcPluginBase *p_plugin = reinterpret_cast<VlcPluginBase *>(instance->pdata);
    if( NULL == p_plugin )
    {
        /* we should probably show a splash screen here */
        return NPERR_NO_ERROR;
    }

    p_plugin->getVLC();

    /*
     * PLUGIN DEVELOPERS:
     *  Before setting window to point to the
     *  new window, you may wish to compare the new window
     *  info to the previous window (if any) to note window
     *  size changes, etc.
     */

    /* retrieve current window */
    NPWindow& curr_window = p_plugin->getWindow();

    if (window/* && window->window */) {
        if (!curr_window.window) {
            /* we've just been created */
            p_plugin->setWindow(*window);
            p_plugin->create_windows();
            p_plugin->resize_windows();
            p_plugin->set_player_window();

            /* now set plugin state to that requested in parameters */
            bool show_toolbar = p_plugin->get_options().get_show_toolbar();
            p_plugin->set_toolbar_visible( show_toolbar );

            /* handle streams properly */
            if( !p_plugin->b_stream )
            {
                if( p_plugin->psz_target )
                {
                    if( p_plugin->playlist_add( p_plugin->psz_target ) != -1 )
                    {
                        if( p_plugin->get_options().get_autoplay() )
                        {
                            p_plugin->playlist_play();
                        }
                    }
                    p_plugin->b_stream = true;
                }
            }

            p_plugin->update_controls();
        } else {
            if (window->window == curr_window.window) {
                /* resize / move notification */
                p_plugin->setWindow(*window);
                p_plugin->resize_windows();
            } else {
                /* plugin parent window was changed, notify plugin about it */
                p_plugin->destroy_windows();
                p_plugin->setWindow(*window);
                p_plugin->create_windows();
                p_plugin->resize_windows();
            }
        }
    } else {
        /* NOTE: on Windows, Opera does not call NPP_SetWindow
         * on window destruction. */
        if (curr_window.window) {
            /* we've been destroyed */
            p_plugin->destroy_windows();
        }
    }
    return NPERR_NO_ERROR;
}

NPError NPP_NewStream( NPP instance, NPMIMEType, NPStream *stream,
                       NPBool, NPuint16_t *stype )
{
    if( NULL == instance  )
    {
        return NPERR_INVALID_INSTANCE_ERROR;
    }

    VlcPluginBase *p_plugin = reinterpret_cast<VlcPluginBase *>(instance->pdata);
    if( NULL == p_plugin )
    {
        return NPERR_INVALID_INSTANCE_ERROR;
    }

   /*
   ** Firefox/Mozilla may decide to open a stream from the URL specified
   ** in the SRC parameter of the EMBED tag and pass it to us
   **
   ** since VLC will open the SRC URL as well, we're not interested in
   ** that stream. Otherwise, we'll take it and queue it up in the playlist
   */
    if( !p_plugin->psz_target || strcmp(stream->url, p_plugin->psz_target) )
    {
        /* TODO: use pipes !!!! */
        *stype = NP_ASFILEONLY;
        return NPERR_NO_ERROR;
    }
    return NPERR_GENERIC_ERROR;
}

NPint32_t NPP_WriteReady( NPP, NPStream *)
{
    /* TODO */
    return 8*1024;
}

NPint32_t NPP_Write( NPP, NPStream *, NPint32_t,
                 NPint32_t len, void * )
{
    /* TODO */
    return len;
}

NPError NPP_DestroyStream( NPP instance, NPStream *, NPError )
{
    if( instance == NULL )
    {
        return NPERR_INVALID_INSTANCE_ERROR;
    }
    return NPERR_NO_ERROR;
}

void NPP_StreamAsFile( NPP instance, NPStream *stream, const char* )
{
    if( instance == NULL )
    {
        return;
    }

    VlcPluginBase *p_plugin = reinterpret_cast<VlcPluginBase *>(instance->pdata);
    if( NULL == p_plugin )
    {
        return;
    }

    if( p_plugin->playlist_add( stream->url ) != -1 )
    {
        if( p_plugin->get_options().get_autoplay() )
        {
            p_plugin->playlist_play();
        }
    }
}

void NPP_URLNotify( NPP instance, const char* ,
                    NPReason, void* )
{
    /***** Insert NPP_URLNotify code here *****\
    PluginInstance* p_plugin;
    if (instance != NULL)
        p_plugin = (PluginInstance*) instance->pdata;
    \*********************************************/
}

void NPP_Print( NPP instance, NPPrint* printInfo )
{
    if( printInfo == NULL )
    {
        return;
    }

    if( instance != NULL )
    {
        /***** Insert NPP_Print code here *****\
        PluginInstance* p_plugin = (PluginInstance*) instance->pdata;
        \**************************************/

        if( printInfo->mode == NP_FULL )
        {
            /*
             * PLUGIN DEVELOPERS:
             *  If your plugin would like to take over
             *  printing completely when it is in full-screen mode,
             *  set printInfo->pluginPrinted to TRUE and print your
             *  plugin as you see fit.  If your plugin wants Netscape
             *  to handle printing in this case, set
             *  printInfo->pluginPrinted to FALSE (the default) and
             *  do nothing.  If you do want to handle printing
             *  yourself, printOne is true if the print button
             *  (as opposed to the print menu) was clicked.
             *  On the Macintosh, platformPrint is a THPrint; on
             *  Windows, platformPrint is a structure
             *  (defined in npapi.h) containing the printer name, port,
             *  etc.
             */

            /***** Insert NPP_Print code here *****\
            void* platformPrint =
                printInfo->print.fullPrint.platformPrint;
            NPBool printOne =
                printInfo->print.fullPrint.printOne;
            \**************************************/

            /* Do the default*/
            printInfo->print.fullPrint.pluginPrinted = false;
        }
        else
        {
            /* If not fullscreen, we must be embedded */
            /*
             * PLUGIN DEVELOPERS:
             *  If your plugin is embedded, or is full-screen
             *  but you returned false in pluginPrinted above, NPP_Print
             *  will be called with mode == NP_EMBED.  The NPWindow
             *  in the printInfo gives the location and dimensions of
             *  the embedded plugin on the printed page.  On the
             *  Macintosh, platformPrint is the printer port; on
             *  Windows, platformPrint is the handle to the printing
             *  device context.
             */

            /***** Insert NPP_Print code here *****\
            NPWindow* printWindow =
                &(printInfo->print.embedPrint.window);
            void* platformPrint =
                printInfo->print.embedPrint.platformPrint;
            \**************************************/
        }
    }
}
<|endoftext|>


<commit_before>// A set of classes deriving from TTask
// see macro tasks.C to see an example of use
// The Exec function of each class prints one line when it is called.
//Author: Rene Brun

#include "TTask.h"

class MyRun : public TTask {

public:
   MyRun() {;}
   MyRun(const char *name, const char *title);
   virtual ~MyRun() {;}
   void Exec(Option_t *option="");

   ClassDef(MyRun,1)   // Run Reconstruction task
};

class MyEvent : public TTask {

public:
   MyEvent() {;}
   MyEvent(const char *name, const char *title);
   virtual ~MyEvent() {;}
   void Exec(Option_t *option="");

   ClassDef(MyEvent,1)   // Event Reconstruction task
};

class MyGeomInit : public TTask {

public:
   MyGeomInit() {;}
   MyGeomInit(const char *name, const char *title);
   virtual ~MyGeomInit() {;}
   void Exec(Option_t *option="");

   ClassDef(MyGeomInit,1)   // Geometry initialisation task
};

class MyMaterialInit : public TTask {

public:
   MyMaterialInit() {;}
   MyMaterialInit(const char *name, const char *title);
   virtual ~MyMaterialInit() {;}
   void Exec(Option_t *option="");

   ClassDef(MyMaterialInit,1)   // Materials initialisation task
};

class MyTracker : public TTask {

public:
   MyTracker() {;}
   MyTracker(const char *name, const char *title);
   virtual ~MyTracker() {;}
   void Exec(Option_t *option="");

   ClassDef(MyTracker,1)   // Main Reconstruction task
};

class MyRecTPC : public TTask {

public:
   MyRecTPC() {;}
   MyRecTPC(const char *name, const char *title);
   virtual ~MyRecTPC() {;}
   void Exec(Option_t *option="");

   ClassDef(MyRecTPC,1)   // TPC Reconstruction
};

class MyRecITS : public TTask {

public:
   MyRecITS() {;}
   MyRecITS(const char *name, const char *title);
   virtual ~MyRecITS() {;}
   void Exec(Option_t *option="");

   ClassDef(MyRecITS,1)   // ITS Reconstruction
};

class MyRecMUON : public TTask {

public:
   MyRecMUON() {;}
   MyRecMUON(const char *name, const char *title);
   virtual ~MyRecMUON() {;}
   void Exec(Option_t *option="");

   ClassDef(MyRecMUON,1)   // MUON Reconstruction
};

class MyRecPHOS : public TTask {

public:
   MyRecPHOS() {;}
   MyRecPHOS(const char *name, const char *title);
   virtual ~MyRecPHOS() {;}
   void Exec(Option_t *option="");

   ClassDef(MyRecPHOS,1)   // PHOS Reconstruction
};

class MyRecRICH : public TTask {

public:
   MyRecRICH() {;}
   MyRecRICH(const char *name, const char *title);
   virtual ~MyRecRICH() {;}
   void Exec(Option_t *option="");

   ClassDef(MyRecRICH,1)   // RICH Reconstruction
};

class MyRecTRD : public TTask {

public:
   MyRecTRD() {;}
   MyRecTRD(const char *name, const char *title);
   virtual ~MyRecTRD() {;}
   void Exec(Option_t *option="");

   ClassDef(MyRecTRD,1)   // TRD Reconstruction
};

class MyRecGlobal : public TTask {

public:
   MyRecGlobal() {;}
   MyRecGlobal(const char *name, const char *title);
   virtual ~MyRecGlobal() {;}
   void Exec(Option_t *option="");

   ClassDef(MyRecGlobal,1)   // Global Reconstruction
};

////////////////////////////////////////////////////////////////////////////////

ClassImp(MyRun)

MyRun::MyRun(const char *name, const char *title)
      :TTask(name,title)
{
}

void MyRun::Exec(Option_t * /*option*/)
{
   printf("MyRun executing\n");
}

////////////////////////////////////////////////////////////////////////////////

ClassImp(MyEvent)

MyEvent::MyEvent(const char *name, const char *title)
      :TTask(name,title)
{
}

void MyEvent::Exec(Option_t * /*option*/)
{
   printf("MyEvent executing\n");
}

////////////////////////////////////////////////////////////////////////////////

ClassImp(MyGeomInit)

MyGeomInit::MyGeomInit(const char *name, const char *title)
      :TTask(name,title)
{
}

void MyGeomInit::Exec(Option_t * /*option*/)
{
   printf("MyGeomInit executing\n");
}

////////////////////////////////////////////////////////////////////////////////

ClassImp(MyMaterialInit)

MyMaterialInit::MyMaterialInit(const char *name, const char *title)
      :TTask(name,title)
{
}

void MyMaterialInit::Exec(Option_t * /*option*/)
{
   printf("MyMaterialInit executing\n");
}

////////////////////////////////////////////////////////////////////////////////

ClassImp(MyTracker)

MyTracker::MyTracker(const char *name, const char *title)
      :TTask(name,title)
{
}

void MyTracker::Exec(Option_t * /*option*/)
{
   printf("MyTracker executing\n");
}

////////////////////////////////////////////////////////////////////////////////

ClassImp(MyRecTPC)

MyRecTPC::MyRecTPC(const char *name, const char *title)
      :TTask(name,title)
{
}

void MyRecTPC::Exec(Option_t * /*option*/)
{
   printf("MyRecTPC executing\n");
}

////////////////////////////////////////////////////////////////////////////////

ClassImp(MyRecITS)

MyRecITS::MyRecITS(const char *name, const char *title)
      :TTask(name,title)
{
}

void MyRecITS::Exec(Option_t * /*option*/)
{
   printf("MyRecITS executing\n");
}

////////////////////////////////////////////////////////////////////////////////

ClassImp(MyRecMUON)

MyRecMUON::MyRecMUON(const char *name, const char *title)
      :TTask(name,title)
{
}

void MyRecMUON::Exec(Option_t * /*option*/)
{
   printf("MyRecMUON executing\n");
}

////////////////////////////////////////////////////////////////////////////////

ClassImp(MyRecPHOS)

MyRecPHOS::MyRecPHOS(const char *name, const char *title)
      :TTask(name,title)
{
}

void MyRecPHOS::Exec(Option_t * /*option*/)
{
   printf("MyRecPHOS executing\n");
}

////////////////////////////////////////////////////////////////////////////////

ClassImp(MyRecRICH)

MyRecRICH::MyRecRICH(const char *name, const char *title)
      :TTask(name,title)
{
}

void MyRecRICH::Exec(Option_t * /*option*/)
{
   printf("MyRecRICH executing\n");
}

////////////////////////////////////////////////////////////////////////////////

ClassImp(MyRecTRD)

MyRecTRD::MyRecTRD(const char *name, const char *title)
      :TTask(name,title)
{
}

void MyRecTRD::Exec(Option_t * /*option*/)
{
   printf("MyRecTRD executing\n");
}

////////////////////////////////////////////////////////////////////////////////

ClassImp(MyRecGlobal)

MyRecGlobal::MyRecGlobal(const char *name, const char *title)
      :TTask(name,title)
{
}

void MyRecGlobal::Exec(Option_t * /*option*/)
{
   printf("MyRecGlobal executing\n");
}
<commit_msg>Doxygen formatting<commit_after>/// \file
/// \ingroup Tutorials
/// A set of classes deriving from TTask.
/// See macro tasks.C to see an example of use
/// The Exec function of each class prints one line when it is called.
///
/// \macro_code
///
/// \author Rene Brun

#include "TTask.h"

class MyRun : public TTask {

public:
   MyRun() {;}
   MyRun(const char *name, const char *title);
   virtual ~MyRun() {;}
   void Exec(Option_t *option="");

   ClassDef(MyRun,1)   // Run Reconstruction task
};

class MyEvent : public TTask {

public:
   MyEvent() {;}
   MyEvent(const char *name, const char *title);
   virtual ~MyEvent() {;}
   void Exec(Option_t *option="");

   ClassDef(MyEvent,1)   // Event Reconstruction task
};

class MyGeomInit : public TTask {

public:
   MyGeomInit() {;}
   MyGeomInit(const char *name, const char *title);
   virtual ~MyGeomInit() {;}
   void Exec(Option_t *option="");

   ClassDef(MyGeomInit,1)   // Geometry initialisation task
};

class MyMaterialInit : public TTask {

public:
   MyMaterialInit() {;}
   MyMaterialInit(const char *name, const char *title);
   virtual ~MyMaterialInit() {;}
   void Exec(Option_t *option="");

   ClassDef(MyMaterialInit,1)   // Materials initialisation task
};

class MyTracker : public TTask {

public:
   MyTracker() {;}
   MyTracker(const char *name, const char *title);
   virtual ~MyTracker() {;}
   void Exec(Option_t *option="");

   ClassDef(MyTracker,1)   // Main Reconstruction task
};

class MyRecTPC : public TTask {

public:
   MyRecTPC() {;}
   MyRecTPC(const char *name, const char *title);
   virtual ~MyRecTPC() {;}
   void Exec(Option_t *option="");

   ClassDef(MyRecTPC,1)   // TPC Reconstruction
};

class MyRecITS : public TTask {

public:
   MyRecITS() {;}
   MyRecITS(const char *name, const char *title);
   virtual ~MyRecITS() {;}
   void Exec(Option_t *option="");

   ClassDef(MyRecITS,1)   // ITS Reconstruction
};

class MyRecMUON : public TTask {

public:
   MyRecMUON() {;}
   MyRecMUON(const char *name, const char *title);
   virtual ~MyRecMUON() {;}
   void Exec(Option_t *option="");

   ClassDef(MyRecMUON,1)   // MUON Reconstruction
};

class MyRecPHOS : public TTask {

public:
   MyRecPHOS() {;}
   MyRecPHOS(const char *name, const char *title);
   virtual ~MyRecPHOS() {;}
   void Exec(Option_t *option="");

   ClassDef(MyRecPHOS,1)   // PHOS Reconstruction
};

class MyRecRICH : public TTask {

public:
   MyRecRICH() {;}
   MyRecRICH(const char *name, const char *title);
   virtual ~MyRecRICH() {;}
   void Exec(Option_t *option="");

   ClassDef(MyRecRICH,1)   // RICH Reconstruction
};

class MyRecTRD : public TTask {

public:
   MyRecTRD() {;}
   MyRecTRD(const char *name, const char *title);
   virtual ~MyRecTRD() {;}
   void Exec(Option_t *option="");

   ClassDef(MyRecTRD,1)   // TRD Reconstruction
};

class MyRecGlobal : public TTask {

public:
   MyRecGlobal() {;}
   MyRecGlobal(const char *name, const char *title);
   virtual ~MyRecGlobal() {;}
   void Exec(Option_t *option="");

   ClassDef(MyRecGlobal,1)   // Global Reconstruction
};

////////////////////////////////////////////////////////////////////////////////

ClassImp(MyRun)

MyRun::MyRun(const char *name, const char *title)
      :TTask(name,title)
{
}

void MyRun::Exec(Option_t * /*option*/)
{
   printf("MyRun executing\n");
}

////////////////////////////////////////////////////////////////////////////////

ClassImp(MyEvent)

MyEvent::MyEvent(const char *name, const char *title)
      :TTask(name,title)
{
}

void MyEvent::Exec(Option_t * /*option*/)
{
   printf("MyEvent executing\n");
}

////////////////////////////////////////////////////////////////////////////////

ClassImp(MyGeomInit)

MyGeomInit::MyGeomInit(const char *name, const char *title)
      :TTask(name,title)
{
}

void MyGeomInit::Exec(Option_t * /*option*/)
{
   printf("MyGeomInit executing\n");
}

////////////////////////////////////////////////////////////////////////////////

ClassImp(MyMaterialInit)

MyMaterialInit::MyMaterialInit(const char *name, const char *title)
      :TTask(name,title)
{
}

void MyMaterialInit::Exec(Option_t * /*option*/)
{
   printf("MyMaterialInit executing\n");
}

////////////////////////////////////////////////////////////////////////////////

ClassImp(MyTracker)

MyTracker::MyTracker(const char *name, const char *title)
      :TTask(name,title)
{
}

void MyTracker::Exec(Option_t * /*option*/)
{
   printf("MyTracker executing\n");
}

////////////////////////////////////////////////////////////////////////////////

ClassImp(MyRecTPC)

MyRecTPC::MyRecTPC(const char *name, const char *title)
      :TTask(name,title)
{
}

void MyRecTPC::Exec(Option_t * /*option*/)
{
   printf("MyRecTPC executing\n");
}

////////////////////////////////////////////////////////////////////////////////

ClassImp(MyRecITS)

MyRecITS::MyRecITS(const char *name, const char *title)
      :TTask(name,title)
{
}

void MyRecITS::Exec(Option_t * /*option*/)
{
   printf("MyRecITS executing\n");
}

////////////////////////////////////////////////////////////////////////////////

ClassImp(MyRecMUON)

MyRecMUON::MyRecMUON(const char *name, const char *title)
      :TTask(name,title)
{
}

void MyRecMUON::Exec(Option_t * /*option*/)
{
   printf("MyRecMUON executing\n");
}

////////////////////////////////////////////////////////////////////////////////

ClassImp(MyRecPHOS)

MyRecPHOS::MyRecPHOS(const char *name, const char *title)
      :TTask(name,title)
{
}

void MyRecPHOS::Exec(Option_t * /*option*/)
{
   printf("MyRecPHOS executing\n");
}

////////////////////////////////////////////////////////////////////////////////

ClassImp(MyRecRICH)

MyRecRICH::MyRecRICH(const char *name, const char *title)
      :TTask(name,title)
{
}

void MyRecRICH::Exec(Option_t * /*option*/)
{
   printf("MyRecRICH executing\n");
}

////////////////////////////////////////////////////////////////////////////////

ClassImp(MyRecTRD)

MyRecTRD::MyRecTRD(const char *name, const char *title)
      :TTask(name,title)
{
}

void MyRecTRD::Exec(Option_t * /*option*/)
{
   printf("MyRecTRD executing\n");
}

////////////////////////////////////////////////////////////////////////////////

ClassImp(MyRecGlobal)

MyRecGlobal::MyRecGlobal(const char *name, const char *title)
      :TTask(name,title)
{
}

void MyRecGlobal::Exec(Option_t * /*option*/)
{
   printf("MyRecGlobal executing\n");
}
<|endoftext|>


<commit_before>/*---------------------------------------------------------------------\
|                                                                      |
|                     _     _   _   _     __     _                     |
|                    | |   | | | \_/ |   /  \   | |                    |
|                    | |   | | | |_| |  / /\ \  | |                    |
|                    | |__ | | | | | | / ____ \ | |__                  |
|                    |____||_| |_| |_|/ /    \ \|____|                 |
|                                                                      |
|                             ca-mgm library                           |
|                                                                      |
|                                         (C) SUSE Linux Products GmbH |
\----------------------------------------------------------------------/

  File:       CA.cpp

  Author:     <Michael Calmer>     <mc@suse.de>
  Maintainer: <Michael Calmer>     <mc@suse.de>

  Purpose:

/-*/

#include  <limal/ca-mgm/CA.hpp>
#include  <limal/Exception.hpp>
#include  <blocxx/Exec.hpp>
#include  <blocxx/EnvVars.hpp>

#include  "CertificateData_Priv.hpp"
#include  "RequestData_Priv.hpp"
#include  "CRLData_Priv.hpp"
#include  "CATools.h"
#include  "OPENSSL.h"

#include  "Utils.hpp"
#include  "Commands.hpp"

using namespace limal;
using namespace limal::ca_mgm;
using namespace blocxx;

CA::CA(const String& caName, const String& caPasswd, const String& repos)
    : caName(caName), caPasswd(caPasswd), repositoryDir(repos),
      config(NULL),
      templ(new CAConfig(repositoryDir+"/"+caName+"/openssl.cnf.tmpl"))
{
}

CA::~CA()
{
    StringArray cmd;
    cmd.push_back(RM_COMMAND);
    cmd.push_back(repositoryDir+"/"+caName+"/openssl.cnf");
    try {
        blocxx::Exec::safeSystem(cmd, blocxx::EnvVars());
    } catch(Exception &e) {
        // ignore errors
        LOGIT_INFO("Remove of openssl.cnf failed. " << e);
    }
}

bool
CA::createSubCA(const String& keyPasswd,
                const RequestGenerationData& caRequestData,
                const CertificateIssueData& ca)
{
    return false;
}

blocxx::String
CA::createRequest(const String& keyPasswd,
                  const RequestGenerationData& requestData)
{
    return String();
}

blocxx::String
CA::issueCertificate(const String& requestName,
                     const CertificateIssueData& issueData)
{
    return String();
}

blocxx::String
CA::createCertificate(const String& keyPasswd,
                      const RequestGenerationData& requestData,
                      const CertificateIssueData&  certificateData)
{
    return String();
}

bool
CA::revokeCertificate(const String& certificateName,
                      const CRLReason& crlReason)
{
    return false;
}

bool
CA::createCRL(const CRLGenerationData& crlData)
{
    return false;
}

blocxx::String
CA::importRequest(const ByteArray& request,
                  FormatType formatType)
{
    return String();
}

CertificateIssueData
CA::getIssueDefaults(Type type)
{
    initConfigFile();
    CertificateIssueData cid = CertificateIssueData(*this, type);
    return cid;
}

RequestGenerationData
CA::getRequestDefaults(Type type)
{
    initConfigFile();
    RequestGenerationData rgd = RequestGenerationData(*this, type);

    return rgd;
}

CRLGenerationData
CA::getCRLDefaults()
{
    initConfigFile();
    CRLGenerationData  crlgd = CRLGenerationData(*this, CRL);
    return crlgd;
}

bool
CA::setIssueDefaults(Type type,
                     const CertificateIssueData& defaults)
{
    initConfigFile();
    if(config) {
        defaults.commit2Config(*this, type);
        commitConfig2Template();
        return true;
    }
    return false;
}

bool
CA::setRequestDefaults(Type type,
                       const RequestGenerationData& defaults)
{
    initConfigFile();
    if(config) {
        defaults.commit2Config(*this, type);
        commitConfig2Template();
        return true;
    }
    return false;
}

bool
CA::setCRLDefaults(const CRLGenerationData& defaults)
{
    initConfigFile();
    if(config) {
        defaults.commit2Config(*this, CRL);
        commitConfig2Template();
        return true;
    }
    return false;
}

StringMapList
CA::getCertificateList()
{
    return StringMapList();
}

StringMapList
CA::getRequestList()
{
    return StringMapList();
}

CertificateData
CA::getCA()
{
    return CertificateData_Priv();
}

RequestData
CA::getRequest(const String& requestName)
{
    return RequestData_Priv();
}

CertificateData
CA::getCertificate(const String& certificateName)
{
    return CertificateData_Priv();
}

CRLData
CA::getCRL()
{
    return CRLData_Priv();
}

ByteArray
CA::exportCACert(FormatType exportType)
{
    return ByteArray();
}

ByteArray
CA::exportCAKey(bool encrypted)
{
    return ByteArray();
}

ByteArray
CA::exportCAasPKCS12(const String& p12Passwd,
                     bool withChain)
{
    return ByteArray();
}

ByteArray
CA::exportCertificate(const String& certificateName,
                      const String& keyPasswd,
                      FormatType exportType)
{
    return ByteArray();
}

ByteArray
CA::exportCertificateKey(const String& certificateName,
                         const String& keyPasswd,
                         bool encrypted)
{
    return ByteArray();
}

ByteArray
CA::exportCertificateasPKCS12(const String& certificateName,
                              const String& keyPasswd,
                              const String& p12Passwd,
                              bool withChain)
{
    return ByteArray();
}

ByteArray
CA::exportCRL(FormatType exportType)
{
    return ByteArray();
}

bool
CA::deleteCA(bool force)
{
    return false;
}

bool
CA::deleteRequest(const String& requestName)
{
    return false;
}

bool
CA::deleteCertificate(const String& certificateName)
{
    return false;
}

bool
CA::updateDB()
{
    return false;
}

bool
CA::verifyCertificate(const String& certificateName,
                      bool crlCheck,
                      CertificatePurpose purpose)
{
    return false;
}

void
CA::initConfigFile()
{
    if(templ) {
        config = templ->clone(repositoryDir+"/"+caName+"/openssl.cnf");
    } else {
        LOGIT_ERROR("template not initialized");
        BLOCXX_THROW(limal::RuntimeException, "template not initialized");
    }
}

void
CA::commitConfig2Template()
{
    if(config) {
        templ = config->clone(repositoryDir+"/"+caName+"/openssl.cnf.tmpl");
        delete config;
        config = NULL;
    } else {
        LOGIT_ERROR("config not initialized");
        BLOCXX_THROW(limal::RuntimeException, "config not initialized");
    }
}

CAConfig*
CA::getConfig()
{
    return config;
}

/* ##########################################################################
 * ###          static Functions                                          ###
 * ##########################################################################
 */

bool
CA::createRootCA(const String& caName,
                 const String& caPasswd,
                 const RequestGenerationData& caRequestData,
                 const CertificateIssueData& caIssueData,
                 const String& repos)
{
    // Create the infrastructure

    try {
        createCaInfrastructure(caName, repos);
    } catch(blocxx::Exception &e) {
        LOGIT_ERROR(e);
        BLOCXX_THROW_SUBEX(limal::SystemException,
                           "Error during create CA infrastructure",
                           e);
    }

    // Create CA Object
    CA tmpCA = CA(caName, caPasswd, repos);

    // copy template to config
    tmpCA.initConfigFile();

    // write request data to config
    caRequestData.commit2Config(tmpCA, CA_Req);

    blocxx::Map<blocxx::String,blocxx::String > hash;
    hash["BINARY"] = OPENSSL_COMMAND;
    hash["CONFIG"] = repos + "/" + caName + "/" + "openssl.cnf";;
    hash["DEBUG"] = "1";
    OPENSSL ossl(hash);

    // create key
    hash.clear();
    hash["OUTFILE"] = repos + "/" + caName + "/" + "cacert.key";
    hash["PASSWD"] = caPasswd;
    hash["BITS"] = String(caRequestData.getKeysize());
    //    hash[""] = "";
	blocxx::String k = ossl.createKey(hash);

    // create request
    hash.clear();
    hash["OUTFILE"] = repos + "/" + caName + "/" + "cacert.req";
    hash["KEYFILE"] = repos + "/" + caName + "/" + "cacert.key";
    hash["PASSWD"] = caPasswd;
    //hash[""] = "";

    blocxx::List<RDNObject> dn = caRequestData.getSubject().getDN();
    blocxx::List<RDNObject>::const_iterator it = dn.begin();
    blocxx::Array<blocxx::String> sdn;
    for(; it != dn.end(); ++it) {
        sdn.push_back( (*it).getValue() );
    }
    sdn.push_back(caRequestData.getChallengePassword());
    sdn.push_back(caRequestData.getUnstructuredName());

    k = ossl.createReq(&hash, &sdn);

    // write certificate issue data to config
    caIssueData.commit2Config(tmpCA, CA_Cert);

    // create the CA certificate
    hash.clear();
    hash["OUTFILE"] = repos + "/" + caName + "/" + "cacert.pem";
    hash["KEYFILE"] = repos + "/" + caName + "/" + "cacert.key";
    hash["REQFILE"] = repos + "/" + caName + "/" + "cacert.req";
    hash["PASSWD"]  = caPasswd;
    hash["DAYS"]    = String((caIssueData.getEndDate() - caIssueData.getStartDate()) /(60*60*24));

    k = ossl.createSelfSignedCert(hash);

    // some clean-ups
    StringArray cmd;
    cmd.push_back(CP_COMMAND);
    cmd.push_back(repos + "/" + caName + "/" + "cacert.pem");
    cmd.push_back(repos + "/" + ".cas/" + caName + ".pem");
    blocxx::Exec::safeSystem(cmd, blocxx::EnvVars());

    cmd.clear();
    cmd.push_back(C_REHASH_COMMAND);
    cmd.push_back(repos + "/" + ".cas/");

    blocxx::EnvVars env;
    env.addVar("PATH", "/usr/bin/");
    blocxx::Exec::safeSystem(cmd, env);

    return true;
}

bool
CA::importCA(const String& caName,
             const String& caCertificate,
             const String& cakey,
             const String& caPasswd)
{
    return false;
}

StringList
CA::getCAList()
{
    return StringList();
}

blocxx::List<StringList>
CA::getCATree()
{
    return List<StringList>();
}

//  private
CA::CA()
{
}

CA::CA(const CA&)
{
}

CA&
CA::operator=(const CA&)
{
    return *this;
}

<commit_msg>- use new PathUtils from limal core lib for cp and rm  - use blocxx::Exec::executeProcessAndGatherOutput for   executing commands<commit_after>/*---------------------------------------------------------------------\
|                                                                      |
|                     _     _   _   _     __     _                     |
|                    | |   | | | \_/ |   /  \   | |                    |
|                    | |   | | | |_| |  / /\ \  | |                    |
|                    | |__ | | | | | | / ____ \ | |__                  |
|                    |____||_| |_| |_|/ /    \ \|____|                 |
|                                                                      |
|                             ca-mgm library                           |
|                                                                      |
|                                         (C) SUSE Linux Products GmbH |
\----------------------------------------------------------------------/

  File:       CA.cpp

  Author:     <Michael Calmer>     <mc@suse.de>
  Maintainer: <Michael Calmer>     <mc@suse.de>

  Purpose:

/-*/

#include  <limal/ca-mgm/CA.hpp>
#include  <limal/Exception.hpp>
#include  <limal/PathUtils.hpp>
#include  <blocxx/Exec.hpp>
#include  <blocxx/EnvVars.hpp>

#include  "CertificateData_Priv.hpp"
#include  "RequestData_Priv.hpp"
#include  "CRLData_Priv.hpp"
#include  "CATools.h"
#include  "OPENSSL.h"

#include  "Utils.hpp"
#include  "Commands.hpp"

using namespace limal;
using namespace limal::ca_mgm;
using namespace blocxx;

CA::CA(const String& caName, const String& caPasswd, const String& repos)
    : caName(caName), caPasswd(caPasswd), repositoryDir(repos),
      config(NULL),
      templ(new CAConfig(repositoryDir+"/"+caName+"/openssl.cnf.tmpl"))
{
    //FIXME: check if caName is not empty
}

CA::~CA()
{
    int r = path::removeFile(repositoryDir+"/"+caName+"/openssl.cnf");

    if(r != 0) {
        LOGIT_INFO("Remove of openssl.cnf failed: " << r);
    }
}

bool
CA::createSubCA(const String& keyPasswd,
                const RequestGenerationData& caRequestData,
                const CertificateIssueData& ca)
{
    return false;
}

blocxx::String
CA::createRequest(const String& keyPasswd,
                  const RequestGenerationData& requestData)
{
    return String();
}

blocxx::String
CA::issueCertificate(const String& requestName,
                     const CertificateIssueData& issueData)
{
    return String();
}

blocxx::String
CA::createCertificate(const String& keyPasswd,
                      const RequestGenerationData& requestData,
                      const CertificateIssueData&  certificateData)
{
    return String();
}

bool
CA::revokeCertificate(const String& certificateName,
                      const CRLReason& crlReason)
{
    return false;
}

bool
CA::createCRL(const CRLGenerationData& crlData)
{
    return false;
}

blocxx::String
CA::importRequest(const ByteArray& request,
                  FormatType formatType)
{
    return String();
}

CertificateIssueData
CA::getIssueDefaults(Type type)
{
    initConfigFile();
    CertificateIssueData cid = CertificateIssueData(*this, type);
    return cid;
}

RequestGenerationData
CA::getRequestDefaults(Type type)
{
    initConfigFile();
    RequestGenerationData rgd = RequestGenerationData(*this, type);

    return rgd;
}

CRLGenerationData
CA::getCRLDefaults()
{
    initConfigFile();
    CRLGenerationData  crlgd = CRLGenerationData(*this, CRL);
    return crlgd;
}

bool
CA::setIssueDefaults(Type type,
                     const CertificateIssueData& defaults)
{
    initConfigFile();
    if(config) {
        defaults.commit2Config(*this, type);
        commitConfig2Template();
        return true;
    }
    return false;
}

bool
CA::setRequestDefaults(Type type,
                       const RequestGenerationData& defaults)
{
    initConfigFile();
    if(config) {
        defaults.commit2Config(*this, type);
        commitConfig2Template();
        return true;
    }
    return false;
}

bool
CA::setCRLDefaults(const CRLGenerationData& defaults)
{
    initConfigFile();
    if(config) {
        defaults.commit2Config(*this, CRL);
        commitConfig2Template();
        return true;
    }
    return false;
}

StringMapList
CA::getCertificateList()
{
    return StringMapList();
}

StringMapList
CA::getRequestList()
{
    return StringMapList();
}

CertificateData
CA::getCA()
{
    return CertificateData_Priv();
}

RequestData
CA::getRequest(const String& requestName)
{
    return RequestData_Priv();
}

CertificateData
CA::getCertificate(const String& certificateName)
{
    return CertificateData_Priv();
}

CRLData
CA::getCRL()
{
    return CRLData_Priv();
}

ByteArray
CA::exportCACert(FormatType exportType)
{
    return ByteArray();
}

ByteArray
CA::exportCAKey(bool encrypted)
{
    return ByteArray();
}

ByteArray
CA::exportCAasPKCS12(const String& p12Passwd,
                     bool withChain)
{
    return ByteArray();
}

ByteArray
CA::exportCertificate(const String& certificateName,
                      const String& keyPasswd,
                      FormatType exportType)
{
    return ByteArray();
}

ByteArray
CA::exportCertificateKey(const String& certificateName,
                         const String& keyPasswd,
                         bool encrypted)
{
    return ByteArray();
}

ByteArray
CA::exportCertificateasPKCS12(const String& certificateName,
                              const String& keyPasswd,
                              const String& p12Passwd,
                              bool withChain)
{
    return ByteArray();
}

ByteArray
CA::exportCRL(FormatType exportType)
{
    return ByteArray();
}

bool
CA::deleteCA(bool force)
{
    return false;
}

bool
CA::deleteRequest(const String& requestName)
{
    return false;
}

bool
CA::deleteCertificate(const String& certificateName)
{
    return false;
}

bool
CA::updateDB()
{
    return false;
}

bool
CA::verifyCertificate(const String& certificateName,
                      bool crlCheck,
                      CertificatePurpose purpose)
{
    return false;
}

void
CA::initConfigFile()
{
    if(templ) {
        config = templ->clone(repositoryDir+"/"+caName+"/openssl.cnf");
    } else {
        LOGIT_ERROR("template not initialized");
        BLOCXX_THROW(limal::RuntimeException, "template not initialized");
    }
}

void
CA::commitConfig2Template()
{
    if(config) {
        templ = config->clone(repositoryDir+"/"+caName+"/openssl.cnf.tmpl");
        delete config;
        config = NULL;
    } else {
        LOGIT_ERROR("config not initialized");
        BLOCXX_THROW(limal::RuntimeException, "config not initialized");
    }
}

CAConfig*
CA::getConfig()
{
    return config;
}

/* ##########################################################################
 * ###          static Functions                                          ###
 * ##########################################################################
 */

bool
CA::createRootCA(const String& caName,
                 const String& caPasswd,
                 const RequestGenerationData& caRequestData,
                 const CertificateIssueData& caIssueData,
                 const String& repos)
{
    // Create the infrastructure

    try {
        createCaInfrastructure(caName, repos);
    } catch(blocxx::Exception &e) {
        LOGIT_ERROR(e);
        BLOCXX_THROW_SUBEX(limal::SystemException,
                           "Error during create CA infrastructure",
                           e);
    }

    // Create CA Object
    CA tmpCA = CA(caName, caPasswd, repos);

    // copy template to config
    tmpCA.initConfigFile();

    // write request data to config
    caRequestData.commit2Config(tmpCA, CA_Req);

    blocxx::Map<blocxx::String,blocxx::String > hash;
    hash["BINARY"] = OPENSSL_COMMAND;
    hash["CONFIG"] = repos + "/" + caName + "/" + "openssl.cnf";;
    hash["DEBUG"] = "1";
    OPENSSL ossl(hash);

    // create key
    hash.clear();
    hash["OUTFILE"] = repos + "/" + caName + "/" + "cacert.key";
    hash["PASSWD"] = caPasswd;
    hash["BITS"] = String(caRequestData.getKeysize());
    //    hash[""] = "";
	blocxx::String k = ossl.createKey(hash);

    // create request
    hash.clear();
    hash["OUTFILE"] = repos + "/" + caName + "/" + "cacert.req";
    hash["KEYFILE"] = repos + "/" + caName + "/" + "cacert.key";
    hash["PASSWD"] = caPasswd;
    //hash[""] = "";

    blocxx::List<RDNObject> dn = caRequestData.getSubject().getDN();
    blocxx::List<RDNObject>::const_iterator it = dn.begin();
    blocxx::Array<blocxx::String> sdn;
    for(; it != dn.end(); ++it) {
        sdn.push_back( (*it).getValue() );
    }
    sdn.push_back(caRequestData.getChallengePassword());
    sdn.push_back(caRequestData.getUnstructuredName());

    k = ossl.createReq(&hash, &sdn);

    // write certificate issue data to config
    caIssueData.commit2Config(tmpCA, CA_Cert);

    // create the CA certificate
    hash.clear();
    hash["OUTFILE"] = repos + "/" + caName + "/" + "cacert.pem";
    hash["KEYFILE"] = repos + "/" + caName + "/" + "cacert.key";
    hash["REQFILE"] = repos + "/" + caName + "/" + "cacert.req";
    hash["PASSWD"]  = caPasswd;
    hash["DAYS"]    = String((caIssueData.getEndDate() - caIssueData.getStartDate()) /(60*60*24));

    k = ossl.createSelfSignedCert(hash);

    // some clean-ups

    int r = path::copyFile(repos + "/" + caName + "/" + "cacert.pem",
                           repos + "/" + ".cas/" + caName + ".pem");

    if(r != 0) {
        LOGIT_INFO("Copy of cacert.pem to .cas/ failed: " << r);
    }

    StringArray cmd;
    cmd.push_back(C_REHASH_COMMAND);
    cmd.push_back(repos + "/" + ".cas/");

    blocxx::EnvVars env;
    env.addVar("PATH", "/usr/bin/");

    String stdOutput;
    String errOutput;
    int    status = 0;
    try {

        blocxx::Exec::executeProcessAndGatherOutput(cmd, stdOutput, errOutput, status, env);

    } catch(Exception& e) {
        LOGIT_INFO( "c_rehash exception:" << e);
        status = -1;
    }
    if(status != 0) {
        LOGIT_INFO( "c_rehash status:" << String(status));
    }
    if(!errOutput.empty()) {
        LOGIT_INFO("c_rehash stderr:" << errOutput);
    }
    if(!stdOutput.empty()) {
        LOGIT_DEBUG("c_rehash stdout:" << stdOutput);
    }
    return true;
}

bool
CA::importCA(const String& caName,
             const String& caCertificate,
             const String& cakey,
             const String& caPasswd)
{
    return false;
}

StringList
CA::getCAList()
{
    return StringList();
}

blocxx::List<StringList>
CA::getCATree()
{
    return List<StringList>();
}

//  private
CA::CA()
{
}

CA::CA(const CA&)
{
}

CA&
CA::operator=(const CA&)
{
    return *this;
}

<|endoftext|>


<commit_before>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2014, OpenNebula Project (OpenNebula.org), C12G Labs        */
/*                                                                            */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may    */
/* not use this file except in compliance with the License. You may obtain    */
/* a copy of the License at                                                   */
/*                                                                            */
/* http://www.apache.org/licenses/LICENSE-2.0                                 */
/*                                                                            */
/* Unless required by applicable law or agreed to in writing, software        */
/* distributed under the License is distributed on an "AS IS" BASIS,          */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   */
/* See the License for the specific language governing permissions and        */
/* limitations under the License.                                             */
/* -------------------------------------------------------------------------- */

#include "Log.h"

#include <string.h>
#include <stdlib.h>
#include <stdexcept>
#include <sstream>
#include <iostream>

#include <sys/types.h>
#include <unistd.h>

#ifdef SYSLOG_LOG
#   include <syslog.h>

#   include "log4cpp/Category.hh"
#   include "log4cpp/CategoryStream.hh"
#   include "log4cpp/Appender.hh"
#   include "log4cpp/SyslogAppender.hh"
#   include "log4cpp/Layout.hh"
#   include "log4cpp/PatternLayout.hh"
#   include "log4cpp/Priority.hh"
#endif /* SYSLOG_LOG */

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

const char Log::error_names[] ={ 'E', 'W', 'I', 'D' };

unsigned int Log::zone_id = 0;

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

FileLog::FileLog(const string&   file_name,
                 const MessageType   level,
                 ios_base::openmode  mode)
        :Log(level), log_file_name(file_name)
{
    ofstream file;

    file.open(log_file_name.c_str(), mode);

    if (file.fail() == true)
    {
        throw runtime_error("Could not open log file");
    }

    if ( file.is_open() == true )
    {
        file.close();
    }
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

FileLog::~FileLog() { }

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void FileLog::log(
    const char *            module,
    const MessageType       type,
    const char *            message)
{
    char        str[26];
    time_t      the_time;
    ofstream    file;

    if( type <= log_level)
    {
        file.open(log_file_name.c_str(), ios_base::app);

        if (file.fail() == true)
        {
            return;
        }

        the_time = time(NULL);

#ifdef SOLARIS
        ctime_r(&(the_time),str,sizeof(char)*26);
#else
        ctime_r(&(the_time),str);
#endif
        // Get rid of final enter character
        str[24] = '\0';

        file << str << " ";
        file << "[Z"<< zone_id<< "]";
        file << "[" << module << "]";
        file << "[" << error_names[type] << "]: ";
        file << message;
        file << endl;

        file.flush();

        file.close();
    }
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void CerrLog::log(
    const char *            module,
    const MessageType       type,
    const char *            message)
{
    char        str[26];
    time_t      the_time;
    ofstream    file;

    if( type <= log_level)
    {
        the_time = time(NULL);

#ifdef SOLARIS
        ctime_r(&(the_time),str,sizeof(char)*26);
#else
        ctime_r(&(the_time),str);
#endif
        // Get rid of final enter character
        str[24] = '\0';

        cerr << str << " ";
        cerr << "[Z"<< zone_id<< "]";
        cerr << "[" << module << "]";
        cerr << "[" << error_names[type] << "]: ";
        cerr << message;
        cerr << endl;

        cerr.flush();
    }
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

#ifdef SYSLOG_LOG

const char * SysLog::CATEGORY = "ROOT";
string       SysLog::LABEL;

/* -------------------------------------------------------------------------- */

SysLog::SysLog(const MessageType level,
               const string&     label):Log(level)
{
    static bool initialized = false;

    if (!initialized) //Initialize just once for all SysLog instances
    {
        ostringstream     oss;
        log4cpp::Appender *appender;

        oss << label << "[" << getpid() << "]";

        LABEL = oss.str();

        appender = new log4cpp::SyslogAppender(CATEGORY, LABEL, LOG_DAEMON);
        appender->setLayout(new log4cpp::PatternLayout());

        log4cpp::Category& root = log4cpp::Category::getRoot();

        root.setPriority(SysLog::get_priority_level(level));
        root.addAppender(appender);

        initialized = true;
    }
};

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void SysLog::log(
    const char *            module,
    const MessageType       type,
    const char *            message)
{
    log4cpp::Category&               root  = log4cpp::Category::getRoot();
    log4cpp::Priority::PriorityLevel level = get_priority_level(type);

    istringstream smessage;
    string        line;

    smessage.str(message);

    while ( getline(smessage, line) )
    {
        root << level << "[Z"<< zone_id<< "]"
                      << "[" << module << "]"
                      << "[" << error_names[type] << "]: "
                      << line;
    }

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

log4cpp::Priority::PriorityLevel SysLog::get_priority_level(
    const MessageType level)
{
    log4cpp::Priority::PriorityLevel priority_level;

    switch (level)
    {
    case Log::ERROR:
        priority_level = log4cpp::Priority::ERROR;
        break;

    case Log::WARNING:
        priority_level = log4cpp::Priority::WARN;
        break;

    case Log::INFO:
        priority_level = log4cpp::Priority::INFO;
        break;

    case Log::DEBUG:
    case Log::DDEBUG:
    case Log::DDDEBUG:
        priority_level = log4cpp::Priority::DEBUG;
        break;

    default:
        priority_level = log4cpp::Priority::NOTSET;
        break;
    }

    return priority_level;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

const char * SysLogResource::CATEGORY = "RESOURCE";

/* -------------------------------------------------------------------------- */

SysLogResource::SysLogResource(
        int                             oid,
        const PoolObjectSQL::ObjectType obj_type,
        const MessageType               clevel):SysLog(clevel)
{
    static bool   initialized = false;
    ostringstream oss_label;
    string        obj_type_str;

    if (!initialized)
    {
        log4cpp::Appender *appender;

        appender = new log4cpp::SyslogAppender(CATEGORY,
                                               SysLog::LABEL,
                                               LOG_DAEMON);

        appender->setLayout(new log4cpp::PatternLayout());

        log4cpp::Category& res = log4cpp::Category::getInstance(CATEGORY);

        res.addAppender(appender);
        res.setPriority(SysLog::get_priority_level(clevel));

        initialized = true;
    }

    obj_type_str = PoolObjectSQL::type_to_str(obj_type);

    oss_label << "[" << obj_type_str << " " << oid << "]";
    obj_label = oss_label.str();
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void SysLogResource::log(
    const char *            module,
    const MessageType       type,
    const char *            message)
{
    log4cpp::Category& res = log4cpp::Category::getInstance(CATEGORY);
    log4cpp::Priority::PriorityLevel level = get_priority_level(type);

    istringstream   smessage;
    string          line;

    smessage.str(message);

    while ( getline(smessage, line) )
    {
        res << level << obj_label
                     << "[Z" << zone_id << "]"
                     << "[" << module << "]"
                     << "[" << error_names[type] << "]: "
                     << line;
    }
}

#endif  /* SYSLOG_LOG */
<commit_msg>Fix compilation issue for syslog<commit_after>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2014, OpenNebula Project (OpenNebula.org), C12G Labs        */
/*                                                                            */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may    */
/* not use this file except in compliance with the License. You may obtain    */
/* a copy of the License at                                                   */
/*                                                                            */
/* http://www.apache.org/licenses/LICENSE-2.0                                 */
/*                                                                            */
/* Unless required by applicable law or agreed to in writing, software        */
/* distributed under the License is distributed on an "AS IS" BASIS,          */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   */
/* See the License for the specific language governing permissions and        */
/* limitations under the License.                                             */
/* -------------------------------------------------------------------------- */

#include "Log.h"

#include <string.h>
#include <stdlib.h>
#include <stdexcept>
#include <sstream>
#include <iostream>

#include <sys/types.h>
#include <unistd.h>

#ifdef SYSLOG_LOG
#   include <syslog.h>

#   include "log4cpp/Category.hh"
#   include "log4cpp/CategoryStream.hh"
#   include "log4cpp/Appender.hh"
#   include "log4cpp/SyslogAppender.hh"
#   include "log4cpp/Layout.hh"
#   include "log4cpp/PatternLayout.hh"
#   include "log4cpp/Priority.hh"
#endif /* SYSLOG_LOG */

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

const char Log::error_names[] ={ 'E', 'W', 'I', 'D' };

unsigned int Log::zone_id = 0;

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

FileLog::FileLog(const string&   file_name,
                 const MessageType   level,
                 ios_base::openmode  mode)
        :Log(level), log_file_name(file_name)
{
    ofstream file;

    file.open(log_file_name.c_str(), mode);

    if (file.fail() == true)
    {
        throw runtime_error("Could not open log file");
    }

    if ( file.is_open() == true )
    {
        file.close();
    }
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

FileLog::~FileLog() { }

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void FileLog::log(
    const char *            module,
    const MessageType       type,
    const char *            message)
{
    char        str[26];
    time_t      the_time;
    ofstream    file;

    if( type <= log_level)
    {
        file.open(log_file_name.c_str(), ios_base::app);

        if (file.fail() == true)
        {
            return;
        }

        the_time = time(NULL);

#ifdef SOLARIS
        ctime_r(&(the_time),str,sizeof(char)*26);
#else
        ctime_r(&(the_time),str);
#endif
        // Get rid of final enter character
        str[24] = '\0';

        file << str << " ";
        file << "[Z"<< zone_id<< "]";
        file << "[" << module << "]";
        file << "[" << error_names[type] << "]: ";
        file << message;
        file << endl;

        file.flush();

        file.close();
    }
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void CerrLog::log(
    const char *            module,
    const MessageType       type,
    const char *            message)
{
    char        str[26];
    time_t      the_time;
    ofstream    file;

    if( type <= log_level)
    {
        the_time = time(NULL);

#ifdef SOLARIS
        ctime_r(&(the_time),str,sizeof(char)*26);
#else
        ctime_r(&(the_time),str);
#endif
        // Get rid of final enter character
        str[24] = '\0';

        cerr << str << " ";
        cerr << "[Z"<< zone_id<< "]";
        cerr << "[" << module << "]";
        cerr << "[" << error_names[type] << "]: ";
        cerr << message;
        cerr << endl;

        cerr.flush();
    }
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

#ifdef SYSLOG_LOG

const char * SysLog::CATEGORY = "ROOT";
string       SysLog::LABEL;

/* -------------------------------------------------------------------------- */

SysLog::SysLog(const MessageType level,
               const string&     label):Log(level)
{
    static bool initialized = false;

    if (!initialized) //Initialize just once for all SysLog instances
    {
        ostringstream     oss;
        log4cpp::Appender *appender;

        oss << label << "[" << getpid() << "]";

        LABEL = oss.str();

        appender = new log4cpp::SyslogAppender(CATEGORY, LABEL, LOG_DAEMON);
        appender->setLayout(new log4cpp::PatternLayout());

        log4cpp::Category& root = log4cpp::Category::getRoot();

        root.setPriority(SysLog::get_priority_level(level));
        root.addAppender(appender);

        initialized = true;
    }
};

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void SysLog::log(
    const char *            module,
    const MessageType       type,
    const char *            message)
{
    log4cpp::Category&               root  = log4cpp::Category::getRoot();
    log4cpp::Priority::PriorityLevel level = get_priority_level(type);

    istringstream smessage;
    string        line;

    smessage.str(message);

    while ( getline(smessage, line) )
    {
        root << level << "[Z"<< zone_id<< "]"
                      << "[" << module << "]"
                      << "[" << error_names[type] << "]: "
                      << line;
    }
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

log4cpp::Priority::PriorityLevel SysLog::get_priority_level(
    const MessageType level)
{
    log4cpp::Priority::PriorityLevel priority_level;

    switch (level)
    {
    case Log::ERROR:
        priority_level = log4cpp::Priority::ERROR;
        break;

    case Log::WARNING:
        priority_level = log4cpp::Priority::WARN;
        break;

    case Log::INFO:
        priority_level = log4cpp::Priority::INFO;
        break;

    case Log::DEBUG:
    case Log::DDEBUG:
    case Log::DDDEBUG:
        priority_level = log4cpp::Priority::DEBUG;
        break;

    default:
        priority_level = log4cpp::Priority::NOTSET;
        break;
    }

    return priority_level;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

const char * SysLogResource::CATEGORY = "RESOURCE";

/* -------------------------------------------------------------------------- */

SysLogResource::SysLogResource(
        int                             oid,
        const PoolObjectSQL::ObjectType obj_type,
        const MessageType               clevel):SysLog(clevel)
{
    static bool   initialized = false;
    ostringstream oss_label;
    string        obj_type_str;

    if (!initialized)
    {
        log4cpp::Appender *appender;

        appender = new log4cpp::SyslogAppender(CATEGORY,
                                               SysLog::LABEL,
                                               LOG_DAEMON);

        appender->setLayout(new log4cpp::PatternLayout());

        log4cpp::Category& res = log4cpp::Category::getInstance(CATEGORY);

        res.addAppender(appender);
        res.setPriority(SysLog::get_priority_level(clevel));

        initialized = true;
    }

    obj_type_str = PoolObjectSQL::type_to_str(obj_type);

    oss_label << "[" << obj_type_str << " " << oid << "]";
    obj_label = oss_label.str();
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void SysLogResource::log(
    const char *            module,
    const MessageType       type,
    const char *            message)
{
    log4cpp::Category& res = log4cpp::Category::getInstance(CATEGORY);
    log4cpp::Priority::PriorityLevel level = get_priority_level(type);

    istringstream   smessage;
    string          line;

    smessage.str(message);

    while ( getline(smessage, line) )
    {
        res << level << obj_label
                     << "[Z" << zone_id << "]"
                     << "[" << module << "]"
                     << "[" << error_names[type] << "]: "
                     << line;
    }
}

#endif  /* SYSLOG_LOG */
<|endoftext|>