[原创] Eclipse的Adapter机制 - Design Pattern (Chinese)

GoF的Adapter解决了将一种接口适配为另一种接口的方法,例如:
将实现了接口A的AImpl适配为接口B,就需要从AImpl继承,同时实现B接口:
class BImpl extends AImpl implements B { ... }
但是在Eclipse中要将一个Object适配为另外的接口,很可能有很多个,并且在将来还可能需要增加新的接口,而客户端需要动态将该Object适配为自己想要的类型
例如,自己的一个对象MyObject需要适配为IFile对象,如果直接使用Adapter接口,就需要实现IFile接口,这是非常困难的,因此Eclipse设计了一种Adapter机制,通过实现IAdaptable接口,就能动态查询一个Object是否支持某个接口,如果支持,就将其转化为该接口的对象
例子:
我们自己设计的MyObject包含一个IFile引用:
class MyObject {
private IFile file;
}
若要将MyObject动态转化为IFile,就需要实现IAdaptable接口:
class MyObject implements IAdaptable {
private IFile file;
public Object getAdapter(Class adapter) {
if(adapter.equals(IFile.class))
return file;
return null;
}
}
客户端希望将MyObject转型为IFile时,就通过getAdapter方法检测是否能将MyObject转型为IFile:
MyObject obj = ...;
if(obj instanceof IAdaptable) {
IFile file = (IFile) ((IAdaptable)obj).getAdapter(IFile.class);
if(file!=null) {
// got the file!
}
}
好处:
客户端可以动态查询一个Object是否支持某个接口
自己的Object不需要通过继承来实现Adapter,因为需要适配的接口越多,类就会越来越复杂
扩展极其容易,例如,一个新的客户端需要InputStream而非IFile,就只需要修改getAdapter()方法:
public Object getAdapter(Class adapter) {
if(adapter.equals(IFile.class))
return file;
if(adapter.equals(InputStream.class))
return file.getInputStream();
return null;
}
原来的客户端不受影响,新的客户端也能正常工作。
有了Adapter机制,就能动态查询任何一个Object能否转型为某一接口。在Eclipse中,许多Object并非IResource类型,但是右键菜单都能列出Copy, Paste, CVS等操作,就是因为他们实现了IAdaptable接口并有能力转化为IResource
额外的好处:扩展代码与原代码无关,例如Java开发环境的一个Objec可能是IJavaClass对象,扩展对象(例如一个右键菜单Action)不会引用IJavaClass,而是引用IResource,组件之间没有耦合。Action只需要告诉Eclipse它需要一个IResource,Eclipse就去查询IJavaClass对象并试图将其转化为IResource,若转化成功,该Action就可以出现在右键菜单上。
下次再继续写Eclipse的AdapterFactory

在客户端和getAdapter中有大量的if else,这是不是有些bad smell?

这些是Eclipse内部调用的,作为插件只需要告诉Eclipse你需要IResource接口,类似:
class MyAction extends WorkbenchAction implements ISelectionChangedListener {
pirvate IResource selectedResource;
public void selectionChanged(IStructuredSelection selection) {
this.selectedResource = (IResource) selection.getFirstSelection();
}
public void run() {
// do with selectedResource...
}
}
配置文件是xml格式的,代码里看不到Object -> IResource的转化

如果不用if then,那就要 用两次反转了

Related

why can't get an object?

1.Two JDO persistant class SocietyEntity and BasicInfo, defined as
following:
package com.md.police.service.society;
import java.io.Serializable;
public class SocietyEntity {
String ID;
BasicInfo basicInfo;
public SocietyEntity() {
}
...
}
package com.md.police.service.society;
public class BasicInfo {
String name;
String phone;
String address;
String stationId;
public BasicInfo() {
}
...
}
when the SocietyEntity object persisted (the SocietyEntity.basicInfo not
null), all data of the BasicInfo object is correctly saved to database.
but when the SocietyEntity object is retrieved from the database, the
SocietyEntity.basicInfo has a value of null. Help!
There isn't much we can suggest without more detail. Obviously Kodo doesn't
have a problem persisting and retrieving simple relations. It's tough to
suggest anything without seeing your actual code, though. It could be a problem
with an application identity class, or the fact that you're circumventing
enhancement by accessing the relation field directly from another unenhanced
class, etc.
There are 3 class defined as following:
1.ResManagerImpl.java
package com.md.police.resource;
import java.lang.reflect.*;
import java.util.*;
import javax.jdo.*;
import kodo.runtime.*;
public class ResManagerImpl
implements ResourceManager {
public Collection selectObjects(Class cls) {
return selectObjects("", cls);
}
public Collection selectObjects(String filter, Class cls) {
Collection collectionObjects, targetObjects;
targetObjects = new Vector();
// Get a PersistenceManagerFactory and PersistenceManager.
PersistenceManager pm = pmf.getPersistenceManager();
// Obtain a transaction and mark the beginning
// of the unit of work boundary.
Transaction transaction = pm.currentTransaction();
transaction.begin();
// Get a query for the specified class and filter.
Query query;
if (filter == null || filter.equals("")) {
query = pm.newQuery(cls);
}
else {
query = pm.newQuery(cls, filter);
//query.declareVariables ("Animal animal;");
}
collectionObjects = (Collection) query.execute();
pm.makeTransientAll(collectionObjects);
transaction.commit();
pm.close();
return collectionObjects;
}
...
static {
pmf = KodoHelper.getPersistenceManagerFactory("kodo.properties");
}
private static PersistenceManagerFactory pmf;
}
2.WeatherRes.java is a JDO class
package com.md.police.resource;
import java.util.*;
public class WeatherRes {
private String temprature;
private String humidity;
private String windDirect;
private String windPower;
private String rainfall;
private String forecastedDate; //primary field
private String forecastingDate;
public WeatherRes() {
}
public String getTemprature() {
return temprature;
}
public String getForecastedDate() {
return forecastedDate;
}
public void setTemprature(String _temp) {
this.temprature = _temp;
}
public void setForecastedDate(String _date) {
this.forecastedDate = _date;
}
public String toString() {
String toString = "forecastedDate:" + this.forecastedDate + "
Tempratue:" +
this.temprature;
return toString;
}
public boolean equals(Object other) {
if (other == this) {
return true;
}
if (other == null) {
return false;
}
if (! (other instanceof WeatherRes)) {
return false;
}
WeatherRes weather = (WeatherRes) other;
boolean returnValue = true;
if ( (forecastedDate == null || weather.getForecastedDate() == null)) {
returnValue = false;
}
if (forecastedDate.equals(weather.getForecastedDate())) {
returnValue = true;
}
else {
returnValue = false;
}
return returnValue;
}
public int hashCode() {
return ( (forecastedDate == null) ? 0 : forecastedDate.hashCode());
}
public String getHumidity() {
return humidity;
}
public String getForecastingDate() {
return forecastingDate;
}
public void setForecastingDate(String forecastingDate) {
this.forecastingDate = forecastingDate;
}
public void setHumidity(String humidity) {
this.humidity = humidity;
}
public void setWindDirect(String windDirect) {
this.windDirect = windDirect;
}
public void setWindPower(String windPower) {
this.windPower = windPower;
}
public String getWindPower() {
return windPower;
}
public String getWindDirect() {
return windDirect;
}
public String getRainfall() {
return rainfall;
}
public void setRainfall(String rainfall) {
this.rainfall = rainfall;
}
}
3.
package com.md.police.test;
import com.md.police.resource.*;
import junit.framework.*;
import java.util.*;
public class ObjectTest {
public ObjectTest() {
}
public static void main(String[] args) {
ResourceManager rmi = new ResManagerImpl();
WeatherRes weather = new WeatherRes();
weather.setTemprature("38锟斤拷");
weather.setHumidity("78%");
weather.setWindPower("6-7锟斤拷");
weather.setForecastedDate("2004-7-29");
rmi.insertObject(weather);
Collection sec = rmi.selectObjects(weather.getClass());
System.out.print("size:"+sec.size());
Object[] obj = sec.toArray();
for (int i = 0; i < obj.length; i++) {
WeatherRes temp = (WeatherRes) obj;
System.out.println("date:" + temp.getForecastedDate());
}
}
}
but there are a error as following:
java.util.NoSuchElementException: The result list has been closed.
     at
com.solarmetric.rop.AbstractResultList.assertOpen(AbstractResultList.java:99)
     at com.solarmetric.rop.ListResultList.toArray(ListResultList.java:119)
     at com.md.police.test.ObjectTest.main(ObjectTest.java:35)
I have transient the jdo objects in ResManagerImpl's method named
selectObjects() by useing pm.makeTransientAll(Collection),but why the
error is occured!
please help!
Are you closing your PM?
What happens when you also add the instances back to a new List (i.e.
new ArrayList ((Collection) query.execute ())?
javasilk wrote:
There are 3 class defined as following:
1.ResManagerImpl.java
package com.md.police.resource;
import java.lang.reflect.*;
import java.util.*;
import javax.jdo.*;
import kodo.runtime.*;
public class ResManagerImpl
implements ResourceManager {
public Collection selectObjects(Class cls) {
return selectObjects("", cls);
}
public Collection selectObjects(String filter, Class cls) {
Collection collectionObjects, targetObjects;
targetObjects = new Vector();
// Get a PersistenceManagerFactory and PersistenceManager.
PersistenceManager pm = pmf.getPersistenceManager();
// Obtain a transaction and mark the beginning
// of the unit of work boundary.
Transaction transaction = pm.currentTransaction();
transaction.begin();
// Get a query for the specified class and filter.
Query query;
if (filter == null || filter.equals("")) {
query = pm.newQuery(cls);
}
else {
query = pm.newQuery(cls, filter);
//query.declareVariables ("Animal animal;");
}
collectionObjects = (Collection) query.execute();
pm.makeTransientAll(collectionObjects);
transaction.commit();
pm.close();
return collectionObjects;
}
...
static {
pmf = KodoHelper.getPersistenceManagerFactory("kodo.properties");
}
private static PersistenceManagerFactory pmf;
}
2.WeatherRes.java is a JDO class
package com.md.police.resource;
import java.util.*;
public class WeatherRes {
private String temprature;
private String humidity;
private String windDirect;
private String windPower;
private String rainfall;
private String forecastedDate; //primary field
private String forecastingDate;
public WeatherRes() {
}
public String getTemprature() {
return temprature;
}
public String getForecastedDate() {
return forecastedDate;
}
public void setTemprature(String _temp) {
this.temprature = _temp;
}
public void setForecastedDate(String _date) {
this.forecastedDate = _date;
}
public String toString() {
String toString = "forecastedDate:" + this.forecastedDate + "
Tempratue:" +
this.temprature;
return toString;
}
public boolean equals(Object other) {
if (other == this) {
return true;
}
if (other == null) {
return false;
}
if (! (other instanceof WeatherRes)) {
return false;
}
WeatherRes weather = (WeatherRes) other;
boolean returnValue = true;
if ( (forecastedDate == null || weather.getForecastedDate() == null)) {
returnValue = false;
}
if (forecastedDate.equals(weather.getForecastedDate())) {
returnValue = true;
}
else {
returnValue = false;
}
return returnValue;
}
public int hashCode() {
return ( (forecastedDate == null) ? 0 : forecastedDate.hashCode());
}
public String getHumidity() {
return humidity;
}
public String getForecastingDate() {
return forecastingDate;
}
public void setForecastingDate(String forecastingDate) {
this.forecastingDate = forecastingDate;
}
public void setHumidity(String humidity) {
this.humidity = humidity;
}
public void setWindDirect(String windDirect) {
this.windDirect = windDirect;
}
public void setWindPower(String windPower) {
this.windPower = windPower;
}
public String getWindPower() {
return windPower;
}
public String getWindDirect() {
return windDirect;
}
public String getRainfall() {
return rainfall;
}
public void setRainfall(String rainfall) {
this.rainfall = rainfall;
}
}
3.
package com.md.police.test;
import com.md.police.resource.*;
import junit.framework.*;
import java.util.*;
public class ObjectTest {
public ObjectTest() {
}
public static void main(String[] args) {
ResourceManager rmi = new ResManagerImpl();
WeatherRes weather = new WeatherRes();
weather.setTemprature("38锟斤拷");
weather.setHumidity("78%");
weather.setWindPower("6-7锟斤拷");
weather.setForecastedDate("2004-7-29");
rmi.insertObject(weather);
Collection sec = rmi.selectObjects(weather.getClass());
System.out.print("size:"+sec.size());
Object[] obj = sec.toArray();
for (int i = 0; i < obj.length; i++) {
WeatherRes temp = (WeatherRes) obj;
System.out.println("date:" + temp.getForecastedDate());
}
}
}
but there are a error as following:
java.util.NoSuchElementException: The result list has been closed.
     at
com.solarmetric.rop.AbstractResultList.assertOpen(AbstractResultList.java:99)
     at com.solarmetric.rop.ListResultList.toArray(ListResultList.java:119)
     at com.md.police.test.ObjectTest.main(ObjectTest.java:35)
I have transient the jdo objects in ResManagerImpl's method named
selectObjects() by useing pm.makeTransientAll(Collection),but why the
error is occured!
please help!
--
Steve Kim
skim#solarmetric.com
SolarMetric Inc.
http://www.solarmetric.com

[JHS 10.1.3]  error with backing bean

Hi,
I have generated pages with the beta version of jheadstart. When ik create a backing bean from the design of the page and use auto binding i get the following error at runtime
javax.faces.el.PropertyNotFoundException: Error getting property 'EtMediasEmiaUploadDestination1' from bean of type nl.eurotransplant.filemanager.view.backing.EtMediasBackBean
Can i use this binding or should i do something else. When ik build the page without jHeadstart (make a new page with a backing bean on the same entity and view i dont have problems. Should i do something extra when i use jheadstart?
Regards,
Erik 
Erik,
This works the same way as without JHeadstart.
The error indicates that you are missing get/set methods for property EtMediasEmiaUploadDestination1 in your bean. Can you check whether these methods are present?
Steven Davelaar,
JHeadstart Team. 
Hi Steven,
Yes the getters and setters are there. I have build a new project with just one table and i get the same problem. but i get the same error
GetCountryCntNr and SetCountryCntNr are present in the bean testcountry
but i get the same error
javax.faces.el.PropertyNotFoundException: Error getting property 'CountryCntNr' from bean of type nl.test.testcountry
     at com.sun.faces.el.PropertyResolverImpl.getValue(PropertyResolverImpl.java:107)
     at oracle.adfinternal.view.faces.model.FacesPropertyResolver.getValue(FacesPropertyResolver.java:92)
in the jspx page:
<af:inputText id="CountryCntNr"
value="#{bindings.CountryCntNr.inputValue}"
label="CntNr"
required="#{bindings.CountryCntNr.mandatory}"
rows="#{bindings.CountryCntNr.displayHeight}"
columns="#{bindings.CountryCntNr.displayWidth}"
maximumLength="4"
binding="#{appbackint.CountryCntNr}">
faces config:
<managed-bean>
<managed-bean-name>appbackint</managed-bean-name>
<managed-bean-class>nl.test.testcountry</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
<!--oracle-jdev-comment:managed-bean-jsp-link:1WEB-INF/page/Country.jspx-->
</managed-bean>
and the testcountry.java:
import javax.faces.component.UINamingContainer;
import oracle.adf.view.faces.component.core.CoreForm;
import oracle.adf.view.faces.component.core.input.CoreInputText;
import oracle.adf.view.faces.component.core.input.CoreSelectInputDate;
import oracle.adf.view.faces.component.core.layout.CorePanelButtonBar;
import oracle.adf.view.faces.component.core.layout.CorePanelForm;
import oracle.adf.view.faces.component.core.layout.CorePanelGroup;
import oracle.adf.view.faces.component.core.layout.CorePanelPage;
import oracle.adf.view.faces.component.core.nav.CoreCommandButton;
import oracle.adf.view.faces.component.core.output.CoreMessages;
import oracle.adf.view.faces.component.core.output.CoreObjectSpacer;
import oracle.adf.view.faces.component.core.output.CoreOutputFormatted;
import oracle.adf.view.faces.component.html.HtmlBody;
import oracle.adf.view.faces.component.html.HtmlHead;
import oracle.adf.view.faces.component.html.HtmlHtml;
public class testcountry {
private CorePanelGroup panelGroup1;
private CoreObjectSpacer objectSpacer1;
private CoreInputText CountryCntDeleteUser;
private CoreSelectInputDate CountryCntDeleteDate;
private CoreInputText CountryCntEt;
private CoreInputText CountryCntName;
private CoreInputText CountryCntCode;
private CoreInputText CountryCntNr;
private CorePanelForm panelForm1;
private CorePanelGroup panelGroup2;
private CoreOutputFormatted outputFormatted1;
private CorePanelGroup panelGroup3;
private CoreCommandButton commandButton1;
private CoreCommandButton commandButton2;
private CoreCommandButton commandButton3;
private CorePanelButtonBar panelButtonBar1;
private CoreMessages messages1;
private CorePanelPage panelPage1;
private CoreForm form1;
private UINamingContainer pageConfig;
private HtmlBody body1;
private HtmlHead head1;
private HtmlHtml html1;
public testcountry() {
}
public void setPanelGroup1(CorePanelGroup panelGroup1) {
this.panelGroup1 = panelGroup1;
}
public CorePanelGroup getPanelGroup1() {
return panelGroup1;
}
public void setObjectSpacer1(CoreObjectSpacer objectSpacer1) {
this.objectSpacer1 = objectSpacer1;
}
public CoreObjectSpacer getObjectSpacer1() {
return objectSpacer1;
}
public void setCountryCntDeleteUser(CoreInputText CountryCntDeleteUser) {
this.CountryCntDeleteUser = CountryCntDeleteUser;
}
public CoreInputText getCountryCntDeleteUser() {
return CountryCntDeleteUser;
}
public void setCountryCntDeleteDate(CoreSelectInputDate CountryCntDeleteDate) {
this.CountryCntDeleteDate = CountryCntDeleteDate;
}
public CoreSelectInputDate getCountryCntDeleteDate() {
return CountryCntDeleteDate;
}
public void setCountryCntEt(CoreInputText CountryCntEt) {
this.CountryCntEt = CountryCntEt;
}
public CoreInputText getCountryCntEt() {
return CountryCntEt;
}
public void setCountryCntName(CoreInputText CountryCntName) {
this.CountryCntName = CountryCntName;
}
public CoreInputText getCountryCntName() {
return CountryCntName;
}
public void setCountryCntCode(CoreInputText CountryCntCode) {
this.CountryCntCode = CountryCntCode;
}
public CoreInputText getCountryCntCode() {
return CountryCntCode;
}
public void setCountryCntNr(CoreInputText CountryCntNr) {
this.CountryCntNr = CountryCntNr;
}
public CoreInputText getCountryCntNr() {
return CountryCntNr;
}
public void setPanelForm1(CorePanelForm panelForm1) {
this.panelForm1 = panelForm1;
}
public CorePanelForm getPanelForm1() {
return panelForm1;
}
public void setPanelGroup2(CorePanelGroup panelGroup2) {
this.panelGroup2 = panelGroup2;
}
public CorePanelGroup getPanelGroup2() {
return panelGroup2;
}
public void setOutputFormatted1(CoreOutputFormatted outputFormatted1) {
this.outputFormatted1 = outputFormatted1;
}
public CoreOutputFormatted getOutputFormatted1() {
return outputFormatted1;
}
public void setPanelGroup3(CorePanelGroup panelGroup3) {
this.panelGroup3 = panelGroup3;
}
public CorePanelGroup getPanelGroup3() {
return panelGroup3;
}
public void setCommandButton1(CoreCommandButton commandButton1) {
this.commandButton1 = commandButton1;
}
public CoreCommandButton getCommandButton1() {
return commandButton1;
}
public void setCommandButton2(CoreCommandButton commandButton2) {
this.commandButton2 = commandButton2;
}
public CoreCommandButton getCommandButton2() {
return commandButton2;
}
public void setCommandButton3(CoreCommandButton commandButton3) {
this.commandButton3 = commandButton3;
}
public CoreCommandButton getCommandButton3() {
return commandButton3;
}
public void setPanelButtonBar1(CorePanelButtonBar panelButtonBar1) {
this.panelButtonBar1 = panelButtonBar1;
}
public CorePanelButtonBar getPanelButtonBar1() {
return panelButtonBar1;
}
public void setMessages1(CoreMessages messages1) {
this.messages1 = messages1;
}
public CoreMessages getMessages1() {
return messages1;
}
public void setPanelPage1(CorePanelPage panelPage1) {
this.panelPage1 = panelPage1;
}
public CorePanelPage getPanelPage1() {
return panelPage1;
}
public void setForm1(CoreForm form1) {
this.form1 = form1;
}
public CoreForm getForm1() {
return form1;
}
public void setPageConfig(UINamingContainer pageConfig) {
this.pageConfig = pageConfig;
}
public UINamingContainer getPageConfig() {
return pageConfig;
}
public void setBody1(HtmlBody body1) {
this.body1 = body1;
}
public HtmlBody getBody1() {
return body1;
}
public void setHead1(HtmlHead head1) {
this.head1 = head1;
}
public HtmlHead getHead1() {
return head1;
}
public void setHtml1(HtmlHtml html1) {
this.html1 = html1;
}
public HtmlHtml getHtml1() {
return html1;
}
} 
Erik,
Looking at the sources, I cannot see what is wrong.
Are you saying you now get the same error in a new project without JHeadstart?
If so, can you please post your problem on the JDeveloper forum?
Thanks,
Steven Davelaar,
JHeadstart Team. 
Hi steven,
i get this problem with a jheadstart project. Not with a non jheadstart project.
I Have version 59 installed. I cant figure out what's wrong. Everthing seems right.
i will try a fresh jdev installation with a new jheadstart installation and see if it still hapens

Complex Dynamic client

Hi
I have complex types say
World.java
package tutorial.types;
import java.util.*;
public class World {
private String name;
private Ocean[] oceans = new Ocean[0];
private Continent[] continents = new Continent[0];
public World() {}
public void setName(String name) { this.name = name; }
public String getName() { return name; }
public Ocean[] getOceans() { return oceans; }
public void setOceans(Ocean[] val) { oceans = val; }
public Continent[] getContinents() { return continents; }
public void setContinents(Continent[] val) { continents = val; }
public void addOcean(Ocean o) {
Ocean[] newOceans = new Ocean[oceans.length+1];
for (int i=0; i < oceans.length; i++){
newOceans[i] = oceans;
}
newOceans[oceans.length] = o;
oceans = newOceans;
}
public void addContinent(Continent c) {
Continent[] newContinents = new Continent[continents.length+1];
for (int i=0; i < continents.length; i++){
newContinents[i] = continents[i];
}
newContinents[continents.length] = c;
continents = newContinents;
}
}
Occean.java
-----------------------
package tutorial.types;
public class Ocean {
private String name;
private int depth;
private boolean hasIslands;
public Ocean() {}
public void setName(String name) { this.name = name; }
public String getName() { return name; }
public int getDepth() { return depth; }
public void setDepth(int depth) { this.depth = depth; }
public boolean getHasIslands() { return hasIslands; }
public void setHasIslands(boolean val) { this.hasIslands = val; }
}
Continent.java
----------------
package tutorial.types;
public class Continent {
private String name;
private int mass;
public Continent() {}
public void setName(String name) {this.name = name; }
public String getName() { return name; }
public int getMass() { return mass; }
public void setMass(int mass){ this.mass = mass; }
}
I am tryigny to write dynamic client for this complex type and am confused and
messing somewhere. Can you gurus can pls look and corrent my client for me thanks
ComplexDynamicClient.java
-----------------------------------
package tutorial.types.client;
import javax.xml.soap.SOAPConstants;
import javax.xml.rpc.ServiceFactory;
import javax.xml.rpc.Service;
import javax.xml.rpc.Call;
import javax.xml.rpc.ParameterMode;
import javax.xml.namespace.QName;
import javax.xml.rpc.encoding.TypeMapping;
import javax.xml.rpc.encoding.TypeMappingRegistry;
import tutorial.types.*;
public class ComplexDynamicClient
{
     public static void main(String a[])
     {
          System.setProperty( "javax.xml.rpc.ServiceFactory",
          "weblogic.webservice.core.rpc.ServiceFactoryImpl" );
          ServiceFactory factory = ServiceFactory.newInstance();
          String targetNamespace = "http://localhost:7001";
          // Types is service name in build.xml
          QName serviceName = new QName(targetNamespace,"Types");
          QName portName = new QName(targetNamespace,"TypesPort");
          QName operationName = new QName(targetNamespace,"addContinent");
          Service service = factory.createService(serviceName);
          TypeMappingRegistry registry = service.getTypeMappingRegistry();
          TypeMapping mapping = registry.getTypeMapping(SOAPConstants.URI_NS_SOAP_ENCODING
);
          mapping.register(World.class, new QName("http://localhost:7001","World"),new
OcceanCodec(),new OcceanCodec());
          Call call = service.createCall();
          call.setPortTypeName(portName);
          call.setOperationName(operationName);
          call.addParameter("World",new QName("http://www.w3.org/2001/XMLSchema","World"),ParameterMode.IN);
          call.addParameter("String",new QName("http://www.w3.org/2001/XMLSchema","String"),ParameterMode.IN);
          call.addParameter("int",new QName("http://www.w3.org/2001/XMLSchema","int"),ParameterMode.IN);
          call.setReturnType(new QName("http://www.w3.org/2001/XMLSchema"),"World");
          call.setTargetEndpointAddress("http://localhost:7001/types/HelloWorldTypes?WSDL");
          World w1 = new World();
          World world =(World)call.invoke(new Object[]{w1,"pranav",10});
     }
}
Service Name in ant is "Types"
Thanks
Awaiting your help.......................
Can you tell us what error you are
getting?
Regards,
-manoj
--
http://manojc.com
"david" <vuda#yahoo.com> wrote in message
news:3ea5a81b$1#newsgroups.bea.com...
>
Hi
I have complex types say
World.java
package tutorial.types;
import java.util.*;
public class World {
private String name;
private Ocean[] oceans = new Ocean[0];
private Continent[] continents = new Continent[0];
public World() {}
public void setName(String name) { this.name = name; }
public String getName() { return name; }
public Ocean[] getOceans() { return oceans; }
public void setOceans(Ocean[] val) { oceans = val; }
public Continent[] getContinents() { return continents; }
public void setContinents(Continent[] val) { continents = val; }
public void addOcean(Ocean o) {
Ocean[] newOceans = new Ocean[oceans.length+1];
for (int i=0; i < oceans.length; i++){
newOceans[i] = oceans;
}
newOceans[oceans.length] = o;
oceans = newOceans;
}
public void addContinent(Continent c) {
Continent[] newContinents = new Continent[continents.length+1];
for (int i=0; i < continents.length; i++){
newContinents[i] = continents[i];
}
newContinents[continents.length] = c;
continents = newContinents;
}
}
Occean.java
-----------------------
package tutorial.types;
public class Ocean {
private String name;
private int depth;
private boolean hasIslands;
public Ocean() {}
public void setName(String name) { this.name = name; }
public String getName() { return name; }
public int getDepth() { return depth; }
public void setDepth(int depth) { this.depth = depth; }
public boolean getHasIslands() { return hasIslands; }
public void setHasIslands(boolean val) { this.hasIslands = val; }
}
Continent.java
----------------
package tutorial.types;
public class Continent {
private String name;
private int mass;
public Continent() {}
public void setName(String name) {this.name = name; }
public String getName() { return name; }
public int getMass() { return mass; }
public void setMass(int mass){ this.mass = mass; }
}
I am tryigny to write dynamic client for this complex type and am confused
and
messing somewhere. Can you gurus can pls look and corrent my client for methanks
>
>
ComplexDynamicClient.java
-----------------------------------
package tutorial.types.client;
import javax.xml.soap.SOAPConstants;
import javax.xml.rpc.ServiceFactory;
import javax.xml.rpc.Service;
import javax.xml.rpc.Call;
import javax.xml.rpc.ParameterMode;
import javax.xml.namespace.QName;
import javax.xml.rpc.encoding.TypeMapping;
import javax.xml.rpc.encoding.TypeMappingRegistry;
import tutorial.types.*;
public class ComplexDynamicClient
{
public static void main(String a[])
{
System.setProperty( "javax.xml.rpc.ServiceFactory",
"weblogic.webservice.core.rpc.ServiceFactoryImpl" );
ServiceFactory factory = ServiceFactory.newInstance();
String targetNamespace = "http://localhost:7001";
// Types is service name in build.xml
QName serviceName = new QName(targetNamespace,"Types");
QName portName = new QName(targetNamespace,"TypesPort");
QName operationName = new QName(targetNamespace,"addContinent");
Service service = factory.createService(serviceName);
TypeMappingRegistry registry = service.getTypeMappingRegistry();
TypeMapping mapping =registry.getTypeMapping(SOAPConstants.URI_NS_SOAP_ENCODING
);
mapping.register(World.class, newQName("http://localhost:7001","World"),new
OcceanCodec(),new OcceanCodec());
Call call = service.createCall();
call.setPortTypeName(portName);
call.setOperationName(operationName);
call.addParameter("World",newQName("http://www.w3.org/2001/XMLSchema","World"),ParameterMode.IN);
call.addParameter("String",newQName("http://www.w3.org/2001/XMLSchema","String"),ParameterMode.IN);
call.addParameter("int",newQName("http://www.w3.org/2001/XMLSchema","int"),ParameterMode.IN);
call.setReturnType(new QName("http://www.w3.org/2001/XMLSchema"),"World");call.setTargetEndpointAddress("http://localhost:7001/types/HelloWorldTypes?W
SDL");
>
World w1 = new World();
World world =(World)call.invoke(new Object[]{w1,"pranav",10});
}
}
Service Name in ant is "Types"
Thanks
Awaiting your help.......................
Hi Manjo C
Thanks for your reply.
I my client i am not able to write the client as i m confused what object to send.
I have World object comprising of occean and continent object.
There is on API that takes in world object, string and int.
NOw i want to invoke this method and am not sure how to make call object and invoke.
I have written something , cant even get to compile
Mainly if u can have a look at my call object and how to invoke and give me soln
would be gr8
Attaching files for your clean understanding
Thanks for all your time and effort.
"manoj cheenath" <manojc#bea.com> wrote:
Can you tell us what error you are
getting?
Regards,
-manoj
--
http://manojc.com
"david" <vuda#yahoo.com> wrote in message
news:3ea5a81b$1#newsgroups.bea.com...
Hi
I have complex types say
World.java
package tutorial.types;
import java.util.*;
public class World {
private String name;
private Ocean[] oceans = new Ocean[0];
private Continent[] continents = new Continent[0];
public World() {}
public void setName(String name) { this.name = name; }
public String getName() { return name; }
public Ocean[] getOceans() { return oceans; }
public void setOceans(Ocean[] val) { oceans = val; }
public Continent[] getContinents() { return continents; }
public void setContinents(Continent[] val) { continents = val; }
public void addOcean(Ocean o) {
Ocean[] newOceans = new Ocean[oceans.length+1];
for (int i=0; i < oceans.length; i++){
newOceans[i] = oceans;
}
newOceans[oceans.length] = o;
oceans = newOceans;
}
public void addContinent(Continent c) {
Continent[] newContinents = new Continent[continents.length+1];
for (int i=0; i < continents.length; i++){
newContinents[i] = continents[i];
}
newContinents[continents.length] = c;
continents = newContinents;
}
}
Occean.java
-----------------------
package tutorial.types;
public class Ocean {
private String name;
private int depth;
private boolean hasIslands;
public Ocean() {}
public void setName(String name) { this.name = name; }
public String getName() { return name; }
public int getDepth() { return depth; }
public void setDepth(int depth) { this.depth = depth; }
public boolean getHasIslands() { return hasIslands; }
public void setHasIslands(boolean val) { this.hasIslands = val; }
}
Continent.java
----------------
package tutorial.types;
public class Continent {
private String name;
private int mass;
public Continent() {}
public void setName(String name) {this.name = name; }
public String getName() { return name; }
public int getMass() { return mass; }
public void setMass(int mass){ this.mass = mass; }
}
I am tryigny to write dynamic client for this complex type and am confused
and
messing somewhere. Can you gurus can pls look and corrent my clientfor me
thanks
ComplexDynamicClient.java
-----------------------------------
package tutorial.types.client;
import javax.xml.soap.SOAPConstants;
import javax.xml.rpc.ServiceFactory;
import javax.xml.rpc.Service;
import javax.xml.rpc.Call;
import javax.xml.rpc.ParameterMode;
import javax.xml.namespace.QName;
import javax.xml.rpc.encoding.TypeMapping;
import javax.xml.rpc.encoding.TypeMappingRegistry;
import tutorial.types.*;
public class ComplexDynamicClient
{
public static void main(String a[])
{
System.setProperty( "javax.xml.rpc.ServiceFactory",
"weblogic.webservice.core.rpc.ServiceFactoryImpl" );
ServiceFactory factory = ServiceFactory.newInstance();
String targetNamespace = "http://localhost:7001";
// Types is service name in build.xml
QName serviceName = new QName(targetNamespace,"Types");
QName portName = new QName(targetNamespace,"TypesPort");
QName operationName = new QName(targetNamespace,"addContinent");
Service service = factory.createService(serviceName);
TypeMappingRegistry registry = service.getTypeMappingRegistry();
TypeMapping mapping =registry.getTypeMapping(SOAPConstants.URI_NS_SOAP_ENCODING
);
mapping.register(World.class, newQName("http://localhost:7001","World"),new
OcceanCodec(),new OcceanCodec());
Call call = service.createCall();
call.setPortTypeName(portName);
call.setOperationName(operationName);
call.addParameter("World",newQName("http://www.w3.org/2001/XMLSchema","World"),ParameterMode.IN);
call.addParameter("String",newQName("http://www.w3.org/2001/XMLSchema","String"),ParameterMode.IN);
call.addParameter("int",newQName("http://www.w3.org/2001/XMLSchema","int"),ParameterMode.IN);
call.setReturnType(new QName("http://www.w3.org/2001/XMLSchema"),"World");call.setTargetEndpointAddress("http://localhost:7001/types/HelloWorldTypes?W
SDL");
World w1 = new World();
World world =(World)call.invoke(new Object[]{w1,"pranav",10});
}
}
Service Name in ant is "Types"
Thanks
Awaiting your help.......................[HelloWorld-Complex.zip]
Is there a reason for you to use dynamic client?
To use a dyn client on need to go through lot of
painful steps like: write/generate codecs for complex
type, register them, add operations & parameters,
etc. If you are using clientgen ant task to generate
a static client, all this work is done for you. So if
possible use static client.
If you still want to use dyn client, check out this
example:
http://manojc.com/?sample26
To try this out, copy this example to a local dir
and type:
ant
ant run--
http://manojc.com
"david" <as_fnk#yhoo.com> wrote in message
news:3ea689c4$1#newsgroups.bea.com...
>
Hi Manjo C
Thanks for your reply.
I my client i am not able to write the client as i m confused what objectto send.
I have World object comprising of occean and continent object.
There is on API that takes in world object, string and int.
NOw i want to invoke this method and am not sure how to make call objectand invoke.
I have written something , cant even get to compile
Mainly if u can have a look at my call object and how to invoke and giveme soln
would be gr8
Attaching files for your clean understanding
Thanks for all your time and effort.
"manoj cheenath" <manojc#bea.com> wrote:
Can you tell us what error you are
getting?
Regards,
-manoj
--
http://manojc.com
"david" <vuda#yahoo.com> wrote in message
news:3ea5a81b$1#newsgroups.bea.com...
Hi
I have complex types say
World.java
package tutorial.types;
import java.util.*;
public class World {
private String name;
private Ocean[] oceans = new Ocean[0];
private Continent[] continents = new Continent[0];
public World() {}
public void setName(String name) { this.name = name; }
public String getName() { return name; }
public Ocean[] getOceans() { return oceans; }
public void setOceans(Ocean[] val) { oceans = val; }
public Continent[] getContinents() { return continents; }
public void setContinents(Continent[] val) { continents = val; }
public void addOcean(Ocean o) {
Ocean[] newOceans = new Ocean[oceans.length+1];
for (int i=0; i < oceans.length; i++){
newOceans[i] = oceans;
}
newOceans[oceans.length] = o;
oceans = newOceans;
}
public void addContinent(Continent c) {
Continent[] newContinents = new Continent[continents.length+1];
for (int i=0; i < continents.length; i++){
newContinents[i] = continents[i];
}
newContinents[continents.length] = c;
continents = newContinents;
}
}
Occean.java
-----------------------
package tutorial.types;
public class Ocean {
private String name;
private int depth;
private boolean hasIslands;
public Ocean() {}
public void setName(String name) { this.name = name; }
public String getName() { return name; }
public int getDepth() { return depth; }
public void setDepth(int depth) { this.depth = depth; }
public boolean getHasIslands() { return hasIslands; }
public void setHasIslands(boolean val) { this.hasIslands = val; }
}
Continent.java
----------------
package tutorial.types;
public class Continent {
private String name;
private int mass;
public Continent() {}
public void setName(String name) {this.name = name; }
public String getName() { return name; }
public int getMass() { return mass; }
public void setMass(int mass){ this.mass = mass; }
}
I am tryigny to write dynamic client for this complex type and am
confused
and
messing somewhere. Can you gurus can pls look and corrent my clientfor me
thanks
ComplexDynamicClient.java
-----------------------------------
package tutorial.types.client;
import javax.xml.soap.SOAPConstants;
import javax.xml.rpc.ServiceFactory;
import javax.xml.rpc.Service;
import javax.xml.rpc.Call;
import javax.xml.rpc.ParameterMode;
import javax.xml.namespace.QName;
import javax.xml.rpc.encoding.TypeMapping;
import javax.xml.rpc.encoding.TypeMappingRegistry;
import tutorial.types.*;
public class ComplexDynamicClient
{
public static void main(String a[])
{
System.setProperty( "javax.xml.rpc.ServiceFactory",
"weblogic.webservice.core.rpc.ServiceFactoryImpl" );
ServiceFactory factory = ServiceFactory.newInstance();
String targetNamespace = "http://localhost:7001";
// Types is service name in build.xml
QName serviceName = new QName(targetNamespace,"Types");
QName portName = new QName(targetNamespace,"TypesPort");
QName operationName = new QName(targetNamespace,"addContinent");
Service service = factory.createService(serviceName);
TypeMappingRegistry registry = service.getTypeMappingRegistry();
TypeMapping mapping =registry.getTypeMapping(SOAPConstants.URI_NS_SOAP_ENCODING
);
mapping.register(World.class, newQName("http://localhost:7001","World"),new
OcceanCodec(),new OcceanCodec());
Call call = service.createCall();
call.setPortTypeName(portName);
call.setOperationName(operationName);
call.addParameter("World",newQName("http://www.w3.org/2001/XMLSchema","World"),ParameterMode.IN);
call.addParameter("String",newQName("http://www.w3.org/2001/XMLSchema","String"),ParameterMode.IN);
call.addParameter("int",newQName("http://www.w3.org/2001/XMLSchema","int"),ParameterMode.IN);
call.setReturnType(newQName("http://www.w3.org/2001/XMLSchema"),"World");
>>>
>
call.setTargetEndpointAddress("http://localhost:7001/types/HelloWorldTypes?W
SDL");
World w1 = new World();
World world =(World)call.invoke(new Object[]{w1,"pranav",10});
}
}
Service Name in ant is "Types"
Thanks
Awaiting your help.......................

解决手机开发中难点:如何实现J2ME对话框

在手机这么小的屏幕上开发应用,难点之一就是频繁的屏幕切换。尽管midp2.0的UI部分已经很丰富了,但这些UI部件都是基于事件回调的。这在处理大量的、简单的问答式交互时显得力不从心。
本文实现了一个阻塞当前线程的对话框,简要地说,你可以使用诸如win32API中dialog函数那样的方式来实现对话框并阻塞等待返回值,然后根据返回值进行不同的处理。听起来很诱人吧。
首先回顾一下MIDP UI的事件处理机制。有两个要点:
1)首先UI部分由系统的一个线程负责维护。也就是说不能阻塞系统的事件处理方法。
2)事件处理使用的是一种回调机制。首先UI部件使用诸如setCommandListener之类的方法为自己注册一个回调接口(其中的回调方法由用户实现);等到触发了相应事件就调用这个注册好的接口的回调方法。
以下是一个实现了CommandListener的类的代码片断:
Form f=new Form("Hello world");
f.addCommand(exit);
f.setCommandListener(this);
可以想象基于事件回调的处理方式,在处理大量的、简单的问答式交互时显得力不从心。你不得不为每一个仅仅是询问要不要继续的对话框而实现一个又一个类,或者处理一个复杂的回调函数。如果选择后者,那么在一个又一个的if-else中处理不同逻辑事件的代码片断一定会烦死你。
较好的做法
这时候我们不免怀念一下win32 Api中对话框函数的处理方式:
int choose=Dialog(title,type……);
if(choose==OK){……}
else if(choose==Cancel){……}
这样处理将会阻塞当前线程,等待返回值,然后根据返回值进行处理。这样做的原因就是在一个逻辑性很完整的任务中,你可以一次性在一个回调方法中完成所有逻辑,而不必为了问询简单的YES/NO问题而在不同的类中间跳来跳去。
如何在MIDP下实现
我们遇到的第一个问题来自于我们的方法必须要阻塞当前线程等待返回值。也就是说,这个对话框不能在UI的回调中直接运行,比如commandAction中。解决办法是将所有的事件处理都放到一个线程类中处理。(这是一点额外的负担,但不可避免)。还好这个工作量不大,要想实现两个对象之间的通信也不难。
第二个问题是如何阻塞当前的线程,我们祭出java线程的三板斧之wait()/notifyAll()。我们可以指定一个信号量(初值false),当其为false时阻塞当前线程,在得到用户通知后将信号量改为true,并唤醒线程。
下面看一下主要思路:
看一下代码:
Dialog.java
/*
*为j2me提供阻塞的dialog调用方法。
*但前提是,
如果要在UI的相应线程中运行
(比如commonAction),
*则需首先打开一个新的线程中使用,
因为UI线程是不可以阻塞的。
*这个版本虽然包含在coreUI2.0中,
但midp1.0也可以用。seimens s57通过测试。
*
*/
package bean;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
/**
* #author Favo
*/
public class Dialog
{
//主类
private boolean blockFlag = false;
public static int YES=0;
public static int NO=1;
private int returnValue;
private Display display;
public Dialog(Display display){
 this.display=display;
}
public void setReturnValue(int i)
{
//设置返回值
 returnValue=i;
}
synchronized boolean getBlockFlag()
{
//取得信号量
 return blockFlag;
}
synchronized void setBlockFlag(boolean flag)
{
//设置信号量
 blockFlag = flag;
}
public int show(String title,
String content,
String yes,String no)
{
 setBlockFlag(false);
 Form f=new DialogForm
 (this,title,content,yes,no);
 display.setCurrent(f);
 //显示UI
 try {
 while(getBlockFlag()==false)
 {
 //如果用户没选择阻塞
  synchronized (this)
{
  wait();
  }
 }
 } catch (InterruptedException e)
 {
 e.printStackTrace();
 System.out.println
 ("InterruptedException in Dialog.show");
 }
 return returnValue;
 //返回
}
public void wakeup()
{
 synchronized (this)
 {
 //唤醒阻塞的线程
 notifyAll();
 }
 
}
}
class DialogForm extends
Form implements CommandListener
{
//UI部分
Command yesCMD;
Command noCMD;
Dialog dialog;
public DialogForm
(Dialog dialog,String title,
String content,String yes,String no)
{
 super(title);
 this.dialog=dialog;
 append(content);
 yesCMD=new Command(yes,Command.OK,1);
 noCMD=new Command(no,Command.CANCEL,1);
 addCommand(yesCMD);
 addCommand(noCMD);
 setCommandListener(this);
}
public void commandAction
(Command c, Displayable d)
{
 if(c==yesCMD)
 {
 dialog.setBlockFlag(true);
 dialog.setReturnValue(Dialog.YES);
 dialog.wakeup();
 }else if(c==noCMD)
 {
 dialog.setBlockFlag(true);
 dialog.setReturnValue(Dialog.NO);
 dialog.wakeup();
 }
}
}
我编写了一个Test。当用户按下show按钮时,开启对话框,并将用户的选择打印出来。
DialogTest.java
package bean;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.midlet.MIDlet;
import javax.microedition.
midlet.MIDletStateChangeException;
public class DialogTest extends
MIDlet implements CommandListener
{
Display display;
Form f = new Form("DialogTest");
Command showCMD =
new Command("show", Command.ITEM, 1);
public DialogTest()
{
 super();
 display = Display.getDisplay(this);
 f.addCommand(showCMD);
 f.setCommandListener(this);
 display.setCurrent(f);
}
protected void startApp()
throws MIDletStateChangeException
{
}
protected void pauseApp()
{
}
protected void destroyApp
(boolean arg0)
throws MIDletStateChangeException
{
}
public void commandAction
(Command c, Displayable d)
{
 new work1(c).start();
}
class work1 extends Thread
{
 Command c;
 
 public work1(Command c)
 {
 super();
 this.c = c;
 }
 public void run()
 {
 super.run();
 if(c==showCMD)
 {
  int choose=new Dialog(display).show
("Choose","Do you like your
Operation?","yes","no");
  if(choose==Dialog.YES)
{
  f.append("Yes,user like\n");
  }else if(choose==Dialog.NO)
{
  f.append("No,user like\n");
  }
  display.setCurrent(f);
 }
 }
}
}
屏幕快照
按下show
用户多次选择的结果
思路不错,顶!
冰晨,我太佩服你了!j2me,很神秘啊,能不能对我在本板块发表的帖子给点建议,谢谢啊。
这个领域,从未涉及,不懂啊。
weiyun_pang
你太客气了吧,以后还要你多多指教呢!!
楼上这位的思路没的说我们支持你
收藏了,以后慢慢看

RandomAccessFile on Server..  Where is File Located???

Hello Professionals:
I have created an oracle trigger on a table on insert that passes the column contents to a java procedure that is intended to write this data to a RandomAccessFile. I am not sure where the file will be created on the Server. I created my java classes on an Oracle 8.1.6 database. My java class (and procedure) that writes the data to the file is indicated below. Your guidance is needed. Thanks. I am logged into the database as teh schema owner of the table and java classes.
Chris
package mypackage1;
import java.io.*;
public class AddData
{
public static void TriggerData(int v_id, String v_name)
{
Record blank;
String fileName = "TriggerData20.dat";
blank = new Record(v_id,v_name);
try {
RandomAccessFile file = new RandomAccessFile(fileName, "rw");
file.seek(file.length());
System.out.println("Just getting ready to write to file");
blank.write(file);
System.out.println("Just written data to file");
System.exit(0);
}
catch (IOException e){
System.out.println("This is not a valid file");
System.exit(1);
}
}
/*
public static void main(String[] args)
{
AddRecord addRecord = new AddRecord();
}
*/
}
--
--
// A class that represents one record of information.
package mypackage1;
import java.io.Serializable;
public class AccountRecord implements Serializable
{
private int account;
private String firstName;
public AccountRecord()
{
this(0,"");
}
public AccountRecord(int acct, String first)
{
setAccount(acct);
setFirstName(first);
}
public void setAccount(int acct)
{
account = acct;
}
public int getAccount(){return account;}
public void setFirstName(String first)
{
firstName = first;
}
public String getFirstName(){return firstName;}
}
--
--
//Record class for RandomAccessFile programs;
//This class will be wrapped as a procedure to call in the Oracle Trigger;
//Two or more values will be passed into the method call Record(xx,xx,etc) from the Oracle table;
package mypackage1;
import java.io.*;
//import AccountRecord class from package!!!!!!!!!!!!!!!!!
public class Record extends AccountRecord
{
//String file = "TriggerData5.dat";
public Record()
{
this(25,"farting");
}
public Record(int acct, String first)
{
super(acct,first);
}
//Read a record from the specified RandomAccessFile
/*{
setAccount(file.readInt() );
setFirstName(padName(file) );
}
private String padName(RandomAccessFile f) throws IOExeption
{
char name[] = new char [15], temp;
for (int i = 0; i < name.length; i++) {
temp = f.readChar();
name[i] = temp;
}
return new String(name).replace('\0',' ' );
}*/
//Write a record to the specified RandomAccessFile
public void write(RandomAccessFile file) throws IOException
{
//file.seek(size());
file.writeInt(getAccount() );
writeName(file, getFirstName() );
}
private void writeName(RandomAccessFile f, String name) throws IOException
{
StringBuffer buf = null;
if (name != null )
buf = new StringBuffer(name);
else
buf = new StringBuffer(15);
buf.setLength(15);
f.writeChars(buf.toString() );
}
/*//Not too sure if I need to have the main method here!!!!!!!!!!!!!!
public static void main(String[] args)
{
Record record = new Record();
}*/
} 
Chris,
i have posted a response on the JDeveloper forum which says:
The file will be created with a root of $ORACLE_HOME ifthe filename is not
an absolute path. The writer must have the proper permissions to write the
file. All subdirectories, if any in the path name, must exist or an
exception will be thrown.
Kuassi
Hello Professionals:
I have created an oracle trigger on a table on insert that passes the column contents to a java procedure that is intended to write this data to a RandomAccessFile. I am not sure where the file will be created on the Server. I created my java classes on an Oracle 8.1.6 database. My java class (and procedure) that writes the data to the file is indicated below. Your guidance is needed. Thanks. I am logged into the database as teh schema owner of the table and java classes.
Chris
package mypackage1;
import java.io.*;
public class AddData
{
public static void TriggerData(int v_id, String v_name)
{
Record blank;
String fileName = "TriggerData20.dat";
blank = new Record(v_id,v_name);
try {
RandomAccessFile file = new RandomAccessFile(fileName, "rw");
file.seek(file.length());
System.out.println("Just getting ready to write to file");
blank.write(file);
System.out.println("Just written data to file");
System.exit(0);
}
catch (IOException e){
System.out.println("This is not a valid file");
System.exit(1);
}
}
/*
public static void main(String[] args)
{
AddRecord addRecord = new AddRecord();
}
*/
}
--
--
// A class that represents one record of information.
package mypackage1;
import java.io.Serializable;
public class AccountRecord implements Serializable
{
private int account;
private String firstName;
public AccountRecord()
{
this(0,"");
}
public AccountRecord(int acct, String first)
{
setAccount(acct);
setFirstName(first);
}
public void setAccount(int acct)
{
account = acct;
}
public int getAccount(){return account;}
public void setFirstName(String first)
{
firstName = first;
}
public String getFirstName(){return firstName;}
}
--
--
//Record class for RandomAccessFile programs;
//This class will be wrapped as a procedure to call in the Oracle Trigger;
//Two or more values will be passed into the method call Record(xx,xx,etc) from the Oracle table;
package mypackage1;
import java.io.*;
//import AccountRecord class from package!!!!!!!!!!!!!!!!!
public class Record extends AccountRecord
{
//String file = "TriggerData5.dat";
public Record()
{
this(25,"farting");
}
public Record(int acct, String first)
{
super(acct,first);
}
//Read a record from the specified RandomAccessFile
/*{
setAccount(file.readInt() );
setFirstName(padName(file) );
}
private String padName(RandomAccessFile f) throws IOExeption
{
char name[] = new char [15], temp;
for (int i = 0; i < name.length; i++) {
temp = f.readChar();
name[i] = temp;
}
return new String(name).replace('\0',' ' );
}*/
//Write a record to the specified RandomAccessFile
public void write(RandomAccessFile file) throws IOException
{
//file.seek(size());
file.writeInt(getAccount() );
writeName(file, getFirstName() );
}
private void writeName(RandomAccessFile f, String name) throws IOException
{
StringBuffer buf = null;
if (name != null )
buf = new StringBuffer(name);
else
buf = new StringBuffer(15);
buf.setLength(15);
f.writeChars(buf.toString() );
}
/*//Not too sure if I need to have the main method here!!!!!!!!!!!!!!
public static void main(String[] args)
{
Record record = new Record();
}*/
} 
Thanks Kuassi for the info. I have set up the permissions on the Unix directory and provided the path. It works and thank you for your help.
Chris

Categories

Resources