Recent Post

Categories

Archives

Cow Computing

10 Jan 11

Using Java Mail API

In order to have the ability of sending email from your java program, you would need Java Mail API. It could be obtained here.

The following code illustrate how to use it. (Comment will guide you thru)

// Obtain the system property and set inside the SMTP server
Properties props = System.getProperties();
props.put("mail.smtp.host", "your isp smtp");

// Obtain the mail session
Session session = Session.getDefaultInstance(props, null);
Message message = new MimeMessage(session);

// Set the address for sender
message.setFrom(new InternetAddress("sender mail address"));

// Set the address for recipient
message.addRecipient(Message.RecipientType.TO, new InternetAddress("recipient mail address"));

// Set the Subject of the mail
message.setSubject("Subject");

// Set the message content of the mail
message.setContent("Message Body", "text/plain");

// Send the mail
Transport.send(message);

09 Dec 3

Implementing a Windows Service in C

Days ago, my colleague wanted to have his program written as a window service, and has no clue doing it. I searched online and came across some info, and then compiled the following program.

/*
* Service.c
*
*/

#include <windows.h>
#include <stdio.h>

SERVICE_STATUS          ServiceStatus;
SERVICE_STATUS_HANDLE   hStatus;

int WriteToLog(char* str)
{
    FILE* log;
    log = fopen("C:\\CowService\\log.txt", "a+");
    fprintf(log, "%s\n", str);
    fclose(log);

    return 0;
}

int InitService()
{
    int result;
    result = WriteToLog("Service Started.");
    return(result);
}

// Handler to be registered and called when user interact with the service. (inside the "Windows Service")
void ControlHandler(DWORD request)
{
    switch(request)
    {
        case SERVICE_CONTROL_STOP:
            WriteToLog("Service Closed");
            ServiceStatus.dwWin32ExitCode = 0;
            ServiceStatus.dwCurrentState = SERVICE_STOPPED;
            SetServiceStatus (hStatus, &ServiceStatus);
            return;
        case SERVICE_CONTROL_SHUTDOWN:
            WriteToLog("Service Closed");
            ServiceStatus.dwWin32ExitCode = 0;
            ServiceStatus.dwCurrentState = SERVICE_STOPPED;
            SetServiceStatus (hStatus, &ServiceStatus);
            return;
        default:
            break;
    }
    SetServiceStatus (hStatus, &ServiceStatus);
    return;
}

void ServiceMain(int argc, char** argv)
{
    int error;

    // Initialize and set the state of the service to be "Pending"
    ServiceStatus.dwServiceType = SERVICE_WIN32;
    ServiceStatus.dwCurrentState = SERVICE_START_PENDING;
    ServiceStatus.dwControlsAccepted   =  SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
    ServiceStatus.dwWin32ExitCode = 0;
    ServiceStatus.dwServiceSpecificExitCode = 0;
    ServiceStatus.dwCheckPoint = 0;
    ServiceStatus.dwWaitHint = 0;

    hStatus = RegisterServiceCtrlHandler("CowService", (LPHANDLER_FUNCTION)ControlHandler);
    if (hStatus == (SERVICE_STATUS_HANDLE)0)
    {
        return;
    }

    error = InitService();
    if (error)
    {
        // Error, set the service state to "Stopped" and return
        ServiceStatus.dwCurrentState = SERVICE_STOPPED;
        ServiceStatus.dwWin32ExitCode = -1;
        SetServiceStatus(hStatus, &ServiceStatus);

        return;
    }

    // Set the service state to be "Running"
    ServiceStatus.dwCurrentState = SERVICE_RUNNING;
    SetServiceStatus(hStatus, &ServiceStatus);

    while (ServiceStatus.dwCurrentState == SERVICE_RUNNING)
    {
        // while the service is on, do whatever you wish here.
        int result = WriteToLog("Service is Running\n");
        Sleep(2000);
    }

    return;
}

int main()
{
    // Create service table entry to be registered
    SERVICE_TABLE_ENTRY ServiceTable[2];
    ServiceTable[0].lpServiceName = "CowService";
    ServiceTable[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)ServiceMain;

    // Setting the entry NULL to indicate it's the end of the service table entry
    ServiceTable[1].lpServiceName = NULL;
    ServiceTable[1].lpServiceProc = NULL;

    StartServiceCtrlDispatcher(ServiceTable);

    return 0;
}

The code is straightforward, and comments should have spoken for itself.

However, to have the service program working, you have to register it with the “Windows Service” by issuing

// sc create <servcie name> bin_path= <location to the service program>
sc create CowService bin_path= C:\CowService.exe

09 Oct 12

Thunderbird Extension Development

Recently, i have been working on an productizing an product of my working company. It involves developing an extension for Thunderbird. During the development process, i have discovered there has been inadequate resources out there for Thunderbird Extension, especially when most developers are interested in working on another Mozilla’s flagship product — FireFox. So, i would like to share my experience on this

To begin, we have to prepare the appropriate directory.

sample.xpi

/install.rdf
/components/
/defaults/
/plugins/
/chrome.manifest
/chrome/icons/default/
/chrome/
/chrome/content
/chrome/skin

Read More / Comment »

09 Sep 23

Java – Cloning an InputStream

There’s a moment when you have been given an InputStream, with its markSupported returned “False”. This means you could only read the stream one and only once, as you can’t call “reset” on it. So, what to do if you want to read the stream for more than one time and be able to re-read the previously read data. The answer is “CLONE”. My very own approach would be to use Apache Commons to turn the stream into string in which it acts as a base. Whenever i need that InputStream, i turns the string back into an stream without affecting the read position and data lost. OK, here’s the steps.

Suppose you got a request object with InputStream.

// request is the Request Object
// Turns InputStream into string
String base = IOUtils.toString(request.getInputStream());

// Whenever you need the InputStream
// Turn the string back to InputStream this way
InputStream in = new ByteArrayInputStream(base.getBytes());

09 Sep 7

.NET code to interact with Java’s Web Service

Recently, i am working on a library to allow .NET developer to interact with a web service built on Java. It’s a SwA (Soap with Attachment). The reason for me to do this is because there’s been no support for such operation in .NET framework and users who want to deal with such scenario will have to write their own code bit by bit to accomplish the job, which is TEDIOUS…

The library i built relies on an open source library called PocketSoap. Its support on Attachment and its ease of use is appealing and i at last chosen to give it a try and build a POC on top of it. Below is a simple usage sample for the PocketSoap library.

using System;
using PocketSOAP;
using PocketSOAPAttachments;

namespace PSTryout
{
    public class psWS
    {
        CoEnvelope e = new CoEnvelopeClass();
        e.Body.Create("id", 1, "", null, null);
        e.EncodingStyle = "";

        HTTPTransport h = new HTTPTransport();
        h.SOAPAction = "query";
        h.Timeout = 30000;
        h.Send("http://localhost:8080/ws/", e.Serialize());

        string enc = "";
        e.Parse(h, enc);
    }
}