發表文章

目前顯示的是 2011的文章

Debug EdtFTP

Debug Edf FTP library by : Add -Dedtftp.log.level=DEBUG for the system properties. Add Logger.setLevel(Level.DEBUG); in the source code.

Optimizing the EclipseLink Application (ELUG)

Reference: http://wiki.eclipse.org/Optimizing_the_EclipseLink_Application_%28ELUG%29

SQL Developer 3 - Connecting to SQL Server Using Third Party Drivers

Here's a Quick How To Connect SQL Devleoper 3 to SQL Server or MySQL Note that you can use "Check For Updates" to locate the available drivers. Click Help->Check For Updates Then check the boxes to enable Oracle Extensions and Third Party SQL Devleoper Extensions In the list scroll down to JTDS JDBC Driver 11.1.58.17 or directly download the JTDS JDBC Driver Restart SQL Developer  And then Click Tools->Preferences->Database->Third Party Drivers Add the JTDS driver. Now if you get a message that says java.sql.SQLException: I/O Error: SSO Failed: Native SSPI library not loaded. You are missing a DLL. Go to SourceForge and download jtds-version-dist.zip and find the missing DLL called ntlmauth.dll Put that anywhere in your path and restart SQL Developer.

EclipseLink How to Configure Primary Key Generation

Using Sequence Objects When using a database that supports sequence objects (such as Oracle Database), EclipseLink can use a database sequence object to automatically generate identifiers for your persistent objects. Using A Default Sequence EclipseLink can produce a default sequence during schema generation. If you use schema generation, then specify that your identifier should be generated and that the SEQUENCE strategy be used to perform the generation. In the following example, the @GeneratedValue annotation indicates that the identifier value should be automatically generated; a strategy of SEQUENCE indicates that a database sequence should be used to generate the identifier. EclipseLink will create a default sequence object during schema generation that will be used at run time. @ Entity public class Inventory implements Serializable {   @Id @GeneratedValue ( strategy=GenerationType. SEQUENCE ) private long id; Spec

JasperServer with NoClassDefFoundError

Problem: JasperServer with java.lang.NoClassDefFoundError: net/sf/jasperreports/engine/util/JRStyledTextParser or Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'fontBean131398302334587677' Solution: Add java.awt.headless=true as the server start arguments.

JavaScript and memory leaks

http://www.javascriptkit.com/javatutors/closuresleak/index.shtml

Multiple writable mappings exist for the field. Only one may be defined as writable, all others must be specified read-only.

In entity bean, the foreign key usually replaced by the referential relationship such as : public class Status implements Serializable {     /**      *      */     private static final long serialVersionUID = 1L;     @Column(name="creation_datetime", nullable = false)     private Timestamp creationDatetime;     @Id     @Column(name="seq_no", nullable = false)     @GeneratedValue(strategy=GenerationType.IDENTITY)     private Integer seqNo;     @Column(name="status", nullable = false)     private String status;     @Column(name="car_id", nullable = false, insertable=false, updatable=false)     private String carId;     @ManyToOne     @JoinColumn(name = "car_id")     private Transaction transaction;     public Status() {     }     public Status(Timestamp creation_datetime,                           Transaction transaction,                           Integer seqNo, String status, String carId) {         this.creationDatetime = creati

Servlet 3.0 Tutorial: @WebListener, @WebServlet, @WebFilter and @WebInitParam

http://blog.caucho.com/2009/10/06/servlet-30-tutorial-weblistener-webservlet-webfilter-and-webinitparam/

When should we close the EntityManager and EntityManagerFactory

For EntityManager: It depends on how you obtained it.  If you created it using EntityManagerFactory you will have to close it no matter what framework you use. If you obtained it using dependency injection (eg using EJB and @PersistenceContext annotation) you should not close it by hand. It's the EntityManager that is actually associated to a database connection and closing the EntityManager will actually release the JDBC connection (most often, return it to a pool). For EntityManagerFactory: Closing an EntityManagerFactory would be closer to destroying a whole connection pool. If you want to think JDBC connection, you should think EntityManager. We should not close the factory after every operation. Creating an EntityManagerFactoryis a pretty expensive operation and should be done once for the lifetime of the application (you close it at the end of the application). So, no, you should not close it for each persist/update/delete operation. The EntityManagerFa

JPA Caching

http://weblogs.java.net/blog/archive/2009/08/21/jpa-caching http://www.developer.com/java/ent/article.php/3892261/JPA-20-Cache-Vs-Hibernate-Cache-Differences-in-Approach.htm

ClassCastException of persistence.xml

java.lang.ClassCastException: : org.apache.xerces.parsers.XIncludeAwareParserConfiguration cannot be cast to org.apache.xerces.xni.parser.XMLParserConfiguration" occurred while attempting to determine the version of "zip:C:/JDeveloper/11.1.1.4.0/user_projects/domains/.../persistence.xml". The problem maybe caused by the encoding of the persistence.xml. Another possible reason is caused by the classloading of the xercesImpl.jar. Qwblogic has built-in xercesImpl.jar, your application should load the jar from parent classloader. However,  using org.apache.xerces.* in weblogic-application.xml may cause classloading problem.  Solution: Remove the prefer settings from weblogic-application.xml - not exactly work or exclude this jar from POM.xml. - work

ClassCastException of entity class

The problem maybe caused by the entity class has been cached in the server even you have renamed the package and redeploy the application. For example, com.service.persistence.delivery.A changed to com.service.persistence.reprint.delivery.A. private static String persistenceUnitName = "EclipseLinkWeb"; private static EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnitName); EntityManagerFactory is acquired statically, and there is no code to free the EntityManagerFactory and other resources before the app starts up again.  This causes the underlying resources to still exist, which have links to the old classloader, and this leads to java.lang.ClassCastException after redeployment. Workaround: Please restart the server. Solution: First, I added the following method to JPAUtil class: public class JPAUtil {   ...       public static void releaseResources() {         if (emf != null) {             emf.close();         }            }

Solution: Can't delete "The... folder does not exist. The file may have been moved or deleted."

Use RMDIR on containing folder Begin like the previous method, but try also rmdir /s foldername (replace foldername with the name of the folder to be deleted). This command should delete a folder with all its subfolders. If the folder name contains one or more spaces, enclose it in quotes. Example: rmdir /s " folder name " Note that the abbreviated command rd can be used in place of rmdir.

Grant right to user to run update statistics on SQL server

create procedure dbo . up_updstats with execute as 'dbo' as exec sp_updatestats go grant execute on dbo . up_updstats to [ ] go

View raw HTTP request on SoapUI

After you sent the soap message to web service end point, please click HTTP log at the bottom of the screen to view the whole HTTP request.

Access web service with username token by SoapUI

Create a new project on SoapUI. Double click on the Binding item. Select Service Endpoint tab page on the property window. Provide username, password. Select PasswordText as the WSS-Type.

Programmatic EntityManager

Instead of you dependence Injection for EntityManager by annotation, you can also adopt programmatic EntityManager by the following code. private static EntityManagerFactoryMap buildEmFactories(String name, String persistenceUnit){                 List dsList =  CsvConfigManager.getReprintConfig(name).getDataSourceList();         EntityManagerFactoryMap managerFactories = new EntityManagerFactoryMap();         for (DataSourceEntry ds: dsList) {             HashMap property = new HashMap ();             property.put(TRANSACTION_TYPE, "JTA");             property.put(JTA_DATASOURCE, ds.getJndi());             property.put(CACHE_TYPE_DEFAULT, "NONE");             property.put(CACHE_SHARED_DEFAULT, "false");             property.put(WEAVING_INTERNAL, "false");             property.put(SESSION_NAME, ds.getJndi());             property.put(LOGGING_SESSION, "false");             property.put(CATEGORY_LOGGING_LEVEL_, "WARNING");

MS SQL Server: EXECUTE permission denied on xp_sqljdbc_xa_init_ex

When attempting to start the system using MS SQL Server 2008 R2 you get an exception like: javax.transaction.xa.XAException: com.microsoft.sqlserver.jdbc_SQLServerException: failed to create the XA control connection. Error: "The EXECUTE permission was denied on the object 'xp_sqljdbc_xa_init_ex', database 'master' schema 'dbo' To fix the problem you should add user for master database with SqlJDBCXAUser permission. or you may execute the following command (also need to grant right first) EXEC sp_addrolemember [SqlJDBCXAUser], 'username'

What is different between Thread.currentThread().getContextClassLoader() and Class.getClassLoader()?

From API document, the Thread.currentThread().getContextClassLoader() returns the context ClassLoader for this Thread. The context ClassLoader is provided by the creator of the thread for use by code running in this thread when loading classes and resources. The default is the ClassLoader context of the parent Thread. The context ClassLoader of the primordial thread is typically set to the class loader used to load the application. The context ClassLoader can be set when a thread is created, and allows the creator of the thread to provide the appropriate class loader to code running in the thread when loading classes and resources.  For example, JNDI and JAXP used thread's ClassLoader. You had better to use thread's ClassLoader in your own code when your code need to deployed on J2EE container. The Class.getClassLoader() returns the class loader for the class. Some implementations may use null to represent the bootstrap class loader. This method will return

NoClassDefFoundError vs ClassNotFoundException

The difference from the Java API Specifications is as follows. For ClassNotFoundException : Thrown when an application tries to load in a class through its string name using: The forName method in class Class . The findSystemClass method in class ClassLoader . The loadClass method in class ClassLoader . but no definition for the class with the specified name could be found. For NoClassDefFoundError : Thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found. The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found. So, it appears that the NoClassDefFoundError occurs when the source was successfully compiled, but at runtime, the required class files were not found. This may be some

Clone database on SQL Server

Method 1: In the SQL Server Management Studio: Right click on the database  Select Tasks Select Copy Database... Follow the step in the Copy Database Wizard Method 2: In the SQL Server Management Studio: Right click on the database Select Tasks Select Back Up... Select the desire database and back up the database to disk Right click on the "Databases" and select New Database... Create a new database with the desire name. Right click on the newly created database Select Tasks Select Restore > Database... to restore the database Select From device to look up the image file.

Remove SQL Server database from single-user mode

Turn off the single-user mode of the database by the following statement: ALTER DATABASE [db_name] SET MULTI_USER WITH NO_WAIT OR exec sp_dboption 'db_user', 'single user', 'FALSE'   If the process is deadlocked, please kill the processed by: select d.name, d.dbid, spid, login_time, nt_domain, nt_username, loginame from sysprocesses p inner join sysdatabases d on p.dbid = d.dbid where d.name = 'jasper_db_sit' go kill spid

java.lang.NoClassDefFoundError: org/apache/xerces/jaxp/datatype/XMLGregorianCalendarImpl$Parser

When you encounter the following error that related to web service. java.lang.NoClassDefFoundError: org/apache/xerces/jaxp/datatype/XMLGregorianCalendarImpl$Parser Solution 1: Ensure no xercesImpl.jar in your classpath since the implementation of xerce is built-in wiht JAVA SE 1.6. Solution 2: Use XmlJavaTypeAdapter [ @XmlJavaTypeAdapter(JaxbDateAdapter.class)] to convert XMLGregorianCalendar type to Date type. XMLGregorianCalendar is the built-in Java data type for JAXB mapping with datetime. Example: Binding.xjb <?xml version="1.0" encoding="UTF-8"?> <bindings xmlns="http://java.sun.com/xml/ns/jaxb"                 xmlns:xsi="http://www.w3.org/2000/10/XMLSchema-instance"                 xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"                 xmlns:xsd="http://www.w3.org/2001/XMLSchema"                 xsi:schemaLocation=" http://java.sun.com/xml/ns/jaxb http://java.sun.com/xml/ns/jaxb/binding

Deployment problem casued maven auto generated application.xml

When you encounter  exception like the following Target state: deploy failed on Cluster CmsappsvCorpBrsmainPrd java.io.FileNotFoundException: File not found The application.xml in your ear maybe stating a wrong war or jar file. This is caused by the application.xml that generated by maven automatically. Please remove to remove this application.xml before building ear file.

Force windows to use a specific network connection

  When more than one network connection is available, Windows uses the one with the lowest metric value. By default, it automatically assigns a metric value based on the network connection's rated speed. See An explanation of the Automatic Metric feature for Internet Protocol routes . To force Windows to use a specific network connection, assign a metric value to each one, giving the lowest value to the desired connection: Open the Network Connections folder (Start > Run > ncpa.cpl) Right click the desired connection. Click Properties > Internet Protocol Version 4. Click Properties > Advanced. Un-check "Automatic metric". Enter a number between 1 and 9999 for the "Interface metric".

Enable nview for geforce on windows 7

Download the Quadro driver from http://www.nvidia.com. Extract the driver by Winrar or 7zip. In the nview folder, create a shortcut for nviewsetup.exe Add -f in the target. Run the shortcut.

Solution for Eclipse hangs at startup

In your workspace directory perform the following steps: cd .metadata/.plugins mv org.eclipse.core.resources org.eclipse.core.resources.bak Start eclipse. (It should show an error message or an empty workspace because no project is found.) Close all open editors tabs. Change to another perspective e.g. Java. Exit eclipse. rm -rf org.eclipse.core.resources (Delete the newly created directory.) mv org.eclipse.core.resources.bk/ org.eclipse.core.resources (Restore the original directory.) Start eclipse and start working.

Web service (JAX-WS) timeout

//1 minute for connection (( BindingProvider ) wsPort ). getRequestContext (). put ( " com.sun.xml.ws.connect.timeout " , 1 * 60 * 1000 ); //3 minutos for request (( BindingProvider ) wsPort ). getRequestContext (). put ( " com.sun.xml.ws.request.timeout " , 3 * 60 * 1000 );   or  import com.sun.xml.ws.developer.JAXWSProperties use JAXWSProperties. CONNECT_TIMEOUT and JAXWSProperties. REQUEST_TIMEOUT  

Executable jar with onejar-maven-plugin

Onejar-maven-plugin collects your application including dependencies, into one executable jar. It's both easy and works well! Problem If you have ever tried doing this before with Maven, you have probably used maven-assembly-plugin , which would leave the door open for classpath problems! It would extract all your dependency jars in one directory together with all your class files and all other classpath resources. The problem is that everything ended up in a big mix, with classpath resources possibly overwriting each other. For example, if two dependencies each had a log4j.properties file in their jar, one log4j.properties would overwrite the other. No more of that mess! Solution Enter maven-onejar-plugin. It lets all your dependency jars stay jars, and your code is in its own jar. All of those jars are put in a bigger jar, which is made executable. Configuration It may sound weird, but it's quite elegant! Just put this in your pom.xml 's tag to make it wo

Turn off WebLogic basic authentication

Editing config.xml To set the e enforce-valid-basic-auth-credentials flag, perform the following steps: 1. Add the element to config.xml within the element. false 2. Start or restart all of the servers in the domain. ============================================= Using WebLogic Scripting Tool (WLST) Using WLST to Check the Value of enforce-valid-basic-auth-credentials The Administration Console does not display or log the enforce-valid-basic-auth-credentials setting. However, you can use WLST to check the value in a running server. Remember that enforce-valid-basic-auth-credentials is a domain-wide setting. The WLST session shown below demonstrates how to check the value of the enforce-valid-basic-auth-credentials flag in a sample running server. Example: wls:/offline> connect('weblogic','weblogic123','t3://localhost:7002') Connecting to t3://localhost:7002 with userid weblogic ... Successfully connected to Admin Server 'AdminS

java.lang.ClassCastException: javax.xml.bind.JAXBElement

When your XSD have no XMLRootElement that contains all types in one element, the code below is not applicable: FooClass foo = (FooClass)unMarshaller.unmarshal(reader); You should use the code below: JAXBElement < FooClass > root = unmarshaller . unmarshal ( inputStream , FooClass . class ); FooClass foo = root . getValue (); XSD Comparison: <xsd:element name="brs-reprint-param" type="brsReprintParam"> <xsd:key name="reportId"> <xsd:selector xpath="./report"/> <xsd:field xpath="@id"/> </xsd:key> </xsd:element> <xsd:complexType name="brsReprintParam"> <xsd:sequence> <xsd:element name="report" type="reprintReport.CT" minOccurs="1" maxOccurs="unbounded"/> </xsd:sequence> </xsd:complexType> <xsd:element name="brs-reprint-param" > <xsd:complexType> &

The different between JPA query statement and native SQL

For JPA, it supports named parameter, such as :parameter1, :parameter2. For native SQL query, it supports positional parameter, such as ?1, ?2.

Rebuild maven local repository index after updated the library

圖片
Please remember to rebuild the maven local repository index after your library is being updated. For example, common library that are developing.

Code for web service client to invoke OC4J web service with WSS Username Token policy

Put UsernameToken.xml in the same package of the web service client class. Please find the code below for the coding details: protected Location locationWebSPort = null; protected static volatile LocationWebSManager me; protected String endpoint = null; protected String userName = null; protected String password = null; protected LocationWebSManager(){ } public static LocationWebSManager getInstance(){ if (me == null){ synchronized(LocationWebSManager.class){ me = new LocationWebSManager(); } } return me; } public Location getWebService() throws Exception{ if (locationWebSPort == null){ synchronized(LocationWebSManager.class){ ClientPolicyFeature cpf = new ClientPolicyFeature(); InputStream asStream = LocationWebSManager.class.getResourceAsStream("UsernameToken.xml"); cpf.setEffectivePolicy(new InputStreamPolicySource(asStream)); URL url = new URL(getEndpoint()); QName qName = new QName("http://loc

Create Web Service with WSS Username Token Polic

Add @WebService(name="", serviceName="", portName="") annotation for the class. Add @Policy(uri = "policy:UsernameToken.xml") for the class. Add @WebMethod(operationName="") for method. Add @WebResult(name="") for method return name. Add @WebParam(name="") for method argument. Create policies folder under WEB-INF. Put the UsernameToken.xml under policies folder. The content of the xml file: <?xml version="1.0"?> <wsp:Policy xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy" xmlns:sp="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200512" > <sp:SupportingTokens> <wsp:Policy> <sp:UsernameToken sp:IncludeToken="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200512/IncludeToken/AlwaysToRecipient"> <wsp:Policy> <sp:WssUsernameToken10/> </wsp:Policy> </sp:UsernameToken> </wsp:Policy> </sp:SupportingTokens>

Generate WebLogic Web Service Client on Eclipse

圖片
Add Dynamic Web Module and Oracle WebLogic Web Service Clients in Project Facets. Add Oracle WebLogic Server 11g in the Project Facets -> Runtimes. Right Click on the project and new a WebLogic Web Services -> Web Service Client. Select Remote WSDL Location. In the Customization Options, choose Define WSDL location at runtime when client instantiated.

Export a report as an image

Map parameters = new HashMap(); JasperPrint jasperPrint = JasperFillManager.fillReport( (JasperReport) JRLoader.loadObject(new File("d:/injuryPresume.jasper")), parameters, new JREmptyDataSource()); JRGraphics2DExporter exporter = new JRGraphics2DExporter(); BufferedImage bufferedImage = new BufferedImage(jasperPrint.getPageWidth() * 4, jasperPrint.getPageHeight() * 4, BufferedImage.TYPE_INT_RGB); Graphics2D g = (Graphics2D) bufferedImage.getGraphics(); exporter.setParameter(JRGraphics2DExporterParameter.GRAPHICS_2D, g); exporter.setParameter(JRGraphics2DExporterParameter.ZOOM_RATIO, Float.valueOf(4)); exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); exporter.exportReport(); g.dispose(); ImageIO.write(bufferedImage, "JPEG", new File("d:/aa.jpg"));