發表文章

目前顯示的是 2012的文章

JAX-WS WebService Time Out

WebS_Service service = new WebS_Service(wsdlLocation, qName); WebS webS = service.getWebSPort(); Map requestContext = ((BindingProvider)webS).getRequestContext(); requestContext.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, wsdlUrl); requestContext.put(BindingProviderProperties.REQUEST_TIMEOUT, 3000); // Timeout in millis requestContext.put(BindingProviderProperties.CONNECT_TIMEOUT, 1000); // Timeout in millis

difference between request.getRequestDispatcher() and response.sendRedirect()

Forward( ) : javax.Servlet.RequestDispatcher interface. - RequestDispatcher.forward( ) works on the Server. - The forward( ) works inside the WebContainer. - The forward( ) restricts you to redirect only to a resource in the same web-Application. - After executing the forward( ), the control will return back to the same method from where the forward method was called. - The forward( ) will redirect in the application server itself, it does'n come back to the client. - The forward( ) is faster than Sendredirect( ) . To use the forward( ) of the requestDispatcher interface, the first thing to do is to obtain RequestDispatcher Object. The Servlet technology provides in three ways. 1. By using the getRequestDispatcher( ) of the javax.Servlet.ServletContext interface , passing a String containing the path of the other resources, path is relative to the root of the ServletContext. RequestDispatcher rd=request.getRequestDispatcher ("secondServlet"); Rd.forward(reque

Export excel from Extjs Grid

exporter.js: /** * allows for downloading of grid data (store) directly into excel * Method: extracts data of gridPanel store, uses columnModel to construct XML excel document, * converts to Base64, then loads everything into a data URL link. * * @author Animal * */ /** * base64 encode / decode * * @location http://www.webtoolkit.info/ * */ var Base64 = (function() { // Private property var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; // Private method for UTF-8 encoding function utf8Encode(string) { string = string.replace(/\r\n/g,"\n"); var utftext = ""; for (var n = 0; n < string.length; n++) { var c = string.charCodeAt(n); if (c < 128) { utftext += String.fromCharCode(c); } else if((c > 127) && (c < 2048)) { utftext += String.fromCharCode((c >> 6)

Simple Cross Site Scripting (XSS) Servlet Filter

XSSFilter: public class XSSFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void destroy() { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { chain.doFilter(new XSSRequestWrapper((HttpServletRequest) request), response); } } The HttpServletRequest Wrapper: import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; public class XSSRequestWrapper extends HttpServletRequestWrapper { public XSSRequestWrapper(HttpServletRequest servletRequest) { super(servletRequest); } @Override public String[] getParameterValues(String parameter) { String[] values = super.getParameterValues(parameter); if (values == null) { return null; }

How to prevent cross-site scripting (XSS)

You should HTML escape any input before outputting it back to the user. OWASP XSS (Cross Site Scripting) Prevention Cheat Sheet Consider using   StringEscapeUtils.escapeHtml()   from   Apache Commons Lang Or use   HtmlUtils.htmlEscape()   from   Spring XSS attack prevention XSS prevention in Java JSoup whitelist sanitizer How to encode and store string to prevent XSS

Call VB script in Java code

import java.io.BufferedReader; import java.io.File; import java.io.FileWriter; import java.io.InputStreamReader; public class VBSUtils { private VBSUtils() { } public static boolean isRunning(String process) { boolean found = false; try { File file = File.createTempFile("realhowto",".vbs"); file.deleteOnExit(); FileWriter fw = new java.io.FileWriter(file); String vbs = "Set WshShell = WScript.CreateObject(\"WScript.Shell\")\n" + "Set locator = CreateObject(\"WbemScripting.SWbemLocator\")\n" + "Set service = locator.ConnectServer()\n" + "Set processes = service.ExecQuery _\n" + " (\"select * from Win32_Process where name='" + process +"'\")\n" + "For Each process in processes\n" + "wscript.echo pr

Check if java process is running with VB script

Option Explicit Dim objWMIService, objProcess, colProcess, StdOut Dim strComputer, strProcess, strCommand strComputer = "." ' local computer strProcess = "javaw.exe" strCommand = "BatchReportingClient.jar" ' Check if java process is running on specified computer (. = local computer) IF isProcessRunning(strComputer,strProcess, strCommand) THEN wscript.echo strProcess & " is running on computer '" & strComputer & "'" ELSE wscript.echo strProcess & " is NOT running on computer '" & strComputer & "'" END IF ' Function to check if a process is running FUNCTION isProcessRunning(BYVAL strComputer,BYVAL strProcessName, BYVAL strCommand) DIM objWMIService, strWMIQuery strWMIQuery = "Select * from Win32_Process where name like '" & strProcessName & "'" & " and commandLine like'%" & strCommand & "%

Chekc if process is running with VB script

OPTION EXPLICIT DIM strComputer,strProcess strComputer = "." strProcess = "wrapper.exe" ' Check if Wrapper is running on specified computer IF isProcessRunning(strComputer,strProcess) THEN wscript.echo strProcess & " is running on computer '" & strComputer & "'" ELSE wscript.echo strProcess & " is NOT running on computer '" & strComputer & "'" END IF FUNCTION isProcessRunning(BYVAL strComputer,BYVAL strProcessName) DIM objWMIService, strWMIQuery strWMIQuery = "Select * from Win32_Process where name like '" & strProcessName & "'" SET objWMIService = GETOBJECT("winmgmts:" _ & "{impersonationLevel=impersonate}!\\" _ & strComputer & "\root\cimv2") IF objWMIService.ExecQuery(strWMIQuery).Count > 0 THEN isProcessRunning = TRUE ELSE isProcessRunning = FALSE END IF END FUNCTION

Run the console application at background (hide the console window)

Create a VB script with the following content: Set WshShell = CreateObject("WScript.Shell") WshShell.Run chr(34) & "Your command to run, bat or exe" & Chr(34), 0 Set WshShell = Nothing

Java Wrapper Framework

Comparison of Java Wrapper Framework Comparison of wrapper frameworks YAJSW :   Yet Another Java Service Wrapper JSW :   Java Service Wrapper ACD :   Apache Commons Daemon L4J :   Launch4j Note: If you would like to add further frameworks or in case of errors in the table please inform me. Features/Framework YAJSW JSW ACD L4J License LGPL GPL/Commercial Apache BSD/MIT Run as Windows Service X X X   Run as UNIX Daemon X X X   Support Mac OS X launchd X       Platform indepemdent installation of services/Daemons X       Java Embedable X       Wrap Java Application X X X X Wrap Groovy Script X Wrap native executable X   X   Wrap as executable       X Portable Configuration X X     Capture and Log console output X X     Stop and Reconnect Wrapper X       Monitor Application X X X   Restart Application X X X   Single Instance Enforcement X X   X Control Process Priority X X     Control Process Affinity X       Alert Emails X X (Commercial)     Scripting X    

Version string comparison in Java

1. Use maven API - DefaultArtifactVersion class import org.apache.maven.artifact.versioning.DefaultArtifactVersion; DefaultArtifactVersion minVersion = new DefaultArtifactVersion("1.0.1"); DefaultArtifactVersion maxVersion = new DefaultArtifactVersion("1.10"); DefaultArtifactVersion version = new DefaultArtifactVersion("1.11"); if (version.compareTo(minVersion) == -1 || version.compareTo(maxVersion) == 1) { System.out.println("Sorry, your version is unsupported"); } 2. Create a VersionComparator class // VersionComprator.java import java.util.Comparator; public VersionComprator implements Comparator { public boolean equals(Object o1, Object o2) { return compare(o1, o2) == 0; } public int compare(Object o1, Object o2) { String version1 = (String) o1; String version2 = (String) o2; VersionTokenizer tokenizer1 = new VersionTokenizer(version1); Versio

Shutting down windows operating system by Java

public class Main { public static void main(String[] args) throws IOException { String shutdownCommand=""; String operatingSystem = System.getProperty("os.name"); if ("Linux".equals(operatingSystem) || "Mac OS X".equals(operatingSystem)) { shutdownCommand = "shutdown -h now"; } else if (operatingSystem.startWith("Window")) { shutdownCommand = "shutdown -s -t 0"; } Runtime.getRuntime().exec(shutdownCommand); System.exit(0); } }

Event called when application is being closed

Use Runtime class to register a thread which will be called when the program is being closed.   Runtime . getRuntime (). addShutdownHook ( theHookThread );   Reference: http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Runtime.html#addShutdownHook%28java.lang.Thread%29

Implement a single instance JAVA application

1. Use file lock to ensure single instance is running for this application. private static boolean lockInstance(final String lockFile) { try { final File file = new File(lockFile); final RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw"); final FileLock fileLock = randomAccessFile.getChannel().tryLock(); if (fileLock != null) { Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try { fileLock.release(); randomAccessFile.close(); file.delete(); } catch (Exception e) { log.error("Unable to remove lock file: " + lockFile, e); } } }); return true; } } catch (Exception e) { log.error("Unable to create and/or lock file: " + lockFile, e); } return false; } 2. Another file locking example: 2a.JustOneLock.ja

Windows cannot delete file or folder

Reboot Reboot, then delete. DEL or RMDIR Open a command line window (WindowsKey + R, enter: cmd). Move to the folder in question by means of CD commands like CD \ and CD foldername. Delete the file or folder by using the DEL command to delete files or the RMDIR (remove directory) command to remove directories (folders). Kill explorer.exe If this, on its own, is still not enough, then leave the command line window on the desktop, open Task Manager (Ctrl + Shift + Esc), and kill all explorer.exe tasks. Your desktop will go blank, except for the windows already open. Now try to delete the offending file by means of the DEL command, or folder by means of the RMDIR (remove directory) command, in the command line window, as described above. After that, in the command line window enter: explorer to restart your desktop. If you closed the command line window, you can still restart explorer by opening the Task Manager by holding down the Ctrl and Shift keys and briefly p