Java 最小的web.xml web-app描述符版本2.5

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	version="2.5">
	<display-name>Archetype Created Web Application</display-name>
        <!--
	<servlet>
		<servlet-name>HelloWorldExample</servlet-name>
		<servlet-class>cnx.mywebapp.HelloWorldExample</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>HelloWorldExample</servlet-name>
		<url-pattern>/hello</url-pattern>
	</servlet-mapping>
        -->
</web-app>

Java 带有STDOUT和Daily Rolling FILE appender的logback.xml配置

<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
	<appender name="STDOUT"
			class="ch.qos.logback.core.ConsoleAppender">
		<layout class="ch.qos.logback.classic.PatternLayout">
			<pattern>%-4relative [%thread] %-5level %class - %msg%n</pattern>
		</layout>
	</appender>

	<!--Basic file appender<appender name="FILE"
		class="ch.qos.logback.core.FileAppender">
		<layout class="ch.qos.logback.classic.PatternLayout">
			<pattern>%-4relative [%thread] %-5level %class - %msg%n</pattern>
		</layout>
		<File>sample-log.txt</File>
	</appender>-->

        <!--Daily rolling file appender -->
	<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
		<File>logFile.log</File>
		<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
			<FileNamePattern>logFile.%d{yyyy-MM-dd}.log</FileNamePattern>
		</rollingPolicy>

		<layout class="ch.qos.logback.classic.PatternLayout">
			<Pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</Pattern>
		</layout>
	</appender>
	
	
	<logger name="deng.mysimpleapp">
		<level value="debug" />
	</logger>
	
	<root>
		<level value="error" />
		<appender-ref ref="STDOUT" />
		<appender-ref ref="FILE" />
	</root>
</configuration>

Java 分配键绑定并设置它们

public void setBindings(JFrame mainFrame){
  JComponent c = mainFrame.getRootPane();
  c.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_O , InputEvent.CTRL_DOWN_MASK), "open project");
  c.getActionMap().put("open project", new OpenProjectAction());
}

Java 简单的JMS模板用法示例

public void sendJMS() {
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-config.xml");
        JmsTemplate jmsTemplate = (JmsTemplate) applicationContext.getBean("jmsTemplate");
        jmsTemplate.send(new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                return session.createTextMessage("hello queue world");
            }
        });
    }

Java Spring MVC中的动态列表绑定| mattfleming.com

<c:forEach items="${grid.blocks}" varStatus="gridRow">
   <spring:bind path="grid.blocks[${gridRow.index}].id"> 
      <c:out value="${status.value}"/> 
      <input type="hidden" 
             name="<c:out value="${status.expression}"/>" 
             id="<c:out value="${status.expression}"/>" 
             value="<c:out value="${status.value}"/>" /> 
   </spring:bind> 
   <spring:bind path="grid.blocks[${gridRow.index}].description"> 
      <c:out value="${status.value}"/> 
      <input type="hidden" 
             name="<c:out value="${status.expression}"/>" 
             id="<c:out value="${status.expression}"/>" 
             value="<c:out value="${status.value}"/>" /> 
   </spring:bind> 
</c:forEach>

Java 简单的尾巴就像断言

public class TailAssertor {

    private static final long sec = 1000L;

    private static final Log log = LogService.getLog(TailAssertor.class.getName());

    private static long sampleInterval = 5000;

    public static void assertNewLinesWithTail(final File logfile, final String expectedLine, int durationInSec) {

        long filePointer = logfile.length();// The file pointer keeps track of where we are in the file
        RandomAccessFile file = null;
        try {
            file = new RandomAccessFile(logfile, "r");
            for (final Date startTime = new Date(); new Date().getTime() - startTime.getTime() < durationInSec * sec;) {
                long fileLength = logfile.length();
                if (fileLength < filePointer) {// file has been cleared
                    file = new RandomAccessFile(logfile, "r");
                    filePointer = 0;
                }
                if (fileLength > filePointer) {
                    file.seek(filePointer);// There is new data to read
                    for (String line = file.readLine(); line != null;) {
                        if (line.contains(expectedLine)) {
                            return;
                        }
                        line = file.readLine();
                    }
                    filePointer = file.getFilePointer();
                }
                Thread.sleep(sampleInterval);// Sleep for the specified interval
            }
        } catch (Exception e) {
            log.error(e);
        } finally {
            closeFile(file);
        }
        throw new AssertionError("the requested line wasn't found within the required time frame!");
    }

    private static void closeFile(RandomAccessFile file) {
        if (file != null) {
            try {
                file.close();
            } catch (IOException e) {
                log.error(e);
            }
        }
    }
}

Java 从完整路径名中提取文件名(不带扩展名)

public static String getFileNameWithoutExtension(String fileName) {
        File tmpFile = new File(fileName);
        tmpFile.getName();
        int whereDot = tmpFile.getName().lastIndexOf('.');
        if (0 < whereDot && whereDot <= tmpFile.getName().length() - 2 ) {
            return tmpFile.getName().substring(0, whereDot);
            //extension = filename.substring(whereDot+1);
        }    
        return "";
    }

Java 从完整路径名中提取文件的扩展名

public static String getFileExtension(String fileName) {
        File tmpFile = new File(fileName);
        tmpFile.getName();
        int whereDot = tmpFile.getName().lastIndexOf('.');
        if (0 < whereDot && whereDot <= tmpFile.getName().length() - 2 ) {
            return tmpFile.getName().substring(whereDot+1);
        }    
        return "";
    }

Java 另一个守则

 public void testRefreshDoesNothingIfClipBoardContentsNotChanged() {
        queue = mockClipBoardQueue(false, "Any thing");

        insertDummyValuesIntoQueue(2);
        assertFalse(queue.refresh());

        assertEquals(2, queue.getQueue().size());
    }

Java Comm写道

import java.io.*;
import java.util.*;
import gnu.io.*;

public class Prntr {
	static Enumeration portList;
	static CommPortIdentifier portId;
	static String messageString = "Send this string to the printer!!!";
	static SerialPort serialPort;
	static OutputStream outputStream;

	public static void main(String[] args) {
		portList = CommPortIdentifier.getPortIdentifiers();

		while (portList.hasMoreElements()) {
			portId = (CommPortIdentifier) portList.nextElement();
			if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
				if (portId.getName().equals("COM1")) {
					try {
						serialPort = (SerialPort) portId.open("SimpleWriteApp",
								2000);
					} catch (PortInUseException e) {
						System.out.println("Port in use Exception");
						return;
					}
					try {
						outputStream = serialPort.getOutputStream();
					} catch (IOException e) {
						System.out.println("IO Exception");
					}
					try {
						serialPort.setSerialPortParams(9600,
								SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
								SerialPort.PARITY_NONE);
					} catch (UnsupportedCommOperationException e) {
						System.out.println("UnSupported comm Operation");
					}
					try {
							outputStream.write(messageString.getBytes());
							outputStream.write(0x0D);
					} catch (IOException e) {
						System.out.println(" IO Exception while writing " + e);
					}
				}
			}
		}
	}
}