http://best-practice-software-engineering.ifs.tuwien.ac.at/
Decompiler .java
jar -xf comirva-src-0.3.jar
Enum Error --> downgrade java 1.4
Project -> Properties -> Java Compiler -> Compiler compliance level) to be 1.4 or under? You need 1.5 (5.0) or 1.6 (6.0) for enum declarations to be correct.
Mig Layout Java - Desktop Application
http://www.miglayout.com/
Diagram for Hierarchy of Exception Classes
Java default vs protected access
Diagram to show java string’s immutability
http://best-practice-software-engineering.ifs.tuwien.ac.at/index.html
http://best-practice-software-engineering.blogspot.com/
Eclipse
eclipse.iniSet jre classpath for eclipse
-vm
c:/java/jdk16012/jre/bin/javaw.exe
Java Alamanac
http://www.exampledepot.com/
www.java2s.com
Get Current Directory
File templateDir = new File (".");
System.out.println(templateDir.getCanonicalPath() + "\\web\\templates\\");
Another app data
- Local AppData (C:\Documents and Settings\USER\Local Settings\Application Data)
- Local Settings (C:\Documents and Settings\USER\Local Settings)
- AppData (C:\Documents and Settings\USER\Application Data)
System.getProperty("user.home")
File f = new File(System.getenv("AppData"+"Mozilla/Firefox/Profiles"));
Jena - schemagen.java
//args = new String[] { "-i", "G:/java/appjava/netbeansapp/org.owls.gapi/src/eowl/music.owl" ,"--ontology","--uppercase"};
args = new String[] { "-i", "C:/AppServ/www/Ontology/mysws/MyResource.owl" ,"--owl","--uppercase","--package", "vocabularies","-o", "C:/AppServ/www/Ontology/mysws"};
call a webserivce from a Jsp page
Preconditions: You have working WebService and know its URI (I used http://localhost:8080/helloservice/hello, installed on my machine) Steps: SECTION 1. Stubs creation. 1. Add Axis libs into CLASSPATH. For me it was: <Axis_1_3_home>/lib/axis.jar:<Axis_1_3_home>/lib/commons-logging-1.0.4.jar:<Axis_1_3_home>/lib/commons-discovery-0.2.jar:<Axis_1_3_home>/lib/jaxrpc.jar:<Axis_1_3_home>/lib/saaj.jar:<Axis_1_3_home>/lib/wsdl4j-1.5.1.jar 2. Genearte stubs. java org.apache.axis.wsdl.WSDL2Java <WS_URI>?wsdl For me it was: java org.apache.axis.wsdl.WSDL2Java http://localhost:8080/helloservice/hello?wsdl After that you will have Java Stubs generated accrding to WSDL in your current directory. For me it was: ./helloservice/endpoint/HelloPortBindingStub.java ./helloservice/endpoint/HelloService.java ./helloservice/endpoint/Hello.java ./helloservice/endpoint/HelloServiceLocator.java 3. Compile stubs. In my case it was: javac -d . helloservice/endpoint/*.java 4. Test that stub is working by simple command line client: (name it Main.java, compile and execute) ---------------------------- import helloservice.endpoint.*; public class Main { public static void main(String[]args) throws Exception{ String name="My Name :)"; HelloService service = new HelloServiceLocator(); Hello port = service.getHelloPort(); String response = port.sayHello(name); System.out.println(response); } } --------------------------- So now we are going to create WebApp client (Jsp or Servlet) SECTION 2. WS Jsp/Servlet client using Axis 1. Create directory: <wb_root>/WEB-INF/lib 2. Copy everything from <Axis_1_3_home>/lib/ to <wb_root>/WEB-INF/lib directory 3. Jar your stubs (jar -cvf hellostub.jar helloservice/) and also copy to <wb_root>/WEB-INF/lib 4. Create index.jsp in the <wb_root>: index.jsp: -------------------------------------------- <%@ page import="helloservice.endpoint.HelloServiceLocator,helloservice.endpoint.Hello, helloservice.endpoint.HelloService" %> <html><body> Text: <% HelloService service = new HelloServiceLocator(); Hello port = service.getHelloPort(); String resp = port.sayHello(request.getParameter("username")); %> <h2><font color="black"><%=resp%></font></h2> </body> </html> -------------------------------------------- 5. Create web.xml file in <wb_root>/WEB-INF/ -------------------------------------------- <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" version="2.5" xmlns:xsi="http://www.w3.org/2001/XMLSchema" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name>webclient</display-name> </web-app> --------------------------------------------- 6. Simple copy your web app into <tomcat>/webapps/ For me it was: cp -r <wbroot>/* <tomcat>/wcc 7. Test your client in browser by typing: http://localhost:8080/wcc/index.jsp Or,(to pass parameter in my case), http://localhost:8080/wcc/index.jsp?username=Guest
ERRORS
'Access restriction: The type is not accessible due to restriction on required library xxx.jar' (perhaps using some combination of Eclipse 3.4 and/or JDK 6 update 10?),
You need to go into the Build Path for the project, Libraries tab, select the JRE System Library, and add an access rule, "Accessible, **".
CONVERT STRING TO BOOLEAN
String strBoolean = "true";
boolean theValue = Boolean.parseBoolean(strBoolean);
READ DIR & List Files
File dir = new File("owls");
String [] fileNames = dir.list(); //List FileName
File [] fileObjects= dir.listFiles(); //List FileObject
for (int i = 0; i < fileObjects.length; i++) {
if(!fileObjects[i].isDirectory()){
System.out.println(fileNames[
System.out.println(fileObjects[i].length());
}
}
String.startsWith("http:") ) return new HttpURLConnection();
else if( String.startsWith("ftp:") ) return new FtpURLConnection();
Recursive List
Here is an example of listing files and directories recursively.1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | // File : io/file/RecusiveList.java // Purpose: Recursively list directories and files. // Author : Fred Swartz 1997-08-06 (Bangkok, Thailand), 2000-10-31 (Rota, Spain) // 2006-09-25 (Rodenbach, Deutschland) import java.util.*; import java.io.*; public class RecursiveList { static final int MAX_DEPTH = 20; // Max 20 levels (directory nesting) static final String INDENT_STR = " "; // Single indent. static final String[] INDENTS = new String[MAX_DEPTH]; // Indent array. //===================================================================== main public static void main(String[] args) { //... Initialize array of indentations. INDENTS[0] = INDENT_STR; for (int i = 1; i < MAX_DEPTH; i++) { INDENTS[i] = INDENTS[i-1] + INDENT_STR; } System.out.print("Enter a directory name to list recursively:"); Scanner in = new Scanner(System.in); File root = new File(in.nextLine()); if (root != null && root.isDirectory()) { listRecursively(root, 0); } else { System.out.println("Not a directory: " + root); } } //========================================================== listRecursively public static void listRecursively(File fdir, int depth) { System.out.println(INDENTS[depth] + fdir.getName()); // Print name. if (fdir.isDirectory() && depth < MAX_DEPTH) { for (File f : fdir.listFiles()) { // Go over each file/subdirectory. listRecursively(f, depth+1); } } } } |
java.lang.ClassCastException: [Ljava.lang.String; cannot be cast to java.lang.String
Very simply, you get the exceptionjava.lang.ClassCastException: [Ljava.lang.String; cannot be cast to java.lang.String
when you try to cast an array kind of a class to the linear type. In this case, attempting to cast String -> String[] or vice versa will cause the JVM to throw this particular exception at runtime. Compilers cannot catch this oversight.
As an example, consider an attempt to read all parameters passed to a servlet using the request object. The parameter map can be obtained with:
Map parameters = request.getParameterMap();
From HTML basics, we know that parameters are passed as key/value pairs of Strings to the web server, so the temptation is to assume that the generics mapping for parameters is <String, String>. In fact, compilers will allow you to use this generic:
Map<String,String> parameters = request.getParameterMap();
for(String key: parameters.keySet()) {
String value = parameters.get(key); // error happens here
System.out.println(key + "=" + value);
}
This code snippet will compile and run fine, producing results that look like:
firstName=[Ljava.lang.String;@1fe49b5
lastName=[Ljava.lang.String;@1993b4f
This is assuming parameters passed to the servlet (or JSP) include ones named 'firstName' and 'lastName', of course.
As it turns out, the value side of the parameter map is actually a String[] type. So the proper generic for this map is <String, String[]>. When you call request.getParameter("firstName");, it simply returns the equivalent of parameters.get(key)[0];, which reads the first value associated with the key. This happens even if your form might have sent single-dimension parameters for processing.
So, just remembering the map's generics mapping may save you a lot of headaches down the road. This is simple Java internals - but a look at forums on the web shows how much of a problem this is for programmers out there. You's get the same kind of exception if you attempted to cast Date to Date[] (which would throw java.lang.ClassCastException: java.util.Date cannot be cast to [Ljava.util.Date;).
Dealing with nulls
UtilFactory.convertNull
Java – comparing strings
Use == for primitive data types like intIf (mystring == null)
Use the equals() method to compare objects
Use .equals for strings : if (a.equals(“cat”))
Java - Converting int to string
String myString = Integer.toString(my int value)
or
String str = "" + iJava - Converting String to int
int i = Integer.parseInt(str);
or
int i = Integer.valueOf(str).intValue();
List String to Array String
List<String> tokenList = Tokenizer.wordsToList(sentence);
String[] tokenArray = (String[]) tokenList.toArray();
double to String :
String str = Double.toString(i);
long to String :
String str = Long.toString(l);
float to String :
String str = Float.toString(f);
String to double :
double d = Double.valueOf(str).doubleValue();
String to long :
long l = Long.valueOf(str).longValue();
or
long l = Long.parseLong(str);String to float :
float f = Float.valueOf(str).floatValue();
decimal to binary :
int i = 42;
String binstr = Integer.toBinaryString(i);decimal to hexadecimal :
int i = 42;
String hexstr = Integer.toString(i, 16);
or
String hexstr = Integer.toHexString(i);
or (with leading zeroes and uppercase)
public class Hex {
public static void main(String args[]){
int i = 42;
System.out.print
(Integer.toHexString( 0x10000 | i).substring(1).toUpperCase());
}
}
hexadecimal (String) to integer :
int i = Integer.valueOf("B8DA3", 16).intValue();
or
int i = Integer.parseInt("B8DA3", 16); ASCII code to String
int i = 64;
String aChar = new Character((char)i).toString();integer to ASCII code (byte)
char c = 'A';
int i = (int) c; // i will have the value 65 decimalinteger to boolean
b = (i != 0);
boolean to integer
i = (b)?1:0;
Java Validate Credit Card
- http://www.rgagnon.com/javadetails/java-0034.html
- http://www.codeproject.com/KB/aspnet/wdxcreditcardvalidation.aspx
String Array
static String [] sw={ "a", "able", "about"}
public static String[] getStopWordList() {return(sw);}
public class Stopwords
{
public static Vector removeSW(Vector vm)
{
List sw;
sw=Arrays.asList(stopList.getStopWordList());
Vector v=new Vector();
for(int i=0;i<vm.size();i++)
{
if((sw.contains(vm.elementAt(i))) |((vm.elementAt(i)).toString()).matches("[0-9]+"))
{
}
else
{
v.addElement(vm.elementAt(i));
}
}
return(v);
}
}
The collection classes in java.util include some of the most commonly used classes in Java. The most commonly used collection types are List and Map. Concrete implementations of List include ArrayList and Vector, which are variable size lists ideal for building, storing and manipulating a list of elements of any type of object. Lists are ideal when you want to access elements by numerical index.String Arrays
Maps provide a more general way of storing elements. The Map collection type allows you to store pairs of elements, termed "keys" and "values", where each key maps to one value. Conceptually, you could consider Lists as Maps which have numeric keys. However in practice there no direct connection between Lists and Maps except that they are both defined in java.util. In this article, we will focus on the Maps that are available with the core Java distribution, and also consider how to adapt or implement specialized Maps that are more optimal for your application specific data.
String Comparison
Strings can not be compared with the usual <, <=, >, or >= operators, and the == and != operators don't compare the characters in the strings.
Comparing Strings: ==, .equals(), .compareTo(), ...
To compare Strings for equality, don't use ==. The == operator checks to see if two objects are exactly the same object. Two strings may be different objects, but have the same value (have exactly the same characters in them). Use the .equals() method to compare strings for equality. Similarly, use the .compareTo() method to test for unequal comparisons. For example,
String s = "something", t = "maybe something else"; if (s == t) // Legal, but usually WRONG. if (s.equals(t)) // RIGHT if (s > t) // ILLEGAL if (s.compareTo(t) > 0) // CORRECT>
Java 5 finally introduced support for printing out arrays. The java.util.Arrays utility class has methods for providing a pretty toString for any shape array, including
String[] arry = new String[] { "Test", "Array", "toString" }; // prints out [Test, Array, toString] System.out.println(Arrays.toString(arry));You may notice that the output of these methods matches up closely to the output of the standard list implementations in the collections API.
If you have a multi-dimensional array, you may and you want all of the arrays in that multi-dimensional array to print out, you can use the alternative method - deepToString :
String[][] arry = new String[][] {
{ "Test", "Array", "1" },
{ "Test", "Array", "2" },
{ "Test", "Array", "3" }
};
// prints out:
// [[Test, Array, 1], [Test, Array, 2], [Test, Array, 3]]
System.out.println(Arrays.deepToString(arry));
Print Array
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
{ "Test", "Array", "1" },
{ "Test", "Array", "2" },
{ "Test", "Array", "3" }
};
// prints out:
// [[Test, Array, 1], [Test, Array, 2], [Test, Array, 3]]
System.out.println(Arrays.deepToString(arry));
Print Array
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
Question: | How do I convert a String to a float with Java? |
Answer: |
Converting a String to a float requires that you first convert the String to a Float object, then convert the Float object to a float data type (Float is an object, while float is a primitive data type). An example of a simple program that performs this conversion is shown below: Other notespublic class s2f { public static void main (String[] args) { // String s = "fred"; // do this if you want an exception String s = "100.00"; try { float f = Float.valueOf(s.trim()).floatValue(); System.out.println("float f = " + f); } catch (NumberFormatException nfe) { System.out.println("NumberFormatException: " + nfe.getMessage()); } } }
|
Array & List
//String[] listProperties = new String[100];
List list = new ArrayList();
//int index = 0;
for (ExtendedIterator j = ocl.listDeclaredProperties(); j.hasNext();) {
list.add(j.next().toString());
//System.out.println((OntProperty) j.next());
//System.out.println(index + j.next().toString());
//listProperties[index]= j.next().toString();
//index = index + 1;
}
String[] array = (String[]) list.toArray(new String[list.size()]);
System.out.println(Arrays.toString(array));
Duyệt List
List li = oclass.getDeclaredProperties();
ListIterator k = li.listIterator(li.size());
while (k.hasPrevious()) {
Object element = k.previous();
System.out.println("Properties: " + element.toString());
}
Property[] list = new Property[100];
for (ExtendedIterator j = ocl.listDeclaredProperties(); j.hasNext();) {
String y = j.next().toString();
String xyz = y.substring(Foaf.getURI().length());
System.out.print(xyz);
list[index]= (Property) j.next();
index = index + 1;
}
Generate pairs of random Sentence
String[] articles = { "a", "the", "an", "one", "the first" };
String[] noun1 = { "cat", "dog", "sun", "rain", "boot" };
String[] verb = { "sit", "catch", "stab", "chase", "cuddle" };
String[] noun2 = { "summer", "gun", "chair", "bag", "woman" };
Random r = new Random();
for (int i = 1; i <= 10; i++) {
int selectedElement = r.nextInt(articles.length);
int selectedElement2 = r.nextInt(articles.length);
String randomSentence = articles[selectedElement] + " "
+ noun1[selectedElement] + " " + verb[selectedElement]
+ " " + articles[selectedElement] + " "
+ noun2[selectedElement];
String randomSentence2 = articles[selectedElement] + " "
+ noun1[selectedElement2] + " " + verb[selectedElement2]
+ " " + articles[selectedElement2] + " "
+ noun2[selectedElement2];
System.out.println("sentence 1:" + randomSentence);
System.out.println("sentence 2:" + randomSentence2);
}
Lấy giá trị từ OWL Schema
RDFNode node = thisIndividual.getPropertyValue(Foaf.FAMILY_NAME);
if (node != null) {
System.out.println(node.toString());
}
DateTime in Java
GWT
The import com.gwtext cannot be resolved & Unable to find 'com/gwtext/GwtExt.gwt.xml'
<inherits name='com.gwtext.GwtExt' /> & put the gwtext.jar in the build.xm
Axis2
Options options = new Options();
options.setManageSession(true);
ServiceClient sender = new ServiceClient();
sender.setOptions(options);
MySQL Connection & Create Table
package manage;import java.sql.*;
public class DatabaseInit {
final public static String CONN_STRING="jdbc:mysql://localhost/database";
final public static String USERNAME = "root";
final public static String PASSWORD = "";
public static void createTables() throws Exception {
Class.forName ( "org.mysql.Driver" );
Connection conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
java.sql.Statement stmt = conn.createStatement();
stmt.execute("CREATE TABLE user(userid VARCHAR, password VARCHAR)");
conn.close();
}
public static void main(String[] args) throws Exception {
createTables();
}
}
Hybernate
Error
org.hibernate.QueryException: ClassNotFoundException: org.hibernate.hql.ast.HqlToken [select a.password from employee.dbbeans.LoginBean as a where a.userName = ?]
Solution is to add following property to the hibernate configuration file hibernate.cfg.xml
<property name="hibernate.query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory</property>
TIME UNITS
import java.util.concurrent.TimeUnit;
public class TimeUnitDemo {
public static void main(String[] args) {
TimeUnit tu = TimeUnit.DAYS;
System.out.println(tu.toDays(1));
System.out.println(tu.toHours(1));
System.out.println(tu.toMinutes(1));
}
}
1. Date() + SimpleDateFormat()
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date));
Date date = new Date();
System.out.println(dateFormat.format(date));
2. Calender() + SimpleDateFormat()
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));
http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class GetCurrentDateTime {
public static void main(String[] args) {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
//get current date time with Date()
Date date = new Date();
System.out.println(dateFormat.format(date));
System.out.println(DateUtils.now("dd MMMMM yyyy"));
System.out.println(DateUtils.now("yyyyMMdd"));
System.out.println(DateUtils.now("dd.MM.yy"));
System.out.println(DateUtils.now("MM/dd/yy"));
System.out.println(DateUtils.now("yyyy.MM.dd G 'at' hh:mm:ss z"));
System.out.println(DateUtils.now("EEE, MMM d, ''yy"));
System.out.println(DateUtils.now("h:mm a"));
System.out.println(DateUtils.now("H:mm:ss:SSS"));
System.out.println(DateUtils.now("K:mm a,z"));
System.out.println(DateUtils.now("yyyy.MMMMM.dd GGG hh:mm aaa"));
//get current date time with Calendar()
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));
}
}
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class GetCurrentDateTime {
public static void main(String[] args) {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
//get current date time with Date()
Date date = new Date();
System.out.println(dateFormat.format(date));
System.out.println(DateUtils.now("dd MMMMM yyyy"));
System.out.println(DateUtils.now("yyyyMMdd"));
System.out.println(DateUtils.now("dd.MM.yy"));
System.out.println(DateUtils.now("MM/dd/yy"));
System.out.println(DateUtils.now("yyyy.MM.dd G 'at' hh:mm:ss z"));
System.out.println(DateUtils.now("EEE, MMM d, ''yy"));
System.out.println(DateUtils.now("h:mm a"));
System.out.println(DateUtils.now("H:mm:ss:SSS"));
System.out.println(DateUtils.now("K:mm a,z"));
System.out.println(DateUtils.now("yyyy.MMMMM.dd GGG hh:mm aaa"));
//get current date time with Calendar()
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));
}
}
import java.util.Vector;
public class VectorBenchmark1 {
public static final int MaxSize = 100000;
public static final int NTRIES = 10;
public static void main(String[] args) {
Vector v = new Vector();
long start = System.currentTimeMillis();
for (int i = 0; i < MaxSize; i++)
v.add(new Integer(i));
long end = System.currentTimeMillis();
System.out.println("Allocating vector elements: " + (end - start)
+ " milliseconds");
Integer[] integerArray = new Integer[1];
start = System.currentTimeMillis();
for (int i = 0; i < MaxSize; i++) {
if (i >= integerArray.length) {
Integer[] b = new Integer[i * 2];
System.arraycopy(integerArray, 0, b, 0, integerArray.length);
integerArray = b;
}
integerArray[i] = new Integer(i);
}
end = System.currentTimeMillis();
System.out.println("Allocating array elements: " + (end - start)
+ " milliseconds");
start = System.currentTimeMillis();
for (int j = 0; j < NTRIES; j++)
for (int i = 0; i < MaxSize; i++) {
Integer r = (Integer) v.get(i);
v.set(i, new Integer(r.intValue() + 1));
}
end = System.currentTimeMillis();
System.out.println("Accessing vector elements: " + (end - start)
+ " milliseconds");
start = System.currentTimeMillis();
for (int j = 0; j < NTRIES; j++)
for (int i = 0; i < MaxSize; i++) {
Integer r = integerArray[i];
integerArray[i] = new Integer(r.intValue() + 1);
}
end = System.currentTimeMillis();
System.out.println("Accessing array elements: " + (end - start)
+ " milliseconds");
}
}
0 comments:
Post a Comment