Primavera WebServices ResourceHour.setDate(date) Date cannot be null - SPOUG - Spain Oracle Users Group

Estoy intentando agregar una fecha a una variable del tipo ResourceHour pero me sale un error de "Date cannot be null".Aquí está el código que tengo: public void gestionResourceHour() throws Exception {        String url = Connect.makeHttpURLString(Connect.host, Connect.port, RESOURCE_HOUR_SERVICE);        URL wsdlURL = new URL(url);         ResourceHourService service = new ResourceHourService(wsdlURL);        ResourceHourPortType servicePort = service.getResourceHourPort();        Client client = ClientProxy.getClient(servicePort);        Connect.setCookieOrUserTokenData(client);         List<ResourceHourFieldType> fields = new ArrayList<ResourceHourFieldType>();        fields.add(ResourceHourFieldType.OBJECT_ID);        fields.add(ResourceHourFieldType.ACTIVITY_OBJECT_ID);        fields.add(ResourceHourFieldType.RESOURCE_ID);        fields.add(ResourceHourFieldType.RESOURCE_OBJECT_ID);        fields.add(ResourceHourFieldType.APPROVED_HOURS);        fields.add(ResourceHourFieldType.DATE);        fields.add(ResourceHourFieldType.RESOURCE_ASSIGNMENT_OBJECT_ID);        fields.add(ResourceHourFieldType.STATUS);        fields.add(ResourceHourFieldType.TIMESHEET_PERIOD_OBJECT_ID);        fields.add(ResourceHourFieldType.TIMESHEET_STATUS_DATE);         resourceHours = servicePort.readResourceHours(fields, null, null);        Date actDate = new Date();                Date actualDate = new Date();         TimeZone utc = TimeZone.getTimeZone("UTC");        GregorianCalendar c = new GregorianCalendar(utc);        GregorianCalendar d = new GregorianCalendar(utc);        c.setTime(actDate);        d.setTime(actualDate);        XMLGregorianCalendar gcCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);        XMLGregorianCalendar gcCalendar2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(d);        gcCalendar.setTimezone(DatatypeConstants.FIELD_UNDEFINED);        gcCalendar2.setTimezone(DatatypeConstants.FIELD_UNDEFINED);         ObjectFactory factory = new ObjectFactory();         JAXBElement<Integer> actObjId = factory.createResourceHourActivityObjectId(35857);         JAXBElement<Double> approvedHours = factory.createResourceHourApprovedHours(10.0);         JAXBElement<XMLGregorianCalendar> date = factory.createResourceHourDate(gcCalendar);         JAXBElement<Integer> rsrcAssObjId = factory.createResourceHourResourceAssignmentObjectId(6657);         JAXBElement<XMLGregorianCalendar> timeStatusDate = factory.createResourceHourTimesheetStatusDate(gcCalendar2);         ResourceHour resourceHour = new ResourceHour();         resourceHour.setActivityObjectId(actObjId);        resourceHour.setResourceObjectId(1316);        resourceHour.setApprovedHours(approvedHours);        resourceHour.setDate(date);        resourceHour.setResourceAssignmentObjectId(rsrcAssObjId);        resourceHour.setStatus("Approved");        resourceHour.setTimesheetPeriodObjectId(417);        resourceHour.setTimesheetStatusDate(timeStatusDate);         resourceHours.add(resourceHour);         servicePort.createResourceHours(resourceHours); } Y el error que me sale en el Eclipse: com.primavera.ws.p6.resourcehour.IntegrationFault: Errors located:Date: {0} cannot be null.    at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:131)    at com.sun.proxy.$Proxy39.createResourceHours(Unknown Source)    at code.gestionHojasHoras.gestionResourceHour(gestionHojasHoras.java:384)    at code.MainTimesheet.main(MainTimesheet.java:19)

Related

Can anyone help me???

Hello, i�m a beginner in java and i�m curently triying to make my first aplication, it works fine when runnig from the development tool, but when i make a jar file, it is unable to find the icons and txt file i use in the buttons, labels and text pane
Here�s the source code, the methods crearVentanaRuta and crearVentanaLicencia are the ones who use custom icons. I use the createImageIcon method in the using Swing ciomponents trail of the Java tutorial
/*
* Created on 19-jun-2004
*
*/
package instalerImages;
import herramientas.GeneradorDeVentanas;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import javax.swing.AbstractButton;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JEditorPane;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import eventos.AceptoLicencia;
import eventos.Cancelar;
import eventos.Examinar;
import eventos.Ok;
import eventos.OkLicencia;
/**
* #author Ra�l
*
*/
public class Principal {
public static GeneradorDeVentanas ventanaRuta, ventanaLicencia;
public static JPanel panelDeTextosVentanaRuta;
public static JPanel panelDeBotonesVentanaRuta;
public static JCheckBox acepto, noAcepto;
public static String textoLicencia = new String();
public static JFileChooser menuRuta;
public static JTextField ruta;
public static String rutaPST;
public static void main(String[] args) {
try {
//Crear Ventana Licencia da problemas cuando lo ejecutamos desde el
// so
// el problema est� relacionado con leer el txt ya que no lo ecnuentra
crearVentanaLicencia();
crearVentanaRuta();
//Aqu� habr� que poner un m�todo para crear los arcvhovs con el
// FileInputStream y File
//OutputStream si no son de texto y FileReader y FileWriter si lo
// son
// ejecutarWeiDU();
} catch (Exception e) {
JOptionPane
.showMessageDialog(
null,
" Ha ocurrido un error catastr�fico \n"
+ "Por favor intentelo de nuevo \n"
+ "Es posible que alguno de los ficheros ya existan, de tener la version beta por favor desinstalada y borra los ficheros",
"Ruta no v�lida", JOptionPane.WARNING_MESSAGE);
System.exit(10);
}
}
private static void crearVentanaLicencia() throws Exception {
//Creamos la ventana en si
ventanaLicencia = new GeneradorDeVentanas("Acuerdo de Licencia",
new BorderLayout());
//creamos un area de textoLicencia y un contenedor para ella y los
// botones de acepto y la a�adimos a la ventana en el centro
JEditorPane licencia = new JEditorPane(Principal.class.getResource("images/readme.txt"));
licencia.setEditable(false);
licencia.setBorder(BorderFactory.createLineBorder(Color.black));
licencia
.setToolTipText("Lea este acuerdo de Licencia antes de continuar");
JScrollPane panelDeDesplazamiento = new JScrollPane(licencia,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
panelDeDesplazamiento.setPreferredSize(new Dimension(50, 250));
JPanel panelDeTexto = new JPanel(new BorderLayout());
//Creamos los botones de acepto y no acepto y los a�adimos un control
// de eventos
acepto = new JCheckBox("Acepto");
noAcepto = new JCheckBox("No Acepto");
noAcepto.setSelected(false);
acepto.setSelected(true);
AceptoLicencia aceptacion = new AceptoLicencia();
acepto.addItemListener(aceptacion);
noAcepto.addItemListener(aceptacion);
panelDeTexto.add(panelDeDesplazamiento, BorderLayout.PAGE_START);
panelDeTexto.add(acepto, BorderLayout.EAST);
panelDeTexto.add(noAcepto, BorderLayout.WEST);
JLabel publi = new JLabel(
"Mhoram�s Installer para CLAN Dlan (www.clandlan.net)",
JLabel.CENTER);
publi.setToolTipText("mhoram#clandlan.net");
panelDeTexto.add(publi, BorderLayout.PAGE_END);
ventanaLicencia.addJPanelAPanelConBorderLayout(panelDeTexto,
BorderLayout.CENTER);
//Creamos un panel para los botones y los a�adimos
JPanel panelDeBotonesVentanaLicencia = new JPanel(new BorderLayout());
crearBotonOkyCancelar(panelDeBotonesVentanaLicencia, new OkLicencia(),
new Cancelar());
ventanaLicencia.addJPanelAPanelConBorderLayout(
panelDeBotonesVentanaLicencia, BorderLayout.PAGE_END);
//Creamos una etiqueta para poner el banner de Dlan arriba del todo y
// la a�adimos
JLabel banner = new JLabel(createImageIcon("images/header15.jpg","Banner de Dlan"));
banner.setToolTipText("CLAN Dlan (http://www.clandlan.net)");
ventanaLicencia.getPanelDeVentana()
.add(banner, BorderLayout.PAGE_START);
ventanaLicencia.terminarVentana();
ventanaLicencia.espera();
}
public static void crearVentanaRuta() throws Exception {
//Icono para la etiqueta cancelar
ImageIcon icono = createImageIcon("images/dlanBanner1.jpg","Banner Dlan");
//Layout para la ventana
BorderLayout layoutBasico = new BorderLayout();
//Usamos la clase generadorDeVentanas para crear una Ventana
ventanaRuta = new GeneradorDeVentanas(
"CLAN Dlan Installer para la Traducci�n del PST v0.0",
layoutBasico);
//Creamos un panel para la ruta, con un borde
panelDeTextosVentanaRuta = new JPanel(new BorderLayout());
panelDeTextosVentanaRuta.setBorder(BorderFactory.createEmptyBorder(5,
5, 5, 5));
//Creamos un panel para los botones que usa un BorderLayout para
// colocar los elementos
panelDeBotonesVentanaRuta = new JPanel(new BorderLayout());
panelDeBotonesVentanaRuta.setBorder(BorderFactory.createEmptyBorder(5,
5, 5, 5));
crearBotonOkyCancelar(panelDeBotonesVentanaRuta, new Ok(),
new Cancelar());
//Creamos la casilla para introducir la ruta del pst y la a�adimos al
// panel de textoLicencia
ruta = new JTextField("Seleccione su ruta de instalaci�n del PST");
ruta.setEditable(false);
ruta
.setToolTipText("Use el boton Examinar para introducir aqu� la ruta del PST");
//Creamos un boton de examinar que ejecute el JFile Chooser
JButton botonExaminar = new JButton("Examinar...");
botonExaminar.setVerticalTextPosition(AbstractButton.BOTTOM);
botonExaminar.setHorizontalTextPosition(AbstractButton.CENTER);
botonExaminar.addActionListener(new Examinar());
botonExaminar
.setToolTipText("Uselo para buscar e introducir su directorio de instalaci�n del PST");
JLabel etiquetaRuta = new JLabel(
"Use el boton Examinar para introducir la ruta del PST",
JLabel.CENTER);
//Creamos el navegador para examinar los archivos
menuRuta = new JFileChooser();
//Lo marcamos como solo para directorios
menuRuta.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
//A�adimos todo a la ventana
panelDeTextosVentanaRuta.add(ruta, BorderLayout.PAGE_START);
panelDeTextosVentanaRuta.add(botonExaminar, BorderLayout.PAGE_END);
panelDeTextosVentanaRuta.add(etiquetaRuta, BorderLayout.CENTER);
//A�adimos los paneles de textoLicencia y de botoners al principal de
// la
// ventana
ventanaRuta.addJPanelAPanelConBorderLayout(panelDeBotonesVentanaRuta,
BorderLayout.WEST);
ventanaRuta.addJPanelAPanelConBorderLayout(panelDeTextosVentanaRuta,
BorderLayout.EAST);
//A�adimos la imagen de cabecera a la ventan de ruta
JPanel banner = new JPanel();
banner.setToolTipText("CLAN Dlan (http://www.clandlan.net)");
banner.add(new JLabel(icono, JLabel.CENTER));
ventanaRuta.addJPanelAPanelConBorderLayout(banner,
BorderLayout.PAGE_START);
//A�adimos publicidad para el creador, usease, yo
JPanel publi2 = new JPanel();
publi2.add(new JLabel(
"Mhoram�s Installer v0.0 para CLAN Dlan (www.clandlan.net)",
JLabel.CENTER));
publi2.setToolTipText(("mhoram#clandlan.net"));
ventanaRuta.addJPanelAPanelConBorderLayout(publi2,
BorderLayout.PAGE_END);
//terminamos y ense�amos la ventana
ventanaRuta.terminarVentana();
ventanaRuta.espera();
}
private static void crearBotonOkyCancelar(JPanel panel,
ActionListener actionBotonOk, ActionListener actionBotonCancel) {
//Creamos el boton cancelar, le damos orientacion y control de eventos
// y lo a�adimos al panel que corresponda
// Creamos un icono para el boton
ImageIcon iconoCancelar = createImageIcon("images/ico001.jpg","Boton cancelar");
JButton botonCancelar = new JButton(iconoCancelar);
//botonCancelar.setVerticalTextPosition(AbstractButton.CENTER);
//botonCancelar.setHorizontalTextPosition(AbstractButton.CENTER);
botonCancelar
.setToolTipText("Presione aqu� si desea cancelar la instalaci�n.");
botonCancelar.addActionListener(actionBotonCancel);
botonCancelar.setPreferredSize(new Dimension(69, 45));
botonCancelar.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
panel.add(botonCancelar, BorderLayout.EAST);
//mismo para el boton de ok
//ImageIcon iconoBotonOk = new ImageIcon("imagenes.ico002.jpg");
JButton botonOk = new JButton(createImageIcon("images/ico002.jpg","Boton Ok"));
botonOk.setToolTipText("Presione aqu� para continuar");
botonOk.addActionListener(actionBotonOk);
botonOk.setPreferredSize(new Dimension(65, 45));
botonOk.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
panel.add(botonOk, BorderLayout.WEST);
//Creamos las etiquetas de los botones y las a�adimos con la
// orientacion adecuada
JLabel etiquetaBotonOk = new JLabel("Presione Yes para continuar",
JLabel.CENTER);
etiquetaBotonOk.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JLabel etiquetaBotonCancel = new JLabel("Presione No para salir",
JLabel.CENTER);
etiquetaBotonCancel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5,
5));
panel.add(etiquetaBotonOk, BorderLayout.PAGE_START);
panel.add(etiquetaBotonCancel, BorderLayout.PAGE_END);
}
/** Returns an ImageIcon, or null if the path was invalid. */
public static ImageIcon createImageIcon(String path,
String description) {
java.net.URL imgURL = Principal.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL, description);
} else {
System.err.println("No puedo encontrar el fichero: " + path);
return null;
}
}
/*     public static void ejecutarWeiDU(){
     File weidu=new File(archi);
     Runtime.getRuntime().exec(weidu.getAbsolutePath()).waitFor();
     }*/
public synchronized void continuar() {
notifyAll();
}
}
And here you can see a screen of my current project structure, the images for the icons are in the images directory of the instalerimages package
http://www.clandlan.net/foros/uploads/post-21-1088036738.gif
Thanks, and sorry for my poor english 
Does it print out the "No puedo encontrar el fichero: ..." message? 
When you post code, please use [code] and [/code] tags as described in Formatting Help on the message entry page. It makes it much easier to read.
Does it throw any errors when it starts up (either start it from the command line with java -jar <JarName.jar> or open the Java Console by double clicking on Java Icon in the system tray).
Also, check that the resources are in the jar file ( jar tf jarfile ). 
First of all sorry for not using the apropiate code tags. and thanks for the quick answers
The resources exists in the jar file, the problem is that the createImagenIcon can�t find it, it shows me the message for that, but when i run the source with eclipse (without exporting to a jar file) it find all the images and txt files.
It don�t give me more errors than the createIcon warning message and one exception when triying to use the
Principal.class.getResource("imagenes/readme.txt") command
So the problem is that it can�t find the images and txt files but only when exported to a jar file. As i have said before when i run the source code directly without export it works.
Principal.class.getResource("imagenes/readme.txt")
This will look for the .txt files in a directory relative to the Principal.class's package. So if
Principal.class is in package instalerImages then this code will look for the image in:
JarFile!/instalerImages/imagenes/readme.txt.
Try using:
Principal.class.getResource("/imagenes/readme.txt"); <-- See the / at the start of the name?
to look from the top of the jar file:
JarFile!/imagenes/readme.txt
Principal.class.getResource("imagenes/readme.txt")
This will look for the .txt files in a directory
relative to the Principal.class's package. So if
Principal.class is in package instalerImages then this
code will look for the image in:
JarFile!/instalerImages/imagenes/readme.txt.Yes, that�s what i think, but it didn�t work
Try using:
Principal.class.getResource("/imagenes/readme.txt");
<-- See the / at the start of the name?
to look from the top of the jar file:
JarFile!/imagenes/readme.txtI�ve tried both, but they don�t work, in fact if i do that it dosen�t work nor in jar file nor runnig with eclipse.
Actually i�m desesperate, that�s the only problerm i have to finish my program.
Here a link to the jar file and the source code, if anyone have time to take a look
jar file:
http://www.clandlan.net/foros/index.php?act=Attach&type=post&id=64308
Exported project:
http://www.clandlan.net/foros/index.php?act=Attach&type=post&id=64311
Okay, I downloaded your jar file. Despite what you said, it does NOT have any file "imagenes/readme.txt". It DOES, however, have one called "instalerImages/images/readme.txt".
Okay, I downloaded your jar file. Despite what you
said, it does NOT have any file "imagenes/readme.txt".
It DOES, however, have one called
"instalerImages/images/readme.txt".But the main class is in the InstalerImages package, so the relative path should be images/readme.txt .
That�s true or i�m wrong?
Altough i �ve tried also with instalerImages/images/readme.txt and it don�t work..
I�m sorry if i�m being boring or similar 
$ jar tf test.jar
META-INF/MANIFEST.MF
eventos/Cancelar$VolverCancelar.class
eventos/Cancelar.class
eventos/AceptoLicencia.class
eventos/Examinar.class
eventos/OkLicencia.class
eventos/Ok.class
eventos/CancelarDefinitiva.class
herramientas/GeneradorDeVentanas.class
instalerImages/Principal.class
instalerImages/images/ICO001.JPG
instalerImages/images/ICO002.JPG
instalerImages/images/Readme.txt
instalerImages/images/dlanBanner1.JPG
instalerImages/images/header15.jpg
TODO.txt
.classpath
.project
Look at the caps.
ICO001.jpg in the file, ico001.jpg in the jar.
While your filesystem is not caps sensative (and so works in the IDE) the Jar is (and so does not work). 
ICO001.jpg in the file, ico001.jpg in the jar.
should be
ICO001.jpg in the jar file, ico001.jpg in the source code. 
Yes, it works now, i�m ashamed, thanks, i love you guys.

Problems with a cast for a remote Class

Hi!
I have the next code:
URL url = new URL(urlstr);
//se indican el namespace en el que se encuentra el servicio y su nombre
//(esto se puede ver en el WSDL)
QName qname = new QName(namespaceServiceStr,
nameServiceStr);
ServiceFactory factory = ServiceFactory.newInstance();
Service service = factory.createService( url, qname );
IHelloWorld age = ( IHelloWorld ) service.getPort( IHelloWorld.class );
System.out.println( "age.age(" + argument + ")" );
System.out.println( "output:" + age.sayHello( argument ) );
Is a client of a WebService implemented with JAXR.
I want to create a class to do the connection of a service more general. But I don't know how to implement this line
� IHelloWorld age = ( IHelloWorld ) service.getPort( IHelloWorld.class );� without specify the interface that implements the service. I try to do it like this:
Class age = ( Class ) service.getPort( paramNameInterface);
Where paramNameInterface is a string that contains the name of the interface. But this didn't work. The compiler said: �Cannot cast from Remote to Class�
What can I do? 
It is highly unlikely that that call would return an instance of Class, so it's quite possible that you would fail to cast to Class.
Find out what you're actually getting back... 
Hi!
Thanks for your reply. You were right.
Service.getPort did not return an instance of Class. It returns an instance of a generated stub implementation class or a dynamic proxy.
To implement what I want the correct code is:
String nameInstance = "webservice.IHelloWorld";
Proxy px = (Proxy) service.getPort(Class.forName(nameInstance));
Where nameInstance would be a parameter.
For use the proxy and have the request of the service:
IHelloWorld age = (IHelloWorld) px:
Example of what I said:
My new object that implements the connection to the service in a general way:
{color:#0000ff}package com.lasalle.util;
import java.lang.reflect.Proxy;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.rpc.Service;
import javax.xml.rpc.ServiceFactory
/**
*
* #author M.Reyes
*
*/
public class ServiceConnection {
//variables de propietats de connexió al webservice
String propURL= "service.url";
String propServiceName = "service.name";
String propNamespace = "service.namespace";
String nameInstance = null;
Service service = null;
Proxy px = null;
/**
* Constructor
*
* Construeix una connexió amb els valors per defecte
* de nom de la propietat de l'adreça del fitxer wsdlWebService
* ("service.url"), nom del servei ("service.name")
* i namespace ("service.namespace") necessaris
* per la connexió.
*
* #param aNameInstance
*/
public ServiceConnection(String aNameInstance)
{
nameInstance = aNameInstance;
initConnection();
}
/**
* Constructor
*
* Construeix una connexió amb els valors inicials
* especificats per els noms de les propietats
* a agafar del fitxer de configuració per la connexió.
*
* #param anUrl Adreça en la que es troba el
* fitxer wsdl del webservice
* #param aServiceName Nom del servei
* #param aNamespace Namespace en el que es pot trobar el WebService
* #param aNameInstance
*/
public ServiceConnection(String anUrl, String aServiceName, String aNamespace, String aNameInstance)
{
propURL= anUrl;
propServiceName = aServiceName;
propNamespace = aNamespace;
nameInstance = aNameInstance;
initConnection();
}
/**
* Realiza la conexión con el Servicio
*
*/
private void initConnection()
{
//s'agafen els paràmetres necessaris per connectar-se amb el webservice
String urlstr = CollectionProperties.getPropiedad(propURL);
String nameServiceStr = CollectionProperties.getPropiedad(propServiceName);
String namespaceServiceStr = CollectionProperties.getPropiedad(propNamespace);
// S'especifica la ubicació del fitxer wsdl
URL url = new URL(urlstr);
QName qname = new QName(namespaceServiceStr,nameServiceStr);
//Create an instance of service factory
ServiceFactory factory = ServiceFactory.newInstance();
service = factory.createService( url, qname );
//get the proxy
px = (Proxy) service.getPort(Class.forName(nameInstance));
}
public Service getService()
{
return service;
}
public Proxy getProxy()
{
return px;
}
}
{color}
My class that use the previous code for the connection:
{color:#0000ff}package webservice;
import javax.xml.rpc.Service;
import javax.xml.rpc.ServiceFactory;
import java.lang.reflect.Proxy;
import com.lasalle.util.ServiceConnection;
import javax.xml.namespace.QName;
import com.lasalle.util.resources.CollectionProperties;
import java.lang.reflect.Proxy;
import java.net.URL;
public class HelloClient {
public static void main( String[] args ) throws Exception {
if( args.length < 1 )
{
System.out.println( "Usage: AgeClient name" );
System.exit( 0 );
}
String argument = args[ 0 ];
ServiceConnection sc = new ServiceConnection("webservice.IHelloWorld");
Proxy pry = sc.getProxy();
IHelloWorld age = (IHelloWorld) px;
System.out.println( "age.age(" + argument + ")" );
System.out.println( "output:" + age.sayHello( argument ) );
}
{color}
{color:#0000ff}} {color}
Edited by: Fantagir on Sep 20, 2007 7:25 AM 
This is unnecessarily elaborate. The client code has to refer to the required interface by its class, i.e. IHelloWorld, so there's no point in turning that back into a classname string and then back into a class with Class.forName(). Just pass the class directly to the ServiceConnection constructor, so that:
ServiceConnection(String aNameInstance)becomes
ServiceConnection(Class<?> aNameClass)with the appropriate changes within that class. The client then just has to do this:
ServiceConnection sc = new ServiceConnection(webservice.IHelloWorld.class);That way you're also eliminating the unnecessary risk of the String classname and the actual class drifting apart over maintenance.

replaceFirst and replaceAll

Hi,
I'm trying to change strings in some XML documents, using the methods replaceFirst and replaceAll, with the 1.4.0 JDK. My problem is that the substrings don't seem to be replaced. Is there any bug with this method or same particular way to use it ?
Thanks
Lio 
Works for me, though I'm using 1.4.1. Could you post your code? 
Yes, this is my code
while (IndexBorneDebut >= 0) {
IndexBorneDebut = AnalyseEnCours.indexOf(BorneDebut, DernierIndexTrouve); // Recherche de la borne de d�but
if (IndexBorneDebut >= 0) { // Si la borne de d�but a �t� trouv�e
IndexBorneFin = AnalyseEnCours.indexOf(BorneFin, IndexBorneDebut); // Recherche de la borne de fin � partir de l'index de la borne de d�but
if (IndexBorneFin >= 0) { // Si la borne de fin a �t� trouv�e
if ((IndexBorneFin - IndexBorneDebut) < DistanceMaximale) { // Si la distance entre les deux bornes implique que l'on se trouve dans le cas que l'on veut traiter
ZoneScreenOutput = AnalyseEnCours.substring((IndexBorneDebut+86), AnalyseEnCours.indexOf("]", (IndexBorneDebut+86)));
ChaineARemplacer = AnalyseEnCours.substring( IndexBorneDebut, (AnalyseEnCours.indexOf("]", (IndexBorneDebut+86))) + 16);
ChaineDeRemplacement = "<PROP_HOSTFLD_NAME><[!CDATA[" + ZoneScreenOutput + "]]></PROP_HOSTFLD_NAME>";
Pouet=AnalyseEnCours.replaceFirst(ChaineARemplacer, ChaineDeRemplacement);
// test : faire ici un indexof de chaine � remplacer dans analyseencours pour voir si on le trouve bien !
int test, test2;
test = Pouet.indexOf(ChaineARemplacer, 0);
test2 = Pouet.indexOf(ChaineDeRemplacement, 0);
NombreDeChangements++ ;
AuMoinsUnRemplacementEffectue++ ;
// JOptionPane.showMessageDialog(null, ChaineARemplacer );
I'm going to try with the 1.4.1 
The string being replaced looks pretty complex. Remember that replaceAll interprets it as a regex. I am not very good with regexes, and the few times used replaceAll I had to look at the Java regex documentation to make sure I was replacing what I thought I was replacing. Maybe your string needs some escape characters in it.
See the javadoc for java.util.regex.Pattern: http://java.sun.com/j2se/1.4.1/docs/api/java/util/regex/Pattern.html

How to create a File Object with existing folder

Hi, i�m working in a Java instaleer for some files and programs, , i�ve 3 packages, one called instalerImages with the main class and a folder called Images with all the resources. I have one method to copy a File array, and i think i can get it using the listFiles() method with the apropiate FilenameFilter.
The Question is, how can i create a File Object pointing to the images folder in a non system dependant way and that works when exporting all to a jar file?. In the Jar files forum DrClap (thx guy) told me to use ZIPFile utilities, but i can�t find the way to do that, can anyone help?
I�ve tried with getResource().getFile() but it dosen�t work in the jar file.
Here�s the current jar File i `ve:
https://www.alumnos.unican.es/cgi-bin/web-ftpc.cgi/177113952681/DNLD?instaler%2ejar
And here the Source:
https://www.alumnos.unican.es/cgi-bin/web-ftpc.cgi/177113952681/DNLD?Instaler%2ezip
The main class is instalerImages.Principal
I ve try this :
//Cogemos un fichero del directorio
               File readme=new File(Principal.class.getResource("/instalerImages/images/Readme.txt").getFile());
               System.out.println("File to get the oparent folder "+readme);
               //Creamos un fichero con el directorio de ese fichero
               File directorioAlOverride=(readme.getParentFile());
               //Creamos un filtro para archivos mos y los leemos
               System.out.println("Folder "+directorioAlOverride);
               Filtro mos=new Filtro("mos");
               File[] ficherosMos=directorioAlOverride.listFiles(mos);
               System.out.println("File[] length "+ficherosMos.length);
               //Copiamos los archivos mos al override
               UtilidadesArchivo.copiarArchivosAlOverride(ficherosMos);But don�t work when exporting to a jar., so .. can ayone help??
You're from Universidad de Cantabria? What I coincidence, I'll spend next year there through ERASMUS :)
Unfortunately it's not possible to do what you want, there is no way to create a File object that points to anything inside a .jar file. File objects point to files on the file system and if everything is packed in one .jar file there is only that one .jar file; it's not possible to "see" inside of it with the File class.
It's probably possible to achieve what you want with the JarFile and ZipFile classes somewhat like this:// Find the location of the .jar file where this
URL jarlocation = Principal.class.getProtectionDomain().getCodeSource().getLocation();
// Read the .jar file
JarInputStream in = new JarInputStream(jarlocation.openStream());
// etcetera
JarEntry e = in.getNextJarEntry();
String entryName = e.getName();
if (entry name is accepted) read entry data from "in" and write it somewhere 
Hey, Universidad De Cantabria is a great place, believe me, maybe you study Maths or physics??. i`ve been studing physics til this year.
I`ll try what you say tomorrow, thx a lot. 
Until this year, do you mean you're switching to maths now? I study maths too :)
Which year are you on?
You can find my email address from my user profile. 
It works great, here`s the source :
//Copia los ficheros del tipo dado del interior del jar al override (true,
     // o al directorio
     //raiz del torment false.
     public static void copiarFicheros(String tipoFichero, boolean alOverride)
               throws IOException, FileNotFoundException {
          //No se pueden crear objetos File con un jar, es necesario usar las
          //Herramientas de la clase ZIPFile y JarFile
          //Primero de todo encontramos la ruta donde estar� nuestro
          // ficheroJar
          //Es una URL
          URL rutaDelJar = Principal.class.getProtectionDomain().getCodeSource()
                    .getLocation();
          //Segundo, creamos un JarInputStream paera leer el Jar
          //El metodo openStream de la clase URL abre un inputStream de esa
          // url
          JarInputStream inputDelJar = new JarInputStream(rutaDelJar.openStream());
          //Leemos la entrada del jar que no es otra cosa que uno de los
          // ficheros que hay dentro
          JarEntry fichero = inputDelJar.getNextJarEntry();
          //Mientras la sigueinte entrada exista miarmos si el nombre es el
          // adecuado
          //Y si lo es lo copiamos;
          while (fichero != null) {
               String nombre = fichero.getName();
               String rutaACopiar;
               //Problema, el getName incluye el tema de los directorios, por lo
               // tanto se elimina
               String nombreBien = nombre.substring(4);
               //Si el fichero es del tipo adecuado
               if (nombre.endsWith("." + tipoFichero)) {
                    //Si tenemos que meterlo al override
                    //Creamos el pathname del fichero a copiar al override
                    if (alOverride) {
                         rutaACopiar = new String(rutaPST + "\\override\\"
                                   + nombreBien);
                         //Si va al principal nada m�s
                    } else {
                         rutaACopiar = (rutaPST +"\\"+ nombreBien);
                         //Creamos un FileOutputStream
                    }
                    FileOutputStream ficheroAEscribir = new FileOutputStream(
                              rutaACopiar);
                    BufferedOutputStream rapido = new BufferedOutputStream(
                              ficheroAEscribir);
                    BufferedInputStream leerRapido = new BufferedInputStream(
                              inputDelJar);
                    //Leemos y escribimos el fichero
                    int v;
                    while ((v = leerRapido.read()) != -1) {
                         rapido.write(v);
                    }
                    //Aqui hay que poner lo del log
               }
               //Pasamos al siguiente jarEntry
               fichero = inputDelJar.getNextJarEntry();
          }
     }jslaonen i`ve send you a mail telling something about UC, hope you `ll find it interesting

display not complete of element from XML file

I wrote a program that extract element from file XML, when I want to display the resault I have only two element of descendant of the root element of may file XML .
this is a little part of my file
<RRSet>
- <RR>
<id>1</id>
- <RT>
<numero>1</numero>
<champ>dport</champ>
<valeur>22</valeur>
<AcceptRid>17;18;19;20;21;22;23</AcceptRid>
</RT>
- <RT>
<numero>2</numero>
<champ>dport</champ>
<valeur>80</valeur>
<AcceptRid>31;34;35;36;37</AcceptRid>
</RT>
- <RT>
<numero>3</numero>
<champ>dport</champ>
<valeur>53</valeur>
<AcceptRid>32;33</AcceptRid>
</RT>
- <RT>
<numero>4</numero>
<champ>dport</champ>
<valeur>25</valeur>
<AcceptRid>1</AcceptRid>
</RT>
</RR>
</RRSet>
I used a counter to know the number of RT et it display me 2 or I have more. I don't kow what's the matter
My function is:
static void ExtractionChamps () {
// declararion des elements de la liste
String idRR=null;
String idRT=null;
String champ=null;
String valeur=null;
String ChampAcceptRid=null;
String [] champA=null;
String RT=null;
// On cr�e une instance de SAXBuilder
SAXBuilder sxb = new SAXBuilder();
try
{
//On cr�e un nouveau document JDOM avec en argument le fichier XML
document = sxb.build(new File("RRSet.xml"));
}
catch(Exception e){}
//On initialise un nouvel �l�ment racine avec l'�l�ment racine du document.
racine = document.getRootElement();
//creation des noeuds
List listRR = racine.getChildren("RR");
//On cr�e un Iterator sur notre liste
Iterator i = listRR.iterator();
int compteurRR=0;
//Extraction des champs de l'ensemble RR
while(i.hasNext())
{
// declaration de la liste de Reject Term
ArrayList monArrayListRT = new ArrayList() ;
// un objet qui contient les strucures des Rejected Rules
ChampRR CRR=new ChampRR();
Element courant = (Element)i.next();
//Extraction du premier champ id
idRR=courant.getChild("id").getText();
CRR.id=idRR;
Element racineRT=racine.getChild("RR");
List listRT = racineRT.getChildren("RT");
//On cr�e un Iterator sur notre liste
Iterator j = listRT.iterator();
int compteurRT =0;
while(j.hasNext())
{
ArrayList<String> AcceptidList =new ArrayList<String>();
// un objet qui contient les strucures des Rejected terms RT
ChampEnsemble CE=new ChampEnsemble();
Element courant2 = (Element)j.next();
idRT=courant2.getChild("numero").getText();
champ=courant2.getChild("champ").getText();
valeur=courant2.getChild("valeur").getText();
ChampAcceptRid=courant2.getChild("AcceptRid").getText();
String []ChampA = ChampAcceptRid.split(";");
for (int k=0; k<ChampA.length; k++){
AcceptidList.add(ChampA[k]);
}
CE.initialise(idRT, champ, valeur, AcceptidList);
monArrayListRT.add(CE);
compteurRT++;
}
System.out.println("le nombre de terme � rejetrer = "+compteurRT);
CRR.initialise(idRR, monArrayListRT);
monArrayListRR.add(CRR);
}//fin while
}//fin methode
Thank you 
Welcome to the forum. Many of us find unformatted code hard to read, and so we just won't read it. I suggest that you repost your code, but using code tags so that your code will retain its formatting and be readable. To do this, either use the "code" button at the top of the forum Message editor or place the tag [code] at the top of your block of code and the tag [/code] at the bottom, like so:
[code]
  // your code block goes here.
[/code]good luck, pete 
Thank you
I wrote a program that extract element from file XML, when I want to display the resault I have only two element of descendant of the root element of may file XML .
this is a little part of my file
<RRSet>
- <RR>
<id>1</id>
- <RT>
<numero>1</numero>
<champ>dport</champ>
<valeur>22</valeur>
<AcceptRid>17;18;19;20;21;22;23</AcceptRid>
</RT>
</RR>
- <RR>
<id>2</id>
- <RT>
<numero>1</numero>
<champ>dport</champ>
<valeur>80</valeur>
<AcceptRid>31;34;35;36;37</AcceptRid>
</RT>
- <RT>
<numero>2</numero>
<champ>dport</champ>
<valeur>53</valeur>
<AcceptRid>32;33</AcceptRid>
</RT>
- <RT>
<numero>3</numero>
<champ>dport</champ>
<valeur>25</valeur>
<AcceptRid>1</AcceptRid>
</RT>
</RR>
</RRSet>I used a counter to know the number of RT et it display me 2 or I have more. I don't kow what's the matter
My function is:
static void ExtractionChamps () {
// declararion des elements de la liste
String idRR=null;
String idRT=null;
String champ=null;
String valeur=null;
String ChampAcceptRid=null;
String [] champA=null;
String RT=null;
// On cr�e une instance de SAXBuilder
SAXBuilder sxb = new SAXBuilder();
try
{
//On cr�e un nouveau document JDOM avec en argument le fichier XML
document = sxb.build(new File("RRSet.xml"));
}
catch(Exception e){}
//On initialise un nouvel �l�ment racine avec l'�l�ment racine du document.
racine = document.getRootElement();
//creation des noeuds
List listRR = racine.getChildren("RR");
//On cr�e un Iterator sur notre liste
Iterator i = listRR.iterator();
int compteurRR=0;
//Extraction des champs de l'ensemble RR
while(i.hasNext())
{
// declaration de la liste de Reject Term
ArrayList monArrayListRT = new ArrayList() ;
// un objet qui contient les strucures des Rejected Rules
ChampRR CRR=new ChampRR();
Element courant = (Element)i.next();
//Extraction du premier champ id
idRR=courant.getChild("id").getText();
CRR.id=idRR;
Element racineRT=racine.getChild("RR");
List listRT = racineRT.getChildren("RT");
//On cr�e un Iterator sur notre liste
Iterator j = listRT.iterator();
int compteurRT =0;
while(j.hasNext())
{
ArrayList<String> AcceptidList =new ArrayList<String>();
// un objet qui contient les strucures des Rejected terms RT
ChampEnsemble CE=new ChampEnsemble();
Element courant2 = (Element)j.next();
idRT=courant2.getChild("numero").getText();
champ=courant2.getChild("champ").getText();
valeur=courant2.getChild("valeur").getText();
ChampAcceptRid=courant2.getChild("AcceptRid").getText();
String []ChampA = ChampAcceptRid.split(";");
for (int k=0; k<ChampA.length; k++){
AcceptidList.add(ChampA[k]);
}
CE.initialise(idRT, champ, valeur, AcceptidList);
monArrayListRT.add(CE);
compteurRT++;
}
System.out.println("le nombre de terme � rejetrer = "+compteurRT);
CRR.initialise(idRR, monArrayListRT);
monArrayListRR.add(CRR);
}//fin while
}//fin methodeThank you 
Well, as I read that code it does this:
"For each RR element under the root element, consider the first RR element under the root. Count its RT children and report that number."
So you get 1 RT each time, right?
By the way you will find that code is more readable if it is indented in a logical way. It's not surprising that you're having trouble with it the way it is now.
I expect you wanted your code to do this instead:
"For each RR element under the root element, consider that element. Count its RT children and report that number."

Categories

Resources