Thứ Tư, 27 tháng 10, 2010

Create your own user-defined services Windows NT/2000/XP/2003

The Windows NT/2000 Resource Kit provides two utilities that allow you to create a Windows user-defined service for Windows applications and some 16-bit applications (but not for batch files).

Whats needed for Windows NT/2000:
Instrsrv.exe installs and removes system services from Windows NT/2000
Srvany.exe allows any Windows application to run as a service.
You can download both files here srvany.zip

This zip includes three files. The two you need srvany.exe and instsrv.exe to install the services and also srvany.wri which documents everything you can do with the program.
Note: Make sure the Services Manager is closed while running the DOS commands.



You will need to put these files in a directory called reskit At a MS-DOS command prompt(Start | Run | "cmd.exe"), type the following command:
<path>\reskit\INSTSRV.EXE "Service Name" <path>\reskit\SRVANY.EXE
This creates the service in the Services manager and the registry keys to setup what program to run.

http:www.tacktech.com/



Next open regedit.exe Start | run | regedit.exe
WARNING: Using Registry Editor incorrectly can cause serious problems that may require you to reinstall your operating system. Microsoft cannot guarantee that problems resulting from the incorrect use of Registry Editor can be solved. Use Registry Editor at your own risk.

http:www.tacktech.com/



Next navigate to this registry key.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\service name

http:www.tacktech.com/



From the Edit menu, click Add Key and name it Parameters
Next from the Edit menu, click Add Value and type this information.
Value Name: Application
Data Type : REG_SZ
String : <path>\<application.ext>

http:www.tacktech.com/



Now you can start your service from the Service Manager

http:www.tacktech.com/



With this same program you can remove the service also. Just run this command from command prompt.
<path>\reskit\INSTSRV.EXE "Service Name" REMOVE

http:www.tacktech.com/

Source: http://www.tacktech.com/display.cfm?ttid=197

Thứ Sáu, 22 tháng 10, 2010

Upload file by using servlet

Code: servlet
package com.servlet.FileUploadServlet;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FileUploadServlet extends HttpServlet {

    /**
     * The base upload directory. In this directory all uploaded files will
     * be stored. With the applet param tag 'directory' you can create a
     * subdirectory for a user.
     * See http://www.javaatwork.com/parameters.html#directory for more
     * information about the 'directory' param tag. For a Windows environment
     * the BASE_DIRECTORY can be e.g. * 'c:/temp' for Linux environment '/tmp'.
     */
    private static final String BASE_DIRECTORY = "/images";

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);

        // check if the http request is a multipart request
        // with other words check that the http request can have uploaded files
        if (isMultipart) {

            //  Create a factory for disk-based file items
            FileItemFactory factory = new DiskFileItemFactory();

            //  Create a new file upload handler
            ServletFileUpload servletFileUpload = new ServletFileUpload(factory);

            // Set upload parameters
            // See Apache Commons FileUpload for more information
            // http://jakarta.apache.org/commons/fileupload/using.html
            servletFileUpload.setSizeMax(-1);

            try {

                String directory = "";

                // Parse the request
                List items = servletFileUpload.parseRequest(request);

                // Process the uploaded items
                Iterator iter = items.iterator();

                while (iter.hasNext()) {
                    FileItem item = (FileItem) iter.next();

                    // the param tag directory is sent as a request parameter to
                    // the server
                    // check if the upload directory is available
                    if (item.isFormField()) {

                        String name = item.getFieldName();

                        if (name.equalsIgnoreCase("directory")) {

                            directory = item.getString();
                        }

                        // retrieve the files
                    } else {

                        // the fileNames are urlencoded
                        String fileName = URLDecoder.decode(item.getName());

                        File file = new File(directory, fileName);
                        file = new File(BASE_DIRECTORY, file.getPath());

                        // retrieve the parent file for creating the directories
                        File parentFile = file.getParentFile();

                        if (parentFile != null) {
                            parentFile.mkdirs();
                        }

                        // writes the file to the filesystem
                        item.write(file);
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }

            response.setStatus(HttpServletResponse.SC_OK);

        } else {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }


    }
}


Code: jsp
<form name="uploadForm" action="FileUploadServlet" enctype="multipart/form-data" method="POST">
   <input type="file" name="file1" readonly="readonly" size="70">
   <input type="Submit" value="Upload File"><br>
</form>

Code: web.xml
<servlet>
        <servlet-name>FileUploadServlet</servlet-name>
        <servlet-class>com.servlet.FileUploadServlet</servlet-class>
</servlet>
<servlet-mapping>
        <servlet-name>FileUploadServlet</servlet-name>
        <url-pattern>/FileUploadServlet</url-pattern>
</servlet-mapping>


Link download FileUpload component: here
Link download Common IO component: here

Simple sending mail by JavaMail

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public class SendMail {

    // Send a simple, single part, text/plain e-mail
    public void sendSimple(String toAddress, String body){
        String DEFAULT_ENCODING = "UTF-8";
        // SUBSTITUTE YOUR EMAIL ADDRESSES HERE!!!
        String to = toAddress;
        String from = "your_email_here";
        // SUBSTITUTE YOUR ISP'S MAIL SERVER HERE!!!
        String host = "your_email_server_host_here";

        // Create properties, get Session
        Properties props = new Properties();

        // If using static Transport.send(),
        // need to specify which host to send it to
        props.put("mail.smtp.host", host);
        // To see what is going on behind the scene
        props.put("mail.debug", "true");
        Session session = Session.getInstance(props);

        try {
            // Instantiatee a message
            MimeMessage msg = new MimeMessage(session);

            //Set message attributes
            msg.setFrom(new InternetAddress(from));
            InternetAddress[] address = {new InternetAddress(to)};
            msg.setRecipients(Message.RecipientType.TO, address);
            msg.setSubject("your_subject_here", DEFAULT_ENCODING);
            msg.setSentDate(new Date());

            // Set message content
            msg.setText(body, DEFAULT_ENCODING);
            //Send the message
            Transport.send(msg);
        }
        catch (MessagingException mex) {
            // Prints all nested (chained) exceptions as well
            mex.printStackTrace();
        }
    }
}

Link download JavaMail component: here
Note: if you use JavaMail on Web application, please copy mail.jar to lib folder of Web Application Server

Customize YUICompressor

import com.yahoo.platform.yui.compressor.CssCompressor;
import com.yahoo.platform.yui.compressor.JavaScriptCompressor;
import jargs.gnu.CmdLineParser;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.nio.charset.Charset;
import org.mozilla.javascript.ErrorReporter;
import org.mozilla.javascript.EvaluatorException;

public class YUIExecutor {

    public void run(String inputFolder, String outputFolder) throws Exception{
        File folder = new File(inputFolder);
        File[] listOfFiles = folder.listFiles();

        for (int i = 0; i < listOfFiles.length; i++) {
            if (listOfFiles[i].isFile()) {
                process(inputFolder + listOfFiles[i].getName(), outputFolder + listOfFiles[i].getName());
            }
        }
    }

    private void process(String inputJSFile, String outputJSFile) {
        String[] args = new String[3];
        args[0] = inputJSFile;
        args[1] = "-o";
        args[2] = outputJSFile;
        CmdLineParser parser = new CmdLineParser();
        jargs.gnu.CmdLineParser.Option typeOpt = parser.addStringOption("type");
        jargs.gnu.CmdLineParser.Option verboseOpt = parser.addBooleanOption('v', "verbose");
        jargs.gnu.CmdLineParser.Option nomungeOpt = parser.addBooleanOption("nomunge");
        jargs.gnu.CmdLineParser.Option linebreakOpt = parser.addStringOption("line-break");
        jargs.gnu.CmdLineParser.Option preserveSemiOpt = parser.addBooleanOption("preserve-semi");
        jargs.gnu.CmdLineParser.Option disableOptimizationsOpt = parser.addBooleanOption("disable-optimizations");
        jargs.gnu.CmdLineParser.Option helpOpt = parser.addBooleanOption('h', "help");
        jargs.gnu.CmdLineParser.Option charsetOpt = parser.addStringOption("charset");
        jargs.gnu.CmdLineParser.Option outputFilenameOpt = parser.addStringOption('o', "output");
        Reader in = null;
        Writer out = null;
        try {
            parser.parse(args);
            Boolean help = (Boolean) parser.getOptionValue(helpOpt);
            if (help != null && help.booleanValue()) {
                usage();
                System.exit(0);
            }
            boolean verbose = parser.getOptionValue(verboseOpt) != null;
            String charset = (String) parser.getOptionValue(charsetOpt);
            if (charset == null || !Charset.isSupported(charset)) {
                charset = System.getProperty("file.encoding");
                if (charset == null) {
                    charset = "UTF-8";
                }
                if (verbose) {
                    System.err.println("\n[INFO] Using charset " + charset);
                }
            }
            String fileArgs[] = parser.getRemainingArgs();
            String type = (String) parser.getOptionValue(typeOpt);
            if (fileArgs.length == 0) {
                if (type == null || !type.equalsIgnoreCase("js") && !type.equalsIgnoreCase("css")) {
                    usage();
                    System.exit(1);
                }
                in = new InputStreamReader(System.in, charset);
            } else {
                if (type != null && !type.equalsIgnoreCase("js") && !type.equalsIgnoreCase("css")) {
                    usage();
                    System.exit(1);
                }
                String inputFilename = fileArgs[0];
                if (type == null) {
                    int idx = inputFilename.lastIndexOf('.');
                    if (idx >= 0 && idx < inputFilename.length() - 1) {
                        type = inputFilename.substring(idx + 1);
                    }
                }
                if (type == null || !type.equalsIgnoreCase("js") && !type.equalsIgnoreCase("css")) {
                    usage();
                    System.exit(1);
                }
                in = new InputStreamReader(new FileInputStream(inputFilename), charset);
            }
            int linebreakpos = -1;
            String linebreakstr = (String) parser.getOptionValue(linebreakOpt);
            if (linebreakstr != null) {
                try {
                    linebreakpos = Integer.parseInt(linebreakstr, 10);
                } catch (NumberFormatException _ex) {
                    usage();
                    System.exit(1);
                }
            }
            String outputFilename = (String) parser.getOptionValue(outputFilenameOpt);
            if (type.equalsIgnoreCase("js")) {
                try {
                    JavaScriptCompressor compressor = new JavaScriptCompressor(in, new ErrorReporter() {

                        public void warning(String message, String sourceName, int line, String lineSource, int lineOffset) {
                            if (line < 0) {
                                System.err.println("\n[WARNING] " + message);
                            } else {
                                System.err.println("\n[WARNING] " + line + ':' + lineOffset + ':' + message);
                            }
                        }

                        public void error(String message, String sourceName, int line, String lineSource, int lineOffset) {
                            if (line < 0) {
                                System.err.println("\n[ERROR] " + message);
                            } else {
                                System.err.println("\n[ERROR] " + line + ':' + lineOffset + ':' + message);
                            }
                        }

                        public EvaluatorException runtimeError(String message, String sourceName, int line, String lineSource, int lineOffset) {
                            error(message, sourceName, line, lineSource, lineOffset);
                            return new EvaluatorException(message);
                        }
                    });
                    in.close();
                    in = null;
                    if (outputFilename == null) {
                        out = new OutputStreamWriter(System.out, charset);
                    } else {
                        out = new OutputStreamWriter(new FileOutputStream(outputFilename), charset);
                    }
                    boolean munge = parser.getOptionValue(nomungeOpt) == null;
                    boolean preserveAllSemiColons = parser.getOptionValue(preserveSemiOpt) != null;
                    boolean disableOptimizations = parser.getOptionValue(disableOptimizationsOpt) != null;
                    compressor.compress(out, linebreakpos, munge, verbose, preserveAllSemiColons, disableOptimizations);
                } catch (EvaluatorException e) {
                    e.printStackTrace();
                    System.exit(2);
                }
            } else if (type.equalsIgnoreCase("css")) {
                CssCompressor compressor = new CssCompressor(in);
                in.close();
                in = null;
                if (outputFilename == null) {
                    out = new OutputStreamWriter(System.out, charset);
                } else {
                    out = new OutputStreamWriter(new FileOutputStream(outputFilename), charset);
                }
                compressor.compress(out, linebreakpos);
            }
        } catch (jargs.gnu.CmdLineParser.OptionException _ex) {
            usage();
            System.exit(1);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return;
    }

    private static void usage() {
        System.out.println("\nUsage: java -jar yuicompressor-x.y.z.jar [options] [input file]\n\nGlobal Options\n  -h, --help                Displays this information\n  --type <js|css>           Specifies the type of the input file\n  --charset <charset>       Read the input file using <charset>\n  --line-break <column>     Insert a line break after the specified column number\n  -v, --verbose             Display informational messages and warnings\n  -o <file>                 Place the output into <file>. Defaults to stdout.\n\nJavaScript Options\n  --nomunge                 Minify only, do not obfuscate\n  --preserve-semi           Preserve all semicolons\n  --disable-optimizations   Disable all micro optimizations\n\nIf no input file is specified, it defaults to stdin. In this case, the 'type'\noption is required. Otherwise, the 'type' option is required only if the input\nfile extension is neither 'js' nor 'css'.");
    }
}

Link download yuicompressor component: here

Thứ Năm, 21 tháng 10, 2010

Unprotect an excel worksheet

1. Open VIEW CODE window (Alt+F11)
2. Copy this code below:
Code:
Sub  PasswordBreaker()
    If ActiveSheet.ProtectContents = False Then
         MsgBox "Sheet '" & ActiveSheet.Name & "' is unprotected!",  vbInformation
    Else
        If MsgBox("Sheet '" & ActiveSheet.Name  & "' is protected, do you want to unprotect it?", _
        vbYesNo +  vbQuestion, "Unprotect Active Sheet") = vbNo Then Exit Sub
        Dim i  As Integer, j As Integer, k As Integer
        Dim l As Integer, m As  Integer, n As Integer
        Dim i1 As Integer, i2 As Integer, i3 As  Integer
        Dim i4 As Integer, i5 As Integer, i6 As Integer
        On  Error Resume Next
        For i = 65 To 66: For j = 65 To 66: For k = 65  To 66
        For l = 65 To 66: For m = 65 To 66: For i1 = 65 To 66
         For i2 = 65 To 66: For i3 = 65 To 66: For i4 = 65 To 66
        For i5 =  65 To 66: For i6 = 65 To 66: For n = 32 To 126
             ActiveSheet.Unprotect Chr(i) & Chr(j) & Chr(k) & _
             Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & Chr(i3) & _
             Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)
        Next: Next:  Next: Next: Next: Next
        Next: Next: Next: Next: Next: Next
         If ActiveSheet.ProtectContents = False Then MsgBox "Sheet '" &  ActiveSheet.Name & "' is unprotected!", vbInformation
    End If
End  Sub
3. Run

Delete passwords stored in Windows cache

When you map network drive and select 'Remember your password', it means that you cannot connect with other  pair of username and password. So, do this below: 

net use * /delete /yes (more than twice) --> end all sessions before 

or  

rundll32.exe keymgr.dll, KRShowKeyMgr --> clear network cache

Windows 7 cannot connect Resources on Windows 2k Server

1. gpedit.msc
2. Computer Configuration / Windows Settings / Security Settings /
    Local Policies/ Security Options /
    Network security: LAN Manager authentication level
3. select: Send LM & NTLM - use NTLMv2 session security if negotiated

Sort Java Vector in descending order using comparator example

/*
  Sort Java Vector in descending order using comparator example
  This java example shows how to sort elements of Java Vector in descending order
  using comparator and reverseOrder method of Collections class.
*/

import java.util.Vector;
import java.util.Collections;
import java.util.Comparator;

public class SortVectorInDescendingOrderExample {

  public static void main(String[] args) {

    //create a Vector object
    Vector v = new Vector();

    //Add elements to Vector
    v.add("1");
    v.add("2");
    v.add("3");
    v.add("4");
    v.add("5");

    /*
      To get comparator that imposes reverse order on a Collection use
      static Comparator reverseOrder() method of Collections class
    */

    Comparator comparator = Collections.reverseOrder();

    System.out.println("Before sorting Vector in descending order : " + v);

    /*
      To sort an Vector using comparator use,
      static void sort(List list, Comparator c) method of Collections class.
    */

    Collections.sort(v,comparator);
    System.out.println("After sorting Vector in descending order : " + v);

  }
}

/*
Output would be
Before sorting Vector in descending order : [1, 2, 3, 4, 5]
After sorting Vector in descending order : [5, 4, 3, 2, 1]
*/

Sort Java ArrayList in descending order using comparator example

/*
  Sort Java ArrayList in descending order using comparator example
  This java example shows how to sort elements of Java ArrayList in descending order
  using comparator and reverseOrder method of Collections class.
*/

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class SortArrayListInDescendingOrderExample {

  public static void main(String[] args) {

    //create an ArrayList object
    ArrayList arrayList = new ArrayList();

    //Add elements to Arraylist
    arrayList.add("A");
    arrayList.add("B");
    arrayList.add("C");
    arrayList.add("D");
    arrayList.add("E");

    /*
      To get comparator that imposes reverse order on a Collection use
      static Comparator reverseOrder() method of Collections class
    */

    Comparator comparator = Collections.reverseOrder();

    System.out.println("Before sorting ArrayList in descending order : "+ arrayList);

    /*
      To sort an ArrayList using comparator use,
      static void sort(List list, Comparator c) method of Collections class.
    */

    Collections.sort(arrayList,comparator);
    System.out.println("After sorting ArrayList in descending order : " + arrayList);

  }
}

/*
Output would be
Before sorting ArrayList in descending order : [A, B, C, D, E]
After sorting ArrayList in descending order : [E, D, C, B, A]
*/