Thursday, November 10, 2005

upload file using Apache commons fileupload

I write servlet to process upload file recently, I found the apache commons fileupload is a suitable package for this kind of programming, following is the help message found in package.

Package org.apache.commons.fileupload Description
Component for handling html file uploads as given by rfc 1867 RFC 1867.
Normal usage of the package involves DiskFileUpload parsing the HttpServletRequest and returning a list of FileItem's. These FileItem's provide easy access to the data given in the upload. There is also a low level api for manipulating the upload data encapsulated in the MultipartStream class.
Normal usage example: public void doPost(HttpServletRequest req, HttpServletResponse res)
{
DiskFileUpload fu = new DiskFileUpload();
// maximum size before a FileUploadException will be thrown
fu.setSizeMax(1000000);
// maximum size that will be stored in memory
fu.setSizeThreshold(4096);
// the location for saving data that is larger than getSizeThreshold()
fu.setRepositoryPath("/tmp");
List fileItems = fu.parseRequest(req);
// assume we know there are two files. The first file is a small
// text file, the second is unknown and is written to a file on
// the server
Iterator i = fileItems.iterator();
String comment = ((FileItem)i.next()).getString();
FileItem fi = (FileItem)i.next();
// filename on the client
String fileName = fi.getName();
// save comment and filename to database
...
// write the file
fi.write("/www/uploads/" + fileName);
}
In the example above the first file is loaded into memory as a String. Before calling the getString method, the data may have been in memory or on disk depending on its size. The second file we assume it will be large and therefore never explicitly load it into memory, though if it is less than 4096 bytes it will be in memory before it is written to its final location. When writing to the final location, if the data is larger than the threshold, an attempt is made to rename the temporary file to the given location. If it cannot be renamed, it is streamed to the new location.

Monday, August 15, 2005

Some useful site

1. A good guide to port usage is available on the web at
http://www.sockets.com/services.htm

2. A detailed database of file extensions and programs that use them at
http://filext.com/index.php

3. A detailed list of MIME type
http://www.w3schools.com/media/media_mimeref.asp

Wednesday, August 03, 2005

List all queries in AS400

I recently need list all queries in AS400 and get the definistion of the query.

To do that,
First, run following command,

DSPOBJD OBJ(*ALLUSR/*ALL) OBJTYPE(*QRYDFN) OUTPUT(*OUTFILE)
OUTFILE(WZJLIB/QRYLIST)

Second, for each query in the file, run following command to retrive the definition,

RTVQMQRY QMQRY(&ODLBNM/&ODOBNM) SRCFILE(WZJLIB/QUERIES) ALWQRYDFN(*YES)

the full CL program is named as LISTQUERY.

Thursday, July 28, 2005

a Good JavaScript

Today, I found a good JavaScript, which include following function,

1. preventing user use 'right click', which can block user see the source of your page.

2. have a popup menu to allow user select date.

I copy the source as file name 'commonJS.txt' in my documents.

Monday, July 25, 2005

Solve problem on using Jbuilder 9.0 create Mail program

Recently, I create a program for data synchronization, when the synchronization is done, the program will send a email to inform me.

it is run perfectly in jbuilder, but when run the program created by using jBuilder 9 developer, it show following message:

javax.mail.SendFailedException: Sending failed;
nested exception is:
class javax.mail.MessagingException: IOException while sending message;
nested exception is:
javax.activation.UnsupportedDataTypeException: no object DCH for MIME type multipart/mixed;
boundary="----=_Part_0_31149935.1122348209343"
at javax.mail.Transport.send0(Transport.java:218)
at javax.mail.Transport.send(Transport.java:80)
at movex.sendMailClass.sendMail(sendMailClass.java:226)
at movex.SynTest.main(SynTest.java:80)

after search the internet, I found the solutio for it that we need manually exclude the files of SUN_MICR.RSA and SUN_MICR.SF from the META-INF folder in mail.jar.

To do it, following below steps.

From the jar's folder which on my Pc is 'C:\jBuilder9\lib':

0. copy mail.jar mailbackup.jar
1. mkdir jartemp
2. cd jartemp
3. C:\JBuilder9\jdk1.4\bin\jar -xvf ../mail.jar
4. cd META-INF
5. del SUN_MICR.*
6. cd..
7. C:\JBuilder9\jdk1.4\bin\jar cvf ../mail.jar *

you can delete jartemp now or later.

Then using new generated mail.jar in your jbuilder project.

Thursday, May 19, 2005

Some Useful Tip for EXCEL Visual Basic

1. Suppress alerts and Screen updating
It can be annoying to have to respond to system alerts or see the screen change and flicker while a macro is running. To suppress alerts and screen updating, add following two lines at the beginning of the macro,
Application.DisplayAlerts=False
Application.ScreenUpdating=False

don't forget to add following two lines at the end of the macro,
Application.DisplayAlerts=True
Application.ScreenUpdating=True


2. Error Handling
To trap error, using following statement at the beginning of code that you anticipate error will occur, On Error GoTo errorhandling


put your code here.....
On Error GoTo 0 ' resume
errorhandling:
put your error handling code here......
3. loop statements
  • Do While (condition) ... Loop
  • Do Until (condition) ... Loop
  • For i=Startvalue TO Endvalue Step Stepvalue ... Next
  • For Each ... Next
Example of 'For Each ... Next', To get the shape name which stored in one cell.
For Each Shape In Sheets("data").Shapes
With Shape
pt = .Top
pl = .Left
If (pt >= t) And (pt <= t + h) And (pl >= l) And (pl <= l + w) Then rtnstr = Shape.Name Exit For End If End With Next Shape

4. Convert between String and Numeric
Val(String) , Convert string to numeric.
Str(Number), Convert number to string.
format(number,"format "), Convert number to string
For other type conversion functions, search 'Type Conversion Functions' in Microsoft Visual Basic Help.
5. Get Workbook's name and path
name=ActiveWorkbook.Name
path= ActiveWorkbook.Path

6. Open other excel file
Workbooks.Open (ExcelFileName)
7. Insert picture fit in a Range
' inserts a picture and resizes it to fit the TargetCells range
Sub InsertPictureInRange(PictureFileName As String, TargetCells As Range)

Dim p As Object
Dim t As Double, l As Double, w As Double, h As Double
Dim ot As Double, ol As Double, ow As Double, oh As Double
If TypeName(ActiveSheet) <> "Worksheet" Then Exit Sub
If Dir(PictureFileName) = "" Then Exit Sub
' import pictureSet p = ActiveSheet.Pictures.Insert(PictureFileName)' determine positions
With TargetCells
t = .Top + 1
l = .Left + 1
w = .Offset(0, .Columns.Count).Left - .Left - 2
h = .Offset(.Rows.Count, 0).Top - .Top - 2
End With
' position picture
With p
oh = .Height
ow = .Width
.Top = t
.Left = l
.Width = ow * h / oh
.Height = h
.Placement = xlMoveAndSize
.PrintObject = True
End With
Set p = Nothing
End Sub

8. Wait untill called program finished
Some time in Excel VBA program, we use shell command to call other program, but by By default, the Shell function runs other programs asynchronously. This means that a program started with Shell might not finish executing before the statements following the Shell function are executed. to wait the called program finish, use following code.
first, define the calling for microsoft API
Private Declare Function OpenProcess Lib "kernel32" ( _ByVal dwDesiredAccess As Long, _ByVal bInheritHandle As Long, _ByVal dwProcessID As Long) As Long
Private Declare Function GetExitCodeProcess Lib "kernel32" ( _ByVal hProcess As Long, _IPExitCode As Long) As Long
then, write your VBA's sub or function procedure as below
Public Sub yoursub()
ACCESS_TYPE = &H400
STILL_ACTIVE = &H103
taskid = Shell(cmdline, vbHide)
hproc = OpenProcess(ACCESS_TYPE, False, taskid)
Do
Application.Wait (Now + TimeValue("0:00:01"))
GetExitCodeProcess hproc, lExitCode
Loop While lExitCode = STILL_ACTIVE
do other things....
end sub

9.Convert between string and date
dim A1 as string, outdate as date
dim ctyear as Integer, ctmonth as Integer, ctday as Integer
A1 = "20050701"
ctyear=CInt(Left(A1,4))
ctmonth=CInt(mid(a1,5,2))
ctday=CInt(right(a1,2))
outdate=DateSerial(ctyear,ctmonth,ctday)
'outdate = DateValue(Mid(A1, 5, 2) & "/" &amp;amp;amp; Right(A1, 2) & "/" & Left(A1, 4))
A1 = Format(outdate, "yyyymmdd")

10.Delete rows from title to the last row
Suppose the first tow lines are title, to delete the rows that is not title,
Dim tolcol As Integer, tolrow As Integer

Sheets("Result").Select
Selection.SpecialCells(xlCellTypeLastCell).Select
tolcol = ActiveCell.Column
tolrow = ActiveCell.Row
If (tolrow > 2) Then
Range(Cells(2, 1), Cells(tolrow, tolcol)).Select
Selection.EntireRow.Delete
End If
Range("A2").Select


11.Get last row and column of a sheet
Sheets(ssn).Select
 Selection.SpecialCells(xlCellTypeLastCell).Select
    tolcol = ActiveCell.Column
    tolrow = ActiveCell.Row


12.Find line break in cell
The line break in excel is alt+enter, is char(10). 
=FIND(CHAR(10),C439,1)
 


Tuesday, May 17, 2005

Link Tomcat 5.0 with IIS 6

Update on 05 July 2007 for tomcat 6.0:

1. when installing isapi-redirector, actually not need create entries in registry, just create a text file named ' isapi_redirect.properties' and put it in the same directory of 'isapi_redirect.dll'.
the contains of the file may be like below:

# Configuration file for the Jakarta ISAPI Redirector
# The path to the ISAPI Redirector Extension, relative to the website

# This must be in a virtual directory with execute privileges
extension_uri=/jakarta/isapi_redirect.dll

# Full path to the log file for the ISAPI Redirector
log_file=C:\Program Files\Apache Software Foundation\Jakarta Isapi Redirector\log\isapi_redirect.log

# Log level (debug, info, warn, error or trace)
log_level=info

# Full path to the workers.properties file
worker_file=C:\Program Files\Apache Software Foundation\Jakarta Isapi director\conf\workers.properties

# Full path to the uriworkermap.properties file
worker_mount_file=C:\Program Files\Apache Software Foundation\Jakarta Isapi Redirector\conf\uriworkermap.properties

2. after create virtual directory 'jakarta' in IIS6 or IIS7, need create web service extensions in order to allow jakarta to run,

for IIS6, click 'Add a new web service extension', then key in 'Extension name:" as 'jakarta'; 'Required files:' as 'isapi_redirect.dll' and check 'Set extension status to Allow'.

for IIS7, click 'Handler Mappings', then click 'Add Script Map...', then key in 'Request path:' as '.dll'; key in 'Executable' as ''isapi_redirect.dll' ; key in 'Name' as 'jakarta'.





Recently, I set up a intranet for our company, which running on Windows Server 2003, and web server is IIS 6. We use Apache Tomcat to serve the dynamic request from user, like sales report. There is a good link about how to link Tomcat 5.0 with IIS 6 on windows server 2003, which at http://tjworld.net/help/kb/0001_iis6-Tomcat5-JK2.html .

basically, the step is:
1. install JDK5.0

2. install tomcat

3. install isapi-redirector

4. on IIS, add a new extensions in web service extension.

5. restart server


to install admin service:
Files Needed:
jakarta-tomcat-5.5.9.exe
jakarta-tomcat-5.5.9-admin.zip
1. Install tomcat

2. Unzip the admin package (we'll call it context)

3. Copy the entire directory /server/webapps/adminto/server/webapps

4. Copy the file /conf/Catalina/localhost/admin.xml to /conf/Catalina/localhost

5. Restart your server.

Install jndi mail session

context.xml file:


web.xml file:

Resource reference to a factory for javax.mail.Session instances that may be used for sending electronic mail messages, preconfigured to connect to the appropriate SMTP server.
mail/Session
javax.mail.Session
Container


Finally, Your code should look like this...

Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
Session session = (Session) envCtx.lookup("mail/Session");
MimeMessage message = new MimeMessage( session );

FTP Service's DefaultLogonDomain Not Available in MMC

The FTP Service's DefaultLogonDomain is not available in the Microsoft Management Console (MMC), To work around this problem, we need manually add DefaultLogonDomain to the FTP Service in the MMC.

For NT4
you can use either of the following:
• The Metaedit.exe utility, included with the IIS 4.0 Resource Kit.
• The Adsutil.vbs utility that is included with IIS 4.0.

NOTE: By default, Adsutil.vbs is located in the \System32\Inetsrv\Adminsamples folder. Also, you must first install the Windows Script Host before using Adsutil.vbs.

Run Adsutil.vbs from a command prompt, using the appropriate syntax below (depending on whether you want to set DefaultLogonDomain for all FTP sites, just the default FTP site, or other sites):

•To set DefaultLogonDomain for all FTP sites, run the following command:
adsutil set msftpsvc/DefaultLogonDomain "DomainName"

•To set DefaultLogonDomain for only the default FTP site, run the following command:
adsutil set msftpsvc/1/DefaultLogonDomain "DomainName"

•if command listed above fails, you can use the following command instead, which uses the Mdutil utility from the Windows NT Option Pack compact disc:
mdutil.exe set /msftpsvc/1/DefaultLogonDomain "DomainName"

To set DefaultLogonDomain for any other site, use the same syntax as the default FTP site above, but change the "1" parameter to the appropriate service number.

for Windows Server 2000
You can use same method as for NT.

ADSUTIL.VBS runs under Windows 2000 and requires the installation of IIS. The file is usually located in the C:\Inetpub\AdminScripts directory.
MDUTIL.EXE file utility is included on the Windows 2000 CD-ROM as a zipped file. In order to install it on your computer, simply insert the Windows 2000 installation CD and execute a simple command:
expand -r d:\i386\mdutil.ex_ c:\winnt

For Windows Server 2003

In Windows Server 2003, stop IIS service, then add
DefaultLogonDomain="DomainName" in metabase.xml file at the section of
IIsFtpService.

the file is stored in directory: "C:\WINDOWS\system32\inetsrv".

Useful Link

http://www.windowsecurity.com/pages/article_p.asp?id=1297

http://support.microsoft.com/kb/184319