Tag Archive for java

Get values from a checkbox

// <input type="checkbox" name="checkboxname" checked="checked"/>

for(String checkboxSelected : request.getParameterValues("checkboxname"))
{
...do stuff
}

source

Download file using a servlet

FileInputStream fileToDownload = new FileInputStream("c:/file.xls");
ServletOutputStream output = response.getOutputStream();
response.setContentType("application/msexcel");
response.setHeader("Content-Disposition", "attachment; filename=CombinedReportAdmin.xls");
response.setContentLength(fileToDownload.available());
int c;
while ((c = fileToDownload.read()) != -1)
{
output.write(c);
}
output.flush();
output.close();
fileToDownload.close();

source

Simply write an Excel file from POI to the file system

InputStream inputStream = getClass().getClassLoader().getResourceAsStream("templates/template_report.xls");
POIFSFileSystem fileSystem = new POIFSFileSystem(inputStream);
HSSFWorkbook workBook = new HSSFWorkbook(fileSystem);
FileOutputStream out = new FileOutputStream("workbook.xls");
workBook.write(out);
out.close();
inputStream.close();

source

Spring and Hibernate simple configuration

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
lazy-init="true" parent="classesListContainer">
<property name="dataSource">
<ref bean="dataSource"/>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.SybaseDialect</prop>
<!--<prop key="hibernate.show_sql">true</prop>-->
<!--<prop key="hibernate.format_sql">true</prop>-->
<!--<prop key="hibernate.hbm2ddl.auto">validate</prop>-->
</props>
</property>
<property name="annotatedClasses">
<list>
<value>com.dummy.DummyClass</value>
<!-- list of all the annotated classes -->
</list>
</property>
</bean>

<!-- A template which works with hbm -->
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate" lazy-init="true">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>

source

Java 5 Enum HIbernate mapping

import org.hibernate.HibernateException;
import org.hibernate.usertype.ParameterizedType;
import org.hibernate.usertype.UserType;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Properties;

/**
* This class implements the Type that will be used in the hbm file, notice that
* the JavaEnumToString & StringToJavaEnum implementation isn't provided
* (all they do is to convert Enum<->String in a consistent way, same goes for
* StringUtils (replaceable with apache commons StringUtils).
*/
public class JavaEnumUserType implements UserType, ParameterizedType {

private static final int[] SQL_TYPE = new int[]{Types.VARCHAR};

private Class<? extends Enum> enumClass;

private static JavaEnumToString javaEnumToString = new JavaEnumToString();

private static StringToJavaEnum stringToJavaEnum = new StringToJavaEnum();

public void setParameterValues(Properties parameters) {
String enumClassName = parameters.getProperty("enumClass");
try {
enumClass = Class.forName(enumClassName).asSubclass(Enum.class);
} catch (ClassNotFoundException e) {
throw new HibernateException("Class " + enumClassName + " not found ", e);
}
}

public Object assemble(Serializable cached, Object owner)
throws HibernateException {
return cached;
}

public Object deepCopy(Object value) throws HibernateException {
return value;
}

public Serializable disassemble(Object value) throws HibernateException {
return (Enum) value;
}

public boolean equals(Object x, Object y) throws HibernateException {
return x == y;
}

public int hashCode(Object x) throws HibernateException {
return x.hashCode();
}

public boolean isMutable() {
return false;
}

public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException {
String value = rs.getString(names[0]);
if (rs.wasNull() || StringUtils.isNullOrEmpty(value)) {
return null;
}
return stringToJavaEnum.doConvert(value.trim(), enumClass);
}

public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
if (value == null) {
st.setNull(index, Types.VARCHAR);
} else {
String stringValue = javaEnumToString.doConvert((Enum) value);
st.setString(index, stringValue);
}
}

public Object replace(Object original, Object target, Object owner)
throws HibernateException {
return original;
}

public Class returnedClass() {
return enumClass;
}

public int[] sqlTypes() {
return SQL_TYPE;
}

}

// For example the following bean:

public class DummyBean{

private DummyEnum dummyProp;

public DummyEnum getDummyProp() {
return dummyProp;
}

public void setPageDescriptor(DummyEnum _dummyProp) {
this.dummyProp = _dummyProp;
}

}

// will be mapped in this fashion:

<hibernate-mapping>
<class name="com.dummy.DummyBean" table="DUMMY_TABLE">

<property name="dummyProp" column="DUMMY_PROP">
<type name="com.dummy.JavaEnumUserType">
<param name="enumClass">com.dummy.DummyEnum</param>
</type>
</property>
</hibernate-mapping>

source

Comm write

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);
}
}
}
}
}
}

source

Time comparation in Java

public static boolean isDateBefore(String date1,String date2){
try{
DateFormat df = DateFormat.getDateTimeInstance();
return df.parse(date1).before(df.parse(date2));
}catch(ParseException e){
System.out.print("[SYS] " + e.getMessage());
return false;
}
}

source

Some new Rails Title

    public void testRefreshDoesNotAddContentIfAlreadyExists(){
queue = mockClipBoardQueue(true,"1");
insertDummyValuesIntoQueue(3);
assertFalse(queue.refresh());
assertEquals(3, queue.getQueue().size());
}

source

Another Code

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

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

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

source

AS2 JS FlashからJavascriptを呼ぶ

// htmlヘッダ
function showDialog(message){
alert(message);
}

// Flash側
// ExternalInterfaceライブラリをインポート
import flash.external.ExternalInterface;

// ボタンとかで
callBtn.onPress = function():Void{
var str:String = textBox.text;
ExternalInterface.call("showDialog", str);
}

source