I've got a wsdl with the following code (just a part):
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:sch="http://www.test.com/App" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://www.test.com/App" targetNamespace="http://www.test.com/App">
<wsdl:types>
<xs:schema xmlns:process="http://www.test.com/App" xmlns:xdb="http://xmlns.oracle.com/xdb" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.test.com/App" version="1.0" xdb:mapStringToNCHAR="true" xdb:mapUnboundedStringToLob="true" xdb:schemaURL="ddd" xdb:storeVarrayAsTable="true">
<xs:simpleType name="ClientCountry">
<xs:restriction base="xs:string">
<xs:enumeration value="CLCO1">
<xs:annotation>
<xs:documentation>Spain</xs:documentation>
</xs:annotation>
</xs:enumeration>
<xs:enumeration value="CLCO2">
<xs:annotation>
<xs:documentation>Portugal</xs:documentation>
</xs:annotation>
</xs:enumeration>
</xs:restriction>
</xs:simpleType>
</xs:schema>
</wsdl:types>
</wsdl:definitions>
I've used this wsdl to generate the Java source files using Eclipse (File->New->Other->Web Services->Web Service Client).
It has generated all classes from the wsdl. However, when generating the enumeration types has made just this:
public class ClientCountry implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = -2280793720095616022L;
private java.lang.String _value_;
private static java.util.HashMap _table_ = new java.util.HashMap();
// Constructor
protected ClientCountry(java.lang.String value) {
_value_ = value;
_table_.put(_value_,this);
}
public static final java.lang.String _CLCO1 = "CLCO1";
public static final java.lang.String _CLCO2 = "CLCO2";
public static final ClientCountry CLCO1 = new ClientCountry(_CLCO1);
public static final ClientCountry CLCO2 = new ClientCountry(_CLCO2);
public java.lang.String getValue() { return _value_;}
public static ClientCountry fromValue(java.lang.String value)
throws java.lang.IllegalArgumentException {
ClientCountry enumeration = (ClientCountry)
_table_.get(value);
if (enumeration==null) throw new java.lang.IllegalArgumentException();
return enumeration;
}
public static ClientCountry fromString(java.lang.String value)
throws java.lang.IllegalArgumentException {
return fromValue(value);
}
public boolean equals(java.lang.Object obj) {return (obj == this);}
public int hashCode() { return toString().hashCode();}
public java.lang.String toString() { return _value_;}
public java.lang.Object readResolve() throws java.io.ObjectStreamException { return fromValue(_value_);}
}
I was wondering if there could be any option to make it generates a simple enumeration class using the xs:documentation description as keys for the enum.
Ok. Using jaxws with maven, the generated class now is:
#XmlType(name = "ClientCountry")
#XmlEnum
public enum ClientCountry {
/**
* Spain
*
*/
#XmlEnumValue("CLCO1")
CLCO_1("CLCO1"),
/**
* Portugal
*
*/
#XmlEnumValue("CLCO2")
CLCO_2("CLCO2");
private final String value;
ClientCountry(String v) {
value = v;
}
public String value() {
return value;
}
public static ClientCountry fromValue(String v) {
for (ClientCountry c: ClientCountry.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
}
Much better, but still not perfect, is it?
Related
I think I'm seeking for trouble for myself using complex structure but I need to get over this problem.
I have object nested in object, then the object list
Here's the base Entity
#Data
public class BaseEntity {
private Long id;
private String name;
private String description;
}
Here's my impactEntity built on the top of base Entity
#Data
public class ImpactEntity implements Structable{
private String ref;
private String ASOF;
private Long deliverTime;
private String SLAMissed;
private BaseEntity client;
private BaseEntity application;
private BaseEntity deliverable;
}
Here's my real final object:
#Data
public class IncidentEntity {
private String PID;
private String ID;
private String NID;
private String REF;
private String RREF;
private String ASOF;
private Long StartTime;
private Long endTime;
private String description;
private String active;
private Long createAt;
private List<ImpactEntity> impacts;
}
Here's my incidentMapper:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.well.valley.mapper.IncidentMapper" >
<resultMap id="IncidentEntity" type="org.well.valley.entity.IncidentEntity">
<result column="PID" jdbcType="VARCHAR" property="PID" />
<result column="ID" jdbcType="VARCHAR" property="ID" />
<result column="NID" jdbcType="VARCHAR" property="NID" />
<result column="REF" jdbcType="VARCHAR" property="REF" />
<result column="RREF" jdbcType="VARCHAR" property="RREF" />
<result column="ASOF" jdbcType="VARCHAR" property="ASOF" />
<result column="STARTTIME" jdbcType="INTEGER" property="startTime" />
<result column="ENDTIME" jdbcType="INTEGER" property="endTime" />
<result column="DESCRIPTION" jdbcType="VARCHAR" property="description" />
<result column="ACTIVE" jdbcType="VARCHAR" property="active" />
<result column="CREATEAt" jdbcType="INTEGER" property="createAt" />
<result property="impacts" column="IMPACTS" typeHandler="org.well.valley.utils.typehandlers.OracleTypeHandler" />
</resultMap>
<select id="get" statementType="CALLABLE" parameterType="org.well.valley.entity.IncidentEntity">
call get_incidents(
#{ASOF, jdbcType=VARCHAR},
#{ref, jdbcType=VARCHAR},
#{active, jdbcType=VARCHAR},
#{outParam.c1, mode=OUT, jdbcType=CURSOR, javaType=java.sql.ResultSet, resultMap=IncidentEntity}
)
</select>
</mapper>
I'm using a customized typeHandler to deal with
<result property="impacts" column="IMPACTS" typeHandler="org.well.valley.utils.typehandlers.OracleTypeHandler" />
Here's my full body of the OracleTypeHandler. I want to make it very generic and be able to deal with anything, including something like List although I haven't started the code to deal with the List in the resultset yet.
public class OracleTypeHandler<T> extends BaseTypeHandler<T> {
private Logger logger = LoggerFactory.getLogger(getClass());
private ObjectMapper objectMapper = new ObjectMapper();
private DBMapperBean getDBMapperBean() {
return SpringContext.getBean(DBMapperBean.class);
}
private Class<T> type;
protected int getIndex(ResultSetMetaData data, String columnName) throws SQLException {
logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>11111111111111111111111111");
for (int i = 1; i <= data.getColumnCount(); i++) {
String c = data.getColumnName(i);
if(columnName.equals(c))
{
return i;
}
}
return -1;
}
public OracleTypeHandler(Class<T> type) {
if (type == null) {
throw new IllegalArgumentException("Type argument cannot be null");
}
this.type = type;
logger.info(">>>>>>>>>>>>>>>>>>>>Type is:{}", type);
}
#Override
public void setNonNullParameter(PreparedStatement ps, int index, T parameter, JdbcType jdbcType)
throws SQLException {
logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>333333333333333333333333");
Connection conn = ps.getConnection();
if(parameter.getClass().isArray()) {
if(parameter instanceof String[]) {
Array array = ((OracleConnection) conn).createOracleArray("STRINGARRAY", parameter);
ps.setArray(index, array);
array.free();
}
}
}
#Override
public T getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
ResultSetMetaData metaData = resultSet.getMetaData();
logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>444444444444444444444444444444");
int index = getIndex(metaData, columnName);
String columnClassName = metaData.getColumnClassName(index);
if(columnClassName.equals("oracle.jdbc.OracleStruct"))
{
java.sql.Struct o = (java.sql.Struct)resultSet.getObject(index);
return extractObject(o);
}else if(columnClassName.equals("oracle.jdbc.OracleArray"))
{
Array array = resultSet.getArray(columnName);
Object r = array.getArray();
array.free();
return (T) r;
}
return null;
}
private String typeNameConvert(String type, String target)
{
if(target.equals("DBTYPE"))
{
return type.concat("TYPE");
}else
{
return type.substring(0, type.length()-4);
}
}
private T extractObject(Struct o) throws SQLException {
String typeName = o.getSQLTypeName();
typeName = typeName.substring(typeName.lastIndexOf(".")+1);DBMapperBean dbMapperBean = getDBMapperBean();
typeName = typeNameConvert(typeName, "JAVATYPE");
if(typeName.endsWith("ARRAY"))
{
switch (typeName){
case "STRINGARRAY":
break;
}
}else {
HashMap <String, Class> map = dbMapperBean.getMap();
try {
Class<?> cls = (Class<?>) map.get(typeName);
Structable obj = (Structable) cls.getDeclaredConstructor().newInstance();
Object[] attrs = o.getAttributes();
List<Field> fields = obj.getOrderedField(obj.getClass().getDeclaredFields());
int i = 0;
for (Field f : fields) {
f.setAccessible(true);
Object source = attrs[i];
if(source == null)
{
f.set(obj, null);
}
else {
Class targetType = f.getType();
Class sourceType = source.getClass();
if (Number.class.isAssignableFrom(targetType) && Number.class.isAssignableFrom(sourceType)) {
if (targetType == Long.class) {
source = Long.parseLong(source.toString());
}
}
try {
f.set(obj, source);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
i++;
}
return (T) obj;
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
return null;
}
#Override
public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>66666666666666666");
Struct struct =(java.sql.Struct) rs.getObject(columnIndex);
return extractObject(struct);
}
#Override
public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>7777777777777777777");
Struct struct =(java.sql.Struct) cs.getObject(columnIndex);
return extractObject(struct);
}
}
So even before the DB stored procedure is called, the constructor of the OracleTypeHandler is called, which is expected, as it's to build up a List of the object of objects
19:58:28.439 INFO o.w.v.u.t.OracleTypeHandler - >>>>>>>>>>>>>>>>>>>>Type is:class org.well.valley.entity.BaseEntity
19:58:33.692 INFO o.w.v.u.t.OracleTypeHandler - >>>>>>>>>>>>>>>>>>>>Type is:class org.well.valley.entity.BaseEntity
20:02:43.477 INFO o.w.v.u.t.OracleTypeHandler - >>>>>>>>>>>>>>>>>>>>Type is:class org.well.valley.entity.BaseEntity
20:02:47.161 INFO o.w.v.u.t.OracleTypeHandler - >>>>>>>>>>>>>>>>>>>>Type is:class org.well.valley.entity.BaseEntity
20:03:00.370 INFO o.w.v.u.t.OracleTypeHandler - >>>>>>>>>>>>>>>>>>>>Type is:class [Ljava.lang.String;
20:03:16.080 INFO o.w.v.u.t.OracleTypeHandler - >>>>>>>>>>>>>>>>>>>>Type is:interface java.util.List
However, after my DB stored procedure is called, none of the 3 getNullableResult methods in the typehandler is entered, while I would expect for whatever result set is retrieved one of them should be entered. To be more specific I think this one should be entered, as this is the one to retrieve the result using column name. I was expecting to do some job inside this method. However, it's not entered, and returned an empty List(but if I call the procedure in DB directly I got the result)
public T getNullableResult(ResultSet resultSet, String columnName) throws SQLException
So - can someone please advise what's the reason the getNullableResult methods were not entered? Which typehandler Mybatis us in this case to deal with my impactList?
Thanks a million
I am trying to implement an extension in JDeveloper. It creats a submenu when you click on a DB package.
THe issue comes when I click on an element of my custom submenu, it returns a null pointer Exception.
I can't figure out where I did wrong.
Would you please help me?
Here is how a I created the submenu:
submenu.xml File:
<?xml version="1.0" encoding="windows-1252" ?>
<!-- usage of a name space?-->
<items id="my.contextMenu">
<folder type="PACKAGE">
<name>User Defined Context Menu</name>
<item reloadparent="true"
action-ref="utilitytools.customSave">
<title>saveThisPackage</title>
</folder>
</items>
extension.xml file:
<?xml version="1.0" encoding="UTF-8" ?>
<extension id="utilitytools" version="1.0" esdk-version="1.0"
rsbundle-class="utilitytools.Res"
xmlns="http://jcp.org/jsr/198/extension-manifest">
<name>Utility Tools</name>
<owner>A name</owner>
<dependencies>
<import>oracle.sqldeveloper</import>
<import>oracle.ide</import>
</dependencies>
<hooks>
<jdeveloper-hook xmlns="http://xmlns.oracle.com/jdeveloper/1013/extension">
<addins>
<addin>utilitytools.UtilityToolsAddin</addin>
</addins>
<actions xmlns="http://xmlns.oracle.com/jdeveloper/1013/extension">
<action id="utilitytools.customSave">
<properties>
<property name="Name">saveThisPackage</property>
<property name="SmallIcon"></property>
<property name="LongDescription"></property>
</properties>
<controller-class>utilitytools.savePackageController</controller-class>
<command-class>utilitytools.savePackageCommand</command-class>
</action>
</actions>
</jdeveloper-hook>
<sqldev-navigator-hook xmlns="http://xmlns.oracle.com/sqldeveloper/sqldev-navigator">
<descriptor>submenu.xml</descriptor>
</sqldev-navigator-hook>
</hooks>
</extension>
SubmenuListener file:
public final class SubMenuListener implements ContextMenuListener {
public SubMenuListener() {
super();
}
public void menuWillShow(ContextMenu contextMenu) {
contextMenu.add( contextMenu.createMenuItem(
IdeAction.find( savePackageCommand.actionId() )
));
}
public void menuWillHide(ContextMenu contextMenu) {
//Nothing
}
public boolean handleDefaultAction(Context context) {
return false;
}
}
And the command file:
/**
* Command handler for utilitytools.customSave.
*/
#RegisteredByExtension("utilitytools")
public final class sauvegardePackageCommand extends Command {
public savePackageCommand() {
super(actionId());
}
public int doit() {
SwingUtilities.invokeLater(new Runnable(){
public void run(){
showSaveWindow();
}
});
return OK;
}
/**
* Returns the id of the action this command is associated with.
*
* #return the id of the action this command is associated with.
* #throws IllegalStateException if the action this command is associated
* with is not registered.
*/
public static int actionId() {
final Integer cmdId = Ide.findCmdID(".utilitytools.customSave");
if (cmdId == null)
throw new IllegalStateException("Action esdksample.showElementClass not found.");
return cmdId;
}
private static void showSaveWindow(){
JFrame frame = new JFrame("SAVE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JPanelSavePackage());//Or any window you want to popup
frame.pack();
frame.setVisible(true);
}
}
I'm developing a web app using struts 2 framework and i'm facing a problem with select tag in a jsp.
The select tag seems to work fine, but as soon as i press the submit button, my action cannot get the data from the select.
I have looked for problems about select, but all of them seem to be related with the list.
In my case, the list is shown fine. So, I'm quite lost and I dont know what should I do.
Here are my jsp code and my action code. When I press the submit, it suppose that the form will be sent to my action, and I shoud get the data from the form, but when I print the data is always null.
JSP Code:
<s:form action="borrarCita" method="post">
<s:select id="idCita" name="idCita" list="pendings" listKey="idCita" listValue="fecha" label="Elija una cita a anular"></s:select>
<s:submit value="Aceptar"/>
</s:form>
The action code:
public class CitasAction extends ActionSupport implements SessionAware{
private static final long serialVersionUID = 1L;
private Map session = ActionContext.getContext().getSession();
private List pendings= new ArrayList<Cita>();
private String idCita;
private String desplegarCitasPendientes;
private String pedirCita;
private String consultarCitas;
private String citaAnulada;
public String execute(){
return SUCCESS;
}
public String pedirCita(){
setCitaAnulada("");
setDesplegarCitasPendientes("");
setConsultarCitas("");
DbService db = (DbService)session.get("db");
Paciente paciente = (Paciente)session.get("Paciente");
List listaMedicos = db.getListaMedicos();
session.remove("listaCitas");
session.put("listaMedicos", listaMedicos);
setPedirCita("ok");
return SUCCESS;
}
public String desplegarCitasPendientes(){
setCitaAnulada("");
setPedirCita("");
setConsultarCitas("");
Paciente pac = (Paciente)session.get("user");
Iterator<Cita> nombreIterator = pac.getCitas().iterator();
while(nombreIterator.hasNext()){
Cita primera = nombreIterator.next();
if(primera.getStatus().equals("Pending")){
getPendings().add(primera);
}
}
setDesplegarCitasPendientes("ok");
return SUCCESS;
}
public String borrarCita(){
setConsultarCitas("");
setPedirCita("");
setDesplegarCitasPendientes("");
System.out.println(getIdCita());
System.out.println(ActionContext.getContext().getParameters().toString());
Paciente pac = (Paciente)session.get("user");
/*
Iterator<Cita> iterator = pac.getCitas().iterator();
while(iterator.hasNext()){
Cita primera = iterator.next();
if(primera.getFecha().equals(getFecha())){
iterator.remove();
break;
}
}
pac.setCitas(getPendings());
pac.getCitas().remove(getCitaSeleccionada());
session.put("user", pac);
DbService db = (DbService)session.get("db");
db.uploadPaciente(pac);*/
setCitaAnulada("ok");
return SUCCESS;
}
public String consultarCitas(){
setPedirCita("");
setDesplegarCitasPendientes("");
setCitaAnulada("");
setConsultarCitas("ok");
return SUCCESS;
}
public Map getSession() {
return session;
}
public void setSession(Map session) {
this.session = session;
}
public List getPendings() {
return pendings;
}
public void setPendings(List pendings) {
this.pendings = pendings;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
public String getDesplegarCitasPendientes() {
return desplegarCitasPendientes;
}
public void setDesplegarCitasPendientes(String desplegarCitasPendientes) {
this.desplegarCitasPendientes = desplegarCitasPendientes;
}
public String getPedirCita() {
return pedirCita;
}
public void setPedirCita(String pedirCita) {
this.pedirCita = pedirCita;
}
public String getConsultarCitas() {
return consultarCitas;
}
public void setConsultarCitas(String consultarCitas) {
this.consultarCitas = consultarCitas;
}
public String getCitaAnulada() {
return citaAnulada;
}
public void setCitaAnulada(String citaAnulada) {
this.citaAnulada = citaAnulada;
}
public String getIdCita() {
return idCita;
}
public void setIdCita(String idCita) {
this.idCita = idCita;
}
}
So, to sum up, I have that select tag in a jsp and when a press the submit, the action doesn't get any data from the select.
I hope someone can help me with this because it's driving me crazy.
If you need more information, please let me know and I will try to post it as soon as posible.
Thanks in advance.
Edit:
Here is a part of the Cita.class code. Also it has the setters and the getters for every attribute.
public class Cita implements Serializable{
#Id #GeneratedValue
#Column(name="CITA_ID")
private int idCita;
#Column(name="FECHA")
#Temporal(TemporalType.DATE)
private Date fecha;
#Column(name="HORA")
#Temporal(TemporalType.TIME)
private Date hora;
#Column(name="ESTADO")
private String status;
#Column(name="ESPECIALIDAD")
private String especialidad;
#ManyToOne
#JoinColumn(name="MEDICO_ID")
private Medico medico;
#ManyToOne
#JoinColumn(name="PACIENTE_ID")
private Paciente paciente;
And here is the struts.xml:
<interceptors>
<interceptor name="logger" class="interceptor.LoginInterceptor"/>
<interceptor-stack name="myStack">
<interceptor-ref name="logger"/>
</interceptor-stack>
</interceptors>
<action name="desplegarCitasPendientes" class="action.CitasAction" method="desplegarCitasPendientes">
<interceptor-ref name="myStack"/>
<result name="success">/citas.jsp</result>
<result name="login" type="redirect">/index.jsp</result>
<result name="input">/index.jsp</result>
</action>
<action name="borrarCita" class="action.CitasAction" method="borrarCita">
<interceptor-ref name="myStack"/>
<result name="success">/citas.jsp</result>
<result name="login" type="redirect">/index.jsp</result>
<result name="input">/index.jsp</result>
</action>
#Jeroen, sorry for the huge wall of code. It was my first post here.
#Roman, I hope this helps you to help me :-)
Thanks for your replies guys.
Edit 2:
Here is my LoginInterceptor:
public class LoginInterceptor extends AbstractInterceptor {
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
public String intercept(final ActionInvocation invocation) throws Exception {
Map<String, Object> session = invocation.getInvocationContext().getSession();
// sb: if the user is already signed-in, then let the request through.
if (session.get("user") != null) {
return invocation.invoke();
}else{
System.out.println("redirect");
return "login";
}
}
}
If you need something else, let me know :-)
Looks like a Interceptor issue.
What is myStack ?
Here's a sample stack I use in my projects (with Login Interceptor)
<package name="test" extends="struts-default">
<interceptors>
<interceptor name="nlogin" class="interceptors.LoginInterceptor"/>
<interceptor-stack name="loginStack">
<interceptor-ref name="nlogin"/>
<interceptor-ref name="defaultStack"/>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="loginStack"/>
<action name="test-list" class="actions.InboxAction">
<result>/pages/inbox/list.jsp</result>
</action>
</package>
loginStack is being used as the defaultStack for all actions in that package, because of <default-interceptor-ref name="loginStack"/>
ok guys, It seems that I fixed it. Thanks to the coding_idiot's answer, I was able to figure out what was wrong. It seems that lack of defaultStack in my own stack was the problem. I just added the defaultStack and it looks like working fine now.
So, thank you very much to everyone and specially to coding_idiot.
The code finally looks like:
<interceptors>
<interceptor name="logger" class="interceptor.LoginInterceptor"/>
<interceptor-stack name="myStack">
<interceptor-ref name="logger"/>
<interceptor-ref name="defaultStack"/>
</interceptor-stack>
</interceptors>
I am having a controller class with two types of methods. first type must execute its body as soon as URL is hit suppose "http://localhost:8080/SpringAOP1/welcome/two/aa". Here SpringAOP1 is my project,welcome is the controller class name(Which is set with annotation) and two is the function name with parameter "aa".
The Second type of function needs to be pre-handled by a interceptor.So when URL is hit suppose "http://localhost:8080/SpringAOP1/welcome/intercep/six/aa" the interceptor must be called. Here i am passing the "intercep" parameter with all those functions of second type which needs interceptor call.
Controller class:-
#Controlle
#RequestMapping("/welcome")
public class HelloController {
#RequestMapping(method = RequestMethod.GET)
public String printWelcome1(ModelMap model) {
model.addAttribute("message", "Spring 3 MVC Hello World 1");
return "hello";
}
#RequestMapping( value="two/{name}", method = RequestMethod.GET)
public String printWelcome2(#PathVariable String name,ModelMap model) {
model.addAttribute("message", "Spring 3 MVC Hello World 2");
model.addAttribute("value", name);
return "hello";
}
#RequestMapping( value="intercep/six/{name}", method = RequestMethod.GET)
public String printWelcome6(#PathVariable String name,ModelMap model) {
model.addAttribute("message", "Spring 3 MVC Hello World 6");
model.addAttribute("value", name);
return "hello";
}
`
Dispatcher servlet
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.mkyong.common.controller" />
<bean name="HijackBeforeMethod" class="com.mkyong.common.controller.HijackBeforeMethod"/>
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/intercep/*"/>
<bean id="HijackBeforeMethod" class="com.mkyong.common.controller.HijackBeforeMethod" />
</mvc:interceptor>
</mvc:interceptors>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="order" value="0" />
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
HijackBeforeMethod
(This is the interceptor Class which is called)
public class HijackBeforeMethod extends HandlerInterceptorAdapter {
public Boolean comp(String u,String p)
{
Map mMap = new HashMap();
mMap.put("aa", "bb");
mMap.put("mm", "nn");
mMap.put("xx", "yy");
Iterator iter = mMap.entrySet().iterator();
String k,v;
Boolean flg=false;
while (iter.hasNext())
{
Map.Entry mEntry = (Map.Entry) iter.next();
if(mEntry.getKey().equals(u) && mEntry.getValue().equals(p))
flg=true;
}
return flg;
}
public boolean preHandle(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse, Object o) throws Exception {
String u="aa";
String p="bb";
//System.out.println(" The username is--> "+u+" and pass is --> "+p);
Boolean ch=comp(u,p);
if(ch)
{
if(httpServletRequest.getMethod().equalsIgnoreCase("get")){
String uri = httpServletRequest.getRequestURI();
System.out.println("The method is GET :: "+ uri);
}
else
{
return false;
}
}
}
Please help me finding this. I am in greate trouble..
You can use the WebRequestInterceptor interface instead of HandlerInterceptorAdapter.
The following code segment is working fine for me.
public class FlashInterceptor implements WebRequestInterceptor {
private Flash flash;
#Autowired
public void setFlash(Flash flash) {
this.flash = flash;
}
#Override
public void preHandle(WebRequest request) throws Exception {
final Map<String, Object> messages = flash.getMessages();
if (messages.containsKey("flash_info")) {
request.setAttribute("flash_info", messages.get("flash_info"),
RequestAttributes.SCOPE_REQUEST);
request.setAttribute("flash_info_params",
messages.get("flash_info_params"),
RequestAttributes.SCOPE_REQUEST);
}
if (messages.containsKey("flash_error")) {
request.setAttribute("flash_error", messages.get("flash_error"),
RequestAttributes.SCOPE_REQUEST);
request.setAttribute("flash_error_params",
messages.get("flash_error_params"),
RequestAttributes.SCOPE_REQUEST);
}
if (messages.containsKey("flash_success")) {
request.setAttribute("flash_success",
messages.get("flash_success"),
RequestAttributes.SCOPE_REQUEST);
request.setAttribute("flash_success_params",
messages.get("flash_success_params"),
RequestAttributes.SCOPE_REQUEST);
}
flash.reset();
}
#Override
public void postHandle(WebRequest request, ModelMap model) throws Exception {
}
#Override
public void afterCompletion(WebRequest request, Exception ex)
throws Exception {
}
}
I am getting started with JaxB and am using the Moxy implementation. I have an industry standard xsd that I converted to Java Object Model using Jaxb. I have gotten as far as annotating simple fields like string,integer and date.
I have been searching and need to be pointed in the right direction to annotate the following field which is a xsd complex type which has 4 attributes and an optional string element. A subset of the generated code is as follows:
Conditions.java
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"condition"
})
#XmlRootElement(name = "conditions")
public class Conditions {
protected List<Conditions.Condition> condition;
public List<Conditions.Condition> getCondition() {
if (condition == null) {
condition = new ArrayList<Conditions.Condition>();
}
return this.condition;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = {
"problemDate",
"problemType",
"problemCode",
"problemStatus",
})
public static class Condition {
protected IvlTs problemDate;
//This is the field I need to annotate (problemType)
protected Cd problemType;
//The 2 below fields (problemCode, problemStatus) will also have to be annotated but I am just focusing on problemType for now
protected Cd problemCode;
protected Ce problemStatus
public void setProblemDate(IvlTs value) {
this.problemDate = value;
}
public void setProblemType(Cd value) {
this.problemType = value;
}
public void setProblemCode(Cd value) {
this.problemCode = value;
}
public void setProblemStatus(Ce value) {
this.problemStatus = value;
}
//omitted getters
}
Cd.java
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "cd", propOrder = {
"originalText",
})
public class Cd {
protected Object originalText;
#XmlAttribute(name = "code")
#XmlSchemaType(name = "anySimpleType")
protected String code;
#XmlAttribute(name = "displayName")
#XmlSchemaType(name = "anySimpleType")
protected String displayName;
#XmlAttribute(name = "codeSystem")
#XmlSchemaType(name = "anySimpleType")
protected String codeSystem;
#XmlAttribute(name = "codeSystemName")
#XmlSchemaType(name = "anySimpleType")
protected String codeSystemName;
#XmlAttribute(name = "nullFlavor")
protected NullFlavorType nullFlavor;
//ommitted getters and setters
The Cd.java class will be used for a number of other classes, not only in the Conditions.java class.
My question in particular is how would I annotate my fields for problemType in Conditions.java, where problemType has 4 attributes and one optional element.
I will not be able to directly annotate Cd.java as the xml input will differ depending on what class I am implementing (choice of 8 other classes that use Cd.java class). The existing annotations above were auto-generated by Jaxb The xml input for the Conditions.java problemType is as follows:
<PROBLEM_MODULE>
<code>24434</code> //Maps to protected String code in Cd.java;
<codeName>ICD-9</codeName> //Maps to protected String codeSystem in Cd.java;
<display>Asthma</display> //Maps to protected String displayName in Cd.java;
<codeSystem>2.564.34343.222</codeSystem> // Maps to protected String codeSystemName in Cd.java;
</PROBLEM_MODULE>
Please advise where I need to clarify my question. Ultimately I am requesting resources or tutorial to help me through this.
******UPDATE*******
Blaise's solution worked perfectly as I tested it on another project that is not as complex. Thus, the method is right, but there is something that I am getting wrong with the metadata file. I updated the Conditions.java file above, as I left out details that may effect the way I need to implement the metadata file.
My oxm.xml file
<?xml version="1.0" encoding="UTF-8"?>
<xml-bindings
xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
package-name="conditions.exec"
xml-mapping-metadata-complete="true">
<java-types>
<java-type name="Conditions" xml-accessor-type="FIELD">
<xml-root-element name="PROBLEM_MODULE"/>
</java-type>
<java-type name="Cd" xml-accessor-type="FIELD">
<java-attributes>
<xml-type prop-order="code codeSystem displayName codeSystemName"/>
<xml-element java-attribute="codeSystem" name="codeName"/>
<xml-element java-attribute="displayName" name="display"/>
<xml-element java-attribute="codeSystemName" name="codeSystem"/>
</java-attributes>
</java-type>
</java-types>
</xml-bindings>
*Main Class*
public static void main(String[] args) {
try {
Map<String, Object> properties = new HashMap<String, Object>(1);
properties.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, new File("src/conditions/exec/oxm.xml"));
JAXBContext jc = JAXBContext.newInstance(new Class[] {Conditions.class,Cd.class}, properties);
// create an Unmarshaller
Unmarshaller u = jc.createUnmarshaller();
conditions.exec.Conditions InventoryInput = (conditions.exec.Conditions) u.unmarshal(
new File("src/conditions/exec/problems.xml")); //input file
// create a Marshaller and marshal to a file
Marshaller resultMarshaller = jc.createMarshaller();
resultMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
resultMarshaller.marshal(InventoryInput, System.out);
} catch (JAXBException je) {
je.printStackTrace();
}
You can leverage EclipseLink JAXB (MOXy)'s external binding file to apply a second mapping to your class:
oxm.xml
One thing that I have set in this file is xml-mapping-metadata-complete="true", this setting tells MOXy to ignore the annotations completely and just use this file. By default the OXM file is used to supplement the annotations.
<?xml version="1.0"?>
<xml-bindings
xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
package-name="forum7043389"
xml-mapping-metadata-complete="true">
<java-types>
<java-type name="Root2">
<xml-root-element/>
</java-type>
<java-type name="Cd">
<xml-type prop-order="code codeSystem displayName codeSystemName"/>
<java-attributes>
<xml-element java-attribute="codeSystem" name="codeName"/>
<xml-element java-attribute="displayName" name="display"/>
<xml-element java-attribute="codeSystemName" name="codeSystem"/>
</java-attributes>
</java-type>
</java-types>
</xml-bindings>
Demo
The oxm.xml file is passed in as a property to create the JAXBContext. In the example below jc1 is created on the classes and jc2 is created on the classes and oxm.xml
package forum7043389;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import org.eclipse.persistence.jaxb.JAXBContextFactory;
public class Demo {
public static void main(String[] args) throws Exception {
Cd cd = new Cd();
cd.setCode("24434");
cd.setCodeSystem("ICD-9");
cd.setDisplayName("Asthma");
cd.setCodeSystemName("2.564.34343.222");
JAXBContext jc1 = JAXBContext.newInstance(Root1.class);
Marshaller marshaller1 = jc1.createMarshaller();
marshaller1.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
Root1 root1 = new Root1();
root1.setCd(cd);
marshaller1.marshal(root1, System.out);
Map<String, Object> properties = new HashMap<String, Object>(1);
properties.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, "forum7043389/oxm.xml");
JAXBContext jc2 = JAXBContext.newInstance(new Class[] {Root2.class}, properties);
Marshaller marshaller2 = jc2.createMarshaller();
marshaller2.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
Root2 root2 = new Root2();
root2.setCd(cd);
marshaller2.marshal(root2, System.out);
}
}
Output
The following is the output from running the demo:
<?xml version="1.0" encoding="UTF-8"?>
<root1>
<cd code="24434" displayName="Asthma" codeSystem="ICD-9" codeSystemName="2.564.34343.222"/>
</root1>
<?xml version="1.0" encoding="UTF-8"?>
<root2>
<cd>
<code>24434</code>
<codeName>ICD-9</codeName>
<display>Asthma</display>
<codeSystem>2.564.34343.222</codeSystem>
</cd>
</root2>
Cd
package forum7043389;
import javax.xml.bind.annotation.*;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "cd", propOrder = {"originalText",})
public class Cd {
protected Object originalText;
#XmlAttribute(name = "code")
#XmlSchemaType(name = "anySimpleType")
protected String code;
#XmlAttribute(name = "displayName")
#XmlSchemaType(name = "anySimpleType")
protected String displayName;
#XmlAttribute(name = "codeSystem")
#XmlSchemaType(name = "anySimpleType")
protected String codeSystem;
#XmlAttribute(name = "codeSystemName")
#XmlSchemaType(name = "anySimpleType")
protected String codeSystemName;
#XmlAttribute(name = "nullFlavor")
protected NullFlavorType nullFlavor;
public Object getOriginalText() {
return originalText;
}
public void setOriginalText(Object originalText) {
this.originalText = originalText;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getCodeSystem() {
return codeSystem;
}
public void setCodeSystem(String codeSystem) {
this.codeSystem = codeSystem;
}
public String getCodeSystemName() {
return codeSystemName;
}
public void setCodeSystemName(String codeSystemName) {
this.codeSystemName = codeSystemName;
}
public NullFlavorType getNullFlavor() {
return nullFlavor;
}
public void setNullFlavor(NullFlavorType nullFlavor) {
this.nullFlavor = nullFlavor;
}
}
Root1
package forum7043389;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class Root1 {
private Cd cd;
public Cd getCd() {
return cd;
}
public void setCd(Cd cd) {
this.cd = cd;
}
}
Root2
package forum7043389;
public class Root2 {
private Cd cd;
public Cd getCd() {
return cd;
}
public void setCd(Cd cd) {
this.cd = cd;
}
}
For More Information
http://wiki.eclipse.org/EclipseLink/UserGuide/MOXy/Runtime/XML_Bindings
http://blog.bdoughan.com/2010/12/extending-jaxb-representing-annotations.html
http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html