├── .gitignore
├── README.md
├── ejemplo-activemq
├── .gitignore
├── pom.xml
└── src
│ └── main
│ └── java
│ └── com
│ └── chuidiang
│ └── ejemplos
│ ├── MainActiveMQConsumer.java
│ ├── MainActiveMQProducer.java
│ ├── MainEmbeddedActiveMQ.java
│ ├── MainRequestResponseActiveMQ.java
│ └── Util.java
├── ejemplo-hibernate-annotations
├── hibernate.cfg.xml
├── pom.xml
└── src
│ └── main
│ ├── java
│ └── com
│ │ └── chuidiang
│ │ └── ejemplos
│ │ └── hibernate_annotations
│ │ ├── Ejemplo1.java
│ │ ├── Flight.java
│ │ └── HibernateUtil.java
│ └── resources
│ └── logback.xml
├── ejemplo-hibernate
├── hibernate1.cfg.xml
├── hibernate2.cfg.xml
├── hibernate3.cfg.xml
├── hibernate4.cfg.xml
├── pom.xml
└── src
│ └── main
│ ├── java
│ └── com
│ │ └── chuidiang
│ │ └── ejemplos
│ │ └── hibernate
│ │ ├── ejemplo1
│ │ ├── Ejemplo1.java
│ │ ├── Event.java
│ │ └── HibernateUtil.java
│ │ ├── ejemplo2
│ │ ├── Ejemplo2.java
│ │ ├── HibernateUtil.java
│ │ └── Person.java
│ │ ├── ejemplo3
│ │ ├── Ejemplo3.java
│ │ ├── HibernateUtil.java
│ │ └── Person.java
│ │ └── ejemplo4
│ │ ├── Ejemplo4.java
│ │ ├── Event.java
│ │ ├── HibernateUtil.java
│ │ └── Person.java
│ └── resources
│ ├── com
│ └── chuidiang
│ │ └── ejemplos
│ │ └── hibernate
│ │ ├── ejemplo1
│ │ └── Event.hbm.xml
│ │ ├── ejemplo2
│ │ └── Person.hbm.xml
│ │ ├── ejemplo3
│ │ └── Person.hbm.xml
│ │ └── ejemplo4
│ │ ├── Event.hbm.xml
│ │ └── Person.hbm.xml
│ └── logback.xml
├── ejemplo-hilos
├── pom.xml
└── src
│ ├── main
│ └── java
│ │ └── com
│ │ └── chuidiang
│ │ └── ejemplos
│ │ ├── App.java
│ │ └── ThreadPoolExecutorExample.java
│ └── test
│ └── java
│ └── com
│ └── chuidiang
│ └── ejemplos
│ └── AppTest.java
├── ejemplo-izpack
├── maven-izpack
│ ├── pom.xml
│ └── src
│ │ ├── izpack
│ │ └── install.xml
│ │ └── main
│ │ └── java
│ │ └── com
│ │ └── chuidiang
│ │ └── App.java
└── standalone-izpack
│ ├── APLICACION
│ ├── bin
│ │ └── un_ejecutable.txt
│ └── doc
│ │ ├── enarameo.txt
│ │ └── undocumento.txt
│ ├── instalacion-userinput.xml
│ ├── instalacion.xml
│ └── userinput.xml
├── ejemplo-jasperreports
├── README.md
├── pom.xml
└── src
│ └── main
│ ├── java
│ └── com
│ │ └── chuidiang
│ │ └── ejemplos
│ │ └── jasper
│ │ ├── Data.java
│ │ ├── GenerateReport.java
│ │ └── TheData.java
│ └── reports
│ └── report1.jrxml
├── ejemplo-jfreechart
├── pom.xml
└── src
│ └── main
│ └── java
│ └── com
│ └── chuidiang
│ └── ejemplos
│ ├── EjemploJFreeBubbleChart.java
│ ├── EjemploJFreeCategoryDataset.java
│ ├── EjemploJFreeChartAreaChart.java
│ ├── EjemploJFreeChartBoxAndWhikerChart.java
│ ├── EjemploJFreeHistogram.java
│ └── EjemploJFreeWindPlot.java
├── ejemplo-jndi
├── pom.xml
└── src
│ └── main
│ └── java
│ └── com
│ └── chuidiang
│ └── ejemplos
│ ├── JndiClient.java
│ ├── JndiServer.java
│ └── SomeData.java
├── ejemplo-jpa
└── ejemplo-jpa
│ ├── pom.xml
│ └── src
│ └── main
│ ├── java
│ └── com
│ │ └── chuidiang
│ │ └── ejemplos
│ │ ├── domain
│ │ └── Employee.java
│ │ └── jpa
│ │ └── JpaTest.java
│ └── resources
│ └── META-INF
│ └── persistence.xml
├── ejemplo-junit
├── pom.xml
└── src
│ ├── main
│ └── java
│ │ └── com
│ │ └── chuidiang
│ │ └── ejemplos
│ │ ├── Resta.java
│ │ ├── Suma.java
│ │ ├── mazacote
│ │ └── ClaseMazacote.java
│ │ └── semi_mazacote
│ │ ├── Calculator.java
│ │ ├── ClaseSemiMazacote.java
│ │ ├── IfzMuestraResultados.java
│ │ ├── IfzScanner.java
│ │ └── Sumador.java
│ └── test
│ └── java
│ └── com
│ └── chuidiang
│ └── ejemplos
│ ├── junit45
│ ├── AllTest.java
│ ├── CalculatorTest.java
│ ├── Main.java
│ ├── TestResta.java
│ └── TestSuma.java
│ └── poco_mazacote
│ ├── MockMuestraResultados.java
│ ├── MockScanner.java
│ └── TestSumador.java
├── ejemplo-modelo-vista-presenter
├── pom.xml
└── src
│ ├── main
│ └── java
│ │ └── com
│ │ └── chuidiang
│ │ └── ejemplos
│ │ └── mvp
│ │ ├── EjemploModeloVistaPresenter.java
│ │ ├── IfzVista.java
│ │ ├── Modelo.java
│ │ ├── Presenter.java
│ │ └── Vista.java
│ └── test
│ └── java
│ └── com
│ └── chuidiang
│ └── ejemplos
│ └── mvp
│ └── TestPresenter.java
├── ejemplo-osgi
├── ejemplo-maven-felix-plugin
│ ├── OSGI-INF
│ │ └── ThePublicInterface.xml
│ ├── pom.xml
│ └── src
│ │ ├── main
│ │ ├── java
│ │ │ └── com
│ │ │ │ └── chuidiang
│ │ │ │ └── ejemplos
│ │ │ │ ├── App.java
│ │ │ │ ├── api
│ │ │ │ └── ThePublicInterface.java
│ │ │ │ └── impl1
│ │ │ │ ├── Activator.java
│ │ │ │ └── TheInterfaceImplementation.java
│ │ └── resources
│ │ │ └── un-recurso.txt
│ │ └── test
│ │ └── java
│ │ └── com
│ │ └── chuidiang
│ │ └── ejemplos
│ │ └── AppTest.java
└── osgi-app
│ ├── com.chuidiang.ejemplos.app_main
│ ├── build.properties
│ ├── osgi.bnd
│ ├── pom.xml
│ └── src
│ │ └── main
│ │ ├── java
│ │ └── com
│ │ │ └── chuidiang
│ │ │ └── ejemplos
│ │ │ └── app_main
│ │ │ ├── ApplicationMain.java
│ │ │ └── internal
│ │ │ ├── BundleAndMap.java
│ │ │ ├── ExampleServiceImpl.java
│ │ │ ├── MainPanel.java
│ │ │ ├── MainWindow.java
│ │ │ └── PluginInstallation.java
│ │ └── resources
│ │ ├── OSGI-INF
│ │ └── component.xml
│ │ └── readme.txt
│ ├── com.chuidiang.ejemplos.plugin1_v1
│ ├── build.properties
│ ├── osgi.bnd
│ ├── pom.xml
│ └── src
│ │ └── main
│ │ ├── java
│ │ └── com
│ │ │ └── chuidiang
│ │ │ └── ejemplos
│ │ │ └── plugin1
│ │ │ └── internal
│ │ │ └── ExampleServiceImpl.java
│ │ └── resources
│ │ ├── OSGI-INF
│ │ └── component.xml
│ │ └── readme.txt
│ ├── com.chuidiang.ejemplos.plugin1_v2
│ ├── build.properties
│ ├── osgi.bnd
│ ├── pom.xml
│ └── src
│ │ └── main
│ │ ├── java
│ │ └── com
│ │ │ └── chuidiang
│ │ │ └── ejemplos
│ │ │ └── plugin1
│ │ │ └── internal
│ │ │ └── ExampleServiceImpl.java
│ │ └── resources
│ │ └── readme.txt
│ ├── com.chuidiang.ejemplos.plugin2
│ ├── build.properties
│ ├── osgi.bnd
│ ├── pom.xml
│ └── src
│ │ └── main
│ │ ├── java
│ │ └── com
│ │ │ └── chuidiang
│ │ │ └── ejemplos
│ │ │ └── plugin2
│ │ │ └── internal
│ │ │ └── ExampleServiceImpl.java
│ │ └── resources
│ │ ├── OSGI-INF
│ │ └── component.xml
│ │ └── readme.txt
│ ├── com.chuidiang.ejemplos.plugin_interface
│ ├── .settings
│ │ └── org.eclipse.jdt.core.prefs
│ ├── build.properties
│ ├── osgi.bnd
│ ├── pom.xml
│ └── src
│ │ └── main
│ │ ├── java
│ │ └── com
│ │ │ └── chuidiang
│ │ │ └── ejemplos
│ │ │ └── plugin_interface
│ │ │ └── PluginInterface.java
│ │ └── resources
│ │ └── readme.txt
│ ├── pom.xml
│ ├── poms
│ ├── compiled
│ │ └── pom.xml
│ ├── pom.xml
│ └── wrappers
│ │ └── pom.xml
│ └── provision
│ └── pom.xml
├── ejemplo-socket-ssl
├── .gitignore
├── pom.xml
└── src
│ ├── main
│ ├── certs
│ │ ├── client
│ │ │ ├── ClientPublicKey.cer
│ │ │ ├── clientKey.jks
│ │ │ └── clientTrustedCerts.jks
│ │ ├── readme.txt
│ │ └── server
│ │ │ ├── ServerPublicKey.cer
│ │ │ ├── serverKey.jks
│ │ │ └── serverTrustedCerts.jks
│ └── java
│ │ └── com
│ │ └── chuidiang
│ │ └── ejemplos
│ │ ├── AppCustom.java
│ │ ├── AppDefault.java
│ │ ├── SSLCustomClient.java
│ │ ├── SSLCustomServer.java
│ │ ├── SSLDefaultClientSocket.java
│ │ ├── SSLDefaultServerSocket.java
│ │ └── Util.java
│ └── test
│ └── java
│ └── com
│ └── chuidiang
│ └── ejemplos
│ └── AppTest.java
├── ejemplo_cxf
├── pom.xml
└── src
│ ├── main
│ ├── java
│ │ └── com
│ │ │ └── chuidiang
│ │ │ └── ejemplos
│ │ │ └── cxf
│ │ │ ├── Calculadora.java
│ │ │ ├── CalculadoraImpl.java
│ │ │ └── Resultado.java
│ └── webapp
│ │ └── WEB-INF
│ │ ├── beans.xml
│ │ └── web.xml
│ └── test
│ └── java
│ └── com
│ └── chuidiang
│ └── ejemplos
│ └── cxf
│ ├── ClienteCalculadora.java
│ └── ServerCalculadora.java
├── ejemplos-android
├── AndroidManifest.xml
├── proguard-project.txt
├── project.properties
├── res
│ ├── drawable-hdpi
│ │ └── ic_launcher.png
│ ├── drawable-ldpi
│ │ └── ic_launcher.png
│ ├── drawable-mdpi
│ │ └── ic_launcher.png
│ ├── drawable-xhdpi
│ │ └── ic_launcher.png
│ ├── layout
│ │ ├── formulario.xml
│ │ └── main.xml
│ └── values
│ │ └── strings.xml
└── src
│ └── com
│ └── chuidiang
│ └── ejemplos
│ └── android
│ ├── AndroidHolaMundoActivity.java
│ └── DialogoFragment.java
├── ejemplos-java-mysql
├── paisaje.jpg
├── pom.xml
└── src
│ ├── main
│ ├── config
│ │ └── datasource_config.properties
│ └── java
│ │ └── com
│ │ └── chuidiang
│ │ └── ejemplos
│ │ ├── backup_mysql
│ │ └── RecuperarBackup.java
│ │ ├── databasemetadata_mysql
│ │ ├── EjemploDataBaseMetaData.java
│ │ └── EjemploResultSetMetaData.java
│ │ ├── datasource_mysql
│ │ ├── EjemploBasicDataSourceFactory.java
│ │ └── EjemploDataSource.java
│ │ ├── mysql
│ │ ├── Conexion.java
│ │ ├── Dato.java
│ │ ├── DatoGrande.java
│ │ ├── ImagenesEnBaseDatos.java
│ │ └── ObjectsEnBaseDatos.java
│ │ └── preparedstatement_mysql
│ │ ├── EjemploPreparedStatement.java
│ │ └── RendimientoPreparedStatement.java
│ └── test
│ └── java
│ └── com
│ └── chuidiang
│ └── AppTest.java
├── ejemplos-jaxb
├── pom.xml
└── src
│ ├── main
│ ├── java
│ │ └── com
│ │ │ └── chuidiang
│ │ │ └── ejemplos
│ │ │ ├── App.java
│ │ │ └── UnaClase.java
│ └── resources
│ │ └── PurchaseOrders.xsd
│ └── test
│ └── java
│ └── com
│ └── chuidiang
│ └── ejemplos
│ └── AppTest.java
├── ejemplos-swing
├── pom.xml
└── src
│ ├── main
│ └── java
│ │ └── com
│ │ └── chuidiang
│ │ └── ejemplos
│ │ ├── option_pane_dialog_modal
│ │ ├── DialogoModal.java
│ │ └── EjemplosJOptionPane.java
│ │ └── swing_worker
│ │ ├── Principal1.java
│ │ ├── Principal2.java
│ │ ├── Worker1.java
│ │ └── Worker2.java
│ └── test
│ └── java
│ └── com
│ └── chuidiang
│ └── ejemplos
│ └── AppTest.java
├── hibernate-herencia
├── pom.xml
└── src
│ └── main
│ ├── java
│ └── com
│ │ └── chuidiang
│ │ └── ejemplos
│ │ ├── HibernateUtil.java
│ │ ├── Hija1.java
│ │ ├── Hija2.java
│ │ ├── MainEjemploTablaPorSubclase.java
│ │ └── Padre.java
│ └── resources
│ ├── com
│ └── chuidiang
│ │ └── ejemplos
│ │ ├── tabla_por_jerarquia
│ │ └── Padre.hbm.xml
│ │ ├── tabla_por_subclase
│ │ └── Padre.hbm.xml
│ │ └── tabla_por_subclase_concreta
│ │ └── Padre.hbm.xml
│ └── hibernate.cfg.xml
├── mbean
└── src
│ └── com
│ └── chuidiang
│ └── ejemplos
│ └── mbean
│ ├── Hello.java
│ ├── HelloMBean.java
│ └── PruebaMBean.java
├── organizador-fotos
├── pom.xml
└── src
│ └── main
│ └── java
│ └── com
│ └── chuidiang
│ └── organizador_fotos
│ ├── MovePhotos.java
│ └── RenamePhotos.java
├── pruebas-geotools
└── src
│ └── com
│ └── chuidiang
│ └── ejemplos
│ └── geotools
│ ├── GeotoolsMain.java
│ ├── MouseWheel.java
│ ├── PanelCapas.java
│ └── SimpleGeotoolsMain.java
├── pruebas-worldwind
└── src
│ ├── com
│ └── chuidiang
│ │ └── ejemplos
│ │ └── worldwind
│ │ ├── DibujaPoligonos.java
│ │ ├── ElPopUp.java
│ │ ├── FicheroTiff.java
│ │ ├── MainWorlWindExample.java
│ │ ├── MiPoligono.java
│ │ ├── ShapeFile.java
│ │ ├── SimbolosAPP6.java
│ │ └── TrazasSensora.java
│ └── org
│ └── chuidiang
│ └── chuwiki
│ └── worldwind
│ ├── CapaIconos.java
│ ├── CapaPoligonos.java
│ ├── CapaWMS.java
│ └── MainMinimo.java
├── python-ejemplos
└── editor.py
├── python-gmail
├── enviar-gmail-compuesto.py
├── enviar-gmail.py
└── lee-gmail.py
├── python-hilos
└── src
│ ├── thread_hilo_lock.py
│ ├── thread_hilo_simple.py
│ ├── threading_hilo_condition.py
│ ├── threading_hilo_event.py
│ ├── threading_hilo_lock.py
│ ├── threading_hilo_rlock.py
│ ├── threading_hilo_semaphore.py
│ └── threading_hilo_simple.py
├── python-socket
└── src
│ ├── cliente.py
│ ├── servidor.py
│ └── servidor_thread.py
└── scala
├── camel-scala
├── pom.xml
└── src
│ ├── main
│ ├── java
│ │ └── com
│ │ │ └── chuidiang
│ │ │ └── ejemplos
│ │ │ └── App.java
│ └── scala
│ │ └── com
│ │ └── chuidiang
│ │ └── ejemplos
│ │ ├── data
│ │ ├── Data.scala
│ │ ├── DataClientSocketExample.scala
│ │ ├── DataDecoder.scala
│ │ ├── DataEncoder.scala
│ │ ├── DataExample.scala
│ │ ├── DataServerSocketExample.scala
│ │ ├── Protocol.scala
│ │ └── Util.scala
│ │ └── string
│ │ ├── CamelExample.scala
│ │ ├── CustomDecoder.scala
│ │ ├── CustomEncoder.scala
│ │ ├── CustomFrameDecoder.scala
│ │ ├── ScalaClientSocketExample.scala
│ │ └── ScalaServerSocketExample.scala
│ └── test
│ └── java
│ └── com
│ └── chuidiang
│ └── ejemplos
│ └── AppTest.java
└── maven-scala
├── pom.xml
└── src
├── main
├── java
│ └── com
│ │ └── chuidiang
│ │ └── ejemplos
│ │ └── App.java
└── scala
│ └── Hello.scala
└── test
├── java
└── com
│ └── chuidiang
│ └── ejemplos
│ └── AppTest.java
└── scala
└── HelloTest.scala
/.gitignore:
--------------------------------------------------------------------------------
1 | target
2 | .classpath
3 | .project
4 | .settings
5 | *~
6 | .cache
7 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # chuidiang-ejemplos-google-code
2 |
3 | Examples of java code and more.
4 |
--------------------------------------------------------------------------------
/ejemplo-activemq/.gitignore:
--------------------------------------------------------------------------------
1 | /target/
2 |
--------------------------------------------------------------------------------
/ejemplo-activemq/pom.xml:
--------------------------------------------------------------------------------
1 |
3 | 4.0.0
4 | com.chuidiang.ejemplos
5 | ejemplo-activemq
6 | 1.0-SNAPSHOT
7 | Ejemplo Active MQ
8 |
9 |
10 |
11 | org.apache.activemq
12 | activemq-client
13 | 5.11.1
14 |
15 |
16 | org.apache.activemq
17 | activemq-broker
18 | 5.11.1
19 |
20 |
21 | org.slf4j
22 | slf4j-log4j12
23 | 1.7.12
24 |
25 |
26 |
--------------------------------------------------------------------------------
/ejemplo-activemq/src/main/java/com/chuidiang/ejemplos/Util.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos;
2 |
3 | import javax.jms.DeliveryMode;
4 | import javax.jms.Destination;
5 | import javax.jms.JMSException;
6 | import javax.jms.MessageConsumer;
7 | import javax.jms.MessageProducer;
8 | import javax.jms.Session;
9 | import javax.jms.TextMessage;
10 |
11 | public class Util {
12 | public static MessageProducer createQueueProducer(Session session, String queue) throws JMSException{
13 | Destination destination = session.createQueue(queue);
14 | MessageProducer producer = session.createProducer(destination);
15 | producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
16 | return producer;
17 | }
18 |
19 | public static MessageProducer createTopicProducer(Session session, String topic) throws JMSException{
20 | Destination destination = session.createTopic(topic);
21 | MessageProducer producer = session.createProducer(destination);
22 | producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
23 | return producer;
24 | }
25 |
26 | public static MessageConsumer createQueueConsumer(Session session, String queue) throws JMSException{
27 | Destination destination = session.createQueue(queue);
28 | MessageConsumer consumer = session.createConsumer(destination);
29 | return consumer;
30 | }
31 |
32 | public static MessageConsumer createTopicConsumer(Session session, String topic) throws JMSException{
33 | Destination destination = session.createTopic(topic);
34 | MessageConsumer consumer = session.createConsumer(destination);
35 | return consumer;
36 | }
37 |
38 | public static void sendText(Session session, MessageProducer pingProducer, String value) throws JMSException {
39 | TextMessage message = session.createTextMessage(value);
40 | pingProducer.send(message);
41 | }
42 |
43 | }
44 |
--------------------------------------------------------------------------------
/ejemplo-hibernate-annotations/hibernate.cfg.xml:
--------------------------------------------------------------------------------
1 |
4 |
5 |
6 |
7 | org.postgresql.Driver
8 | jdbc:postgresql://localhost/chuidiang-examples
9 | postgres
10 | postgres
11 |
12 | 1
13 |
14 |
15 |
16 | thread
17 |
18 | org.hibernate.cache.NoCacheProvider
19 |
20 | true
21 |
22 | create
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/ejemplo-hibernate-annotations/pom.xml:
--------------------------------------------------------------------------------
1 |
3 | 4.0.0
4 | com.chuidiang.ejemplos
5 | ejemplo-hibernate-annotations
6 | jar
7 | 1.0-SNAPSHOT
8 | ejemplo-hibernate-annotations
9 | https://chuidiang.org
10 |
11 | 17
12 | 17
13 |
14 |
15 |
16 | org.hibernate.orm
17 | hibernate-core
18 | 6.3.1.Final
19 |
20 |
21 | org.postgresql
22 | postgresql
23 | 42.6.0
24 |
25 |
26 | ch.qos.logback
27 | logback-classic
28 | 1.4.11
29 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/ejemplo-hibernate-annotations/src/main/java/com/chuidiang/ejemplos/hibernate_annotations/Ejemplo1.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.hibernate_annotations;
2 |
3 | import org.hibernate.Session;
4 |
5 | import java.util.Date;
6 | import java.util.List;
7 |
8 | /**
9 | * Ejemplo sencillo de hibernate usando annotations.
10 | * Se crea una instancia de Fligth, se guarda en base de datos, se consulta y
11 | * muestra por pantalla, se modifica y se vuelve a consultar y mostrar por
12 | * pantalla.
13 | *
14 | * @author Chuidiang
15 | *
16 | */
17 | public class Ejemplo1 {
18 |
19 | public static void main(String[] args) {
20 | new Ejemplo1();
21 | }
22 |
23 | public Ejemplo1() {
24 | // Se inserta
25 | Long id = insertFlight();
26 |
27 | // Se consulta y muestra por pantalla
28 | listFlights();
29 |
30 | // Se modifica
31 | updateFlight(id);
32 |
33 | // Se vuelve a consultar y mostrar por pantalla
34 | listFlights();
35 | }
36 |
37 | private void updateFlight(Long id) {
38 | Session s = HibernateUtil.getSession();
39 | s.beginTransaction();
40 |
41 | Flight vuelo = (Flight) s.load(Flight.class, id);
42 | vuelo.setFirstname("Nombre cambiado");
43 |
44 | s.getTransaction().commit();
45 | }
46 |
47 | private void listFlights() {
48 | Session s = HibernateUtil.getSession();
49 | s.beginTransaction();
50 |
51 | List vuelos = s.createQuery("from Flight").list();
52 | for (Flight vuelo : vuelos)
53 | System.out.println(vuelo.toString());
54 |
55 | s.getTransaction().commit();
56 | }
57 |
58 | private Long insertFlight() {
59 | // Se obtiene la sesion
60 | Session s = HibernateUtil.getSession();
61 | s.beginTransaction();
62 |
63 | // Se instancia la clase Flight y se rellenan sus datos
64 | Flight f = new Flight();
65 | f.setFirstname("Nombre vuelo");
66 | f.setFecha(new Date());
67 |
68 | // Se salva en base de datos
69 | s.save(f);
70 | s.getTransaction().commit();
71 |
72 | return f.getId();
73 | }
74 |
75 | }
76 |
--------------------------------------------------------------------------------
/ejemplo-hibernate-annotations/src/main/java/com/chuidiang/ejemplos/hibernate_annotations/Flight.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.hibernate_annotations;
2 |
3 | import jakarta.persistence.*;
4 |
5 | import java.util.Date;
6 |
7 | /**
8 | * Clase persistente en base de datos con annotations.
9 | *
10 | * @author Chuidiang
11 | */
12 | @Entity
13 | @Table(name = "VUELO")
14 | public class Flight {
15 |
16 | /** El id */
17 | Long id;
18 | private String firstname;
19 | private Date fecha;
20 |
21 | /** Persistente como clave y valor generado por la base de datos */
22 | @Id
23 | @GeneratedValue
24 | public Long getId() {
25 | return id;
26 | }
27 |
28 | private void setId(Long id) {
29 | this.id = id;
30 | }
31 |
32 | /** Persistente, un tipo basico (string) */
33 | @Basic
34 | @Column(name = "NOMBRE")
35 | public String getFirstname() {
36 | return firstname;
37 | }
38 |
39 | public void setFirstname(String firstname) {
40 | this.firstname = firstname;
41 | }
42 |
43 | public String toString() {
44 | return "Vuelo : " + id + " " + getFirstname() + " " + fecha;
45 | }
46 |
47 | /** Una fecha. Debemos indicar si es DATE, TIME o TIMESTAMP */
48 | @Temporal(TemporalType.TIMESTAMP)
49 | public Date getFecha() {
50 | return fecha;
51 | }
52 |
53 | public void setFecha(Date fecha) {
54 | this.fecha = fecha;
55 | }
56 |
57 | }
58 |
--------------------------------------------------------------------------------
/ejemplo-hibernate-annotations/src/main/java/com/chuidiang/ejemplos/hibernate_annotations/HibernateUtil.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.hibernate_annotations;
2 |
3 | import org.hibernate.HibernateException;
4 | import org.hibernate.Session;
5 | import org.hibernate.SessionFactory;
6 | import org.hibernate.cfg.Configuration;
7 |
8 | import java.io.File;
9 |
10 | /**
11 | * Clase de utilidad para obtener la sesion de hibernate.
12 | *
13 | * @author documentacion hibernate
14 | */
15 | public class HibernateUtil {
16 |
17 | private static final SessionFactory sessionFactory;
18 |
19 | static {
20 | try {
21 | // Si no ponemos fichero, intenta cargar "/hibernate.cfg.xml" en el
22 | // raiz
23 | sessionFactory = new Configuration().configure(
24 | new File("hibernate.cfg.xml")).buildSessionFactory();
25 | } catch (Throwable ex) {
26 | // Log exception!
27 | throw new ExceptionInInitializerError(ex);
28 | }
29 | }
30 |
31 | public static Session getSession() throws HibernateException {
32 | return sessionFactory.openSession();
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/ejemplo-hibernate-annotations/src/main/resources/logback.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
6 |
7 | %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} -%kvp- %msg%n
8 |
9 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/ejemplo-hibernate/hibernate1.cfg.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 | org.postgresql.Driver
9 | jdbc:postgresql://localhost/chuidiang-examples
10 | postgres
11 | postgres
12 |
13 | 1
14 |
15 |
16 |
17 | thread
18 |
19 | org.hibernate.cache.NoCacheProvider
20 |
21 | true
22 |
23 | create
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/ejemplo-hibernate/hibernate2.cfg.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 | org.postgresql.Driver
9 | jdbc:postgresql://localhost/chuidiang-examples
10 | postgres
11 | postgres
12 |
13 | 1
14 |
15 |
16 |
17 | thread
18 |
19 | org.hibernate.cache.NoCacheProvider
20 |
21 | true
22 |
23 | create
24 |
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/ejemplo-hibernate/hibernate3.cfg.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 | org.postgresql.Driver
9 | jdbc:postgresql://localhost/chuidiang-examples
10 | postgres
11 | postgres
12 |
13 | 1
14 |
15 |
16 |
17 | thread
18 |
19 | org.hibernate.cache.NoCacheProvider
20 |
21 | true
22 |
23 | create
24 |
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/ejemplo-hibernate/hibernate4.cfg.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 | org.postgresql.Driver
9 | jdbc:postgresql://localhost/chuidiang-examples
10 | postgres
11 | postgres
12 |
13 | 1
14 |
15 |
16 |
17 | thread
18 |
19 | org.hibernate.cache.NoCacheProvider
20 |
21 | true
22 |
23 | create
24 |
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/ejemplo-hibernate/pom.xml:
--------------------------------------------------------------------------------
1 |
3 | 4.0.0
4 | com.chuidiang.ejemplos
5 | ejemplo-hibernate
6 | jar
7 | 1.0-SNAPSHOT
8 | ejemplo-hibernate
9 | http://chuidiang.org
10 |
11 | 17
12 | 17
13 |
14 |
15 |
16 | junit
17 | junit
18 | 4.13.2
19 | test
20 |
21 |
22 | org.hibernate.orm
23 | hibernate-core
24 | 6.3.1.Final
25 |
26 |
27 | org.postgresql
28 | postgresql
29 | 42.6.0
30 |
31 |
32 | ch.qos.logback
33 | logback-classic
34 | 1.4.11
35 |
36 |
37 |
38 |
--------------------------------------------------------------------------------
/ejemplo-hibernate/src/main/java/com/chuidiang/ejemplos/hibernate/ejemplo1/Ejemplo1.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.hibernate.ejemplo1;
2 |
3 | import org.hibernate.Session;
4 |
5 | import java.util.Date;
6 | import java.util.List;
7 |
8 | /**
9 | * Ejemplo sencillo con Hibernate.
10 | * Se crea un Evento y se inserta en base de datos. Luego se hace la consulta y
11 | * se presenta por pantalla.
12 | *
13 | * @author Chuidiang
14 | *
15 | */
16 | public class Ejemplo1 {
17 |
18 | public static void main(String[] args) {
19 | new Ejemplo1();
20 | }
21 |
22 | public Ejemplo1() {
23 | // Se inserta un evento en bd
24 | createAndStoreEvent("El Event", new Date());
25 |
26 | // Se hace la consulta y se lista
27 | listEvents();
28 | HibernateUtil.getSessionFactory().close();
29 | }
30 |
31 | private Long createAndStoreEvent(String title, Date theDate) {
32 | // Obtener session de hibernate y comenzar transaccion
33 | Session session = HibernateUtil.getSessionFactory().getCurrentSession();
34 | session.beginTransaction();
35 |
36 | // Creacion del evento
37 | Event theEvent = new Event();
38 | theEvent.setTitle(title);
39 | theEvent.setDate(theDate);
40 |
41 | // Insercion en base de datos.
42 | session.save(theEvent);
43 | session.getTransaction().commit();
44 | System.out.println("Insertado: " + theEvent);
45 | return theEvent.getId();
46 | }
47 |
48 | private List listEvents() {
49 | // Obtener sesion de hibernate y comenzar transaccion
50 | Session session = HibernateUtil.getSessionFactory().getCurrentSession();
51 | session.beginTransaction();
52 |
53 | // Consulta y mostrar resultados.
54 | List result = (List) session.createQuery("from Event")
55 | .list();
56 | for (Event evento : result) {
57 | System.out.println("Leido: " + evento);
58 | }
59 |
60 | // Cierre de sesion.
61 | session.getTransaction().commit();
62 |
63 | return result;
64 | }
65 |
66 | }
67 |
--------------------------------------------------------------------------------
/ejemplo-hibernate/src/main/java/com/chuidiang/ejemplos/hibernate/ejemplo1/Event.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.hibernate.ejemplo1;
2 |
3 | import java.util.Date;
4 |
5 | /**
6 | * Clase Evento, persistente en base de datos en este ejemplo.
7 | *
8 | * @author Chuidiang
9 | *
10 | */
11 | public class Event {
12 | /** Clave primaria */
13 | private Long id;
14 |
15 | private String title;
16 | private Date date;
17 |
18 | public Event() {
19 | }
20 |
21 | public Long getId() {
22 | return id;
23 | }
24 |
25 | /**
26 | * Metodo setter privado, hibernate es capaz de llamarlo, pero nosostros
27 | * desde codigo no.
28 | *
29 | * @param id
30 | */
31 | private void setId(Long id) {
32 | this.id = id;
33 | }
34 |
35 | public String getTitle() {
36 | return title;
37 | }
38 |
39 | public void setTitle(String title) {
40 | this.title = title;
41 | }
42 |
43 | public Date getDate() {
44 | return date;
45 | }
46 |
47 | public void setDate(Date date) {
48 | this.date = date;
49 | }
50 |
51 | public String toString() {
52 | return "Evento : " + id + " - " + title + " - " + date;
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/ejemplo-hibernate/src/main/java/com/chuidiang/ejemplos/hibernate/ejemplo1/HibernateUtil.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.hibernate.ejemplo1;
2 |
3 | import java.io.File;
4 |
5 | import org.hibernate.SessionFactory;
6 | import org.hibernate.cfg.Configuration;
7 |
8 | public class HibernateUtil {
9 | private static final SessionFactory sessionFactory;
10 | static {
11 | try {
12 | // Create the SessionFactory from hibernate.cfg.xml
13 | sessionFactory = new Configuration().configure(new File("hibernate1.cfg.xml"))
14 | .buildSessionFactory();
15 | } catch (Throwable ex) {
16 | // Make sure you log the exception, as it might be swallowed
17 | System.err.println("Initial SessionFactory creation failed." + ex);
18 | throw new ExceptionInInitializerError(ex);
19 | }
20 | }
21 |
22 | public static SessionFactory getSessionFactory() {
23 | return sessionFactory;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/ejemplo-hibernate/src/main/java/com/chuidiang/ejemplos/hibernate/ejemplo2/HibernateUtil.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.hibernate.ejemplo2;
2 |
3 | import java.io.File;
4 |
5 | import org.hibernate.SessionFactory;
6 | import org.hibernate.cfg.Configuration;
7 |
8 | public class HibernateUtil {
9 | private static final SessionFactory sessionFactory;
10 | static {
11 | try {
12 | // Create the SessionFactory from hibernate.cfg.xml
13 | sessionFactory = new Configuration().configure(
14 | new File("hibernate2.cfg.xml")).buildSessionFactory();
15 | } catch (Throwable ex) {
16 | // Make sure you log the exception, as it might be swallowed
17 | System.err.println("Initial SessionFactory creation failed." + ex);
18 | throw new ExceptionInInitializerError(ex);
19 | }
20 | }
21 |
22 | public static SessionFactory getSessionFactory() {
23 | return sessionFactory;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/ejemplo-hibernate/src/main/java/com/chuidiang/ejemplos/hibernate/ejemplo2/Person.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.hibernate.ejemplo2;
2 |
3 | import java.util.HashSet;
4 | import java.util.Iterator;
5 | import java.util.Set;
6 |
7 | import com.chuidiang.ejemplos.hibernate.ejemplo1.Event;
8 |
9 | /**
10 | * Clase Person, persistente en base de datos en este ejemplo y con varios Event
11 | * asociados.
12 | *
13 | * @author Chuidiang
14 | *
15 | */
16 | public class Person {
17 | /** Clave primaria */
18 | private Long id;
19 | private int age;
20 | private String firstname;
21 | private String lastname;
22 |
23 | public Person() {
24 | }
25 |
26 | public Long getId() {
27 | return id;
28 | }
29 |
30 | private Set events = new HashSet();
31 |
32 | public Set getEvents() {
33 | return events;
34 | }
35 |
36 | public void setEvents(Set events) {
37 | this.events = events;
38 | }
39 |
40 | /** Metodo setter privado, hibernate puede llamarlo, pero nosotros no */
41 | private void setId(Long id) {
42 | this.id = id;
43 | }
44 |
45 | public int getAge() {
46 | return age;
47 | }
48 |
49 | public void setAge(int age) {
50 | this.age = age;
51 | }
52 |
53 | public String getFirstname() {
54 | return firstname;
55 | }
56 |
57 | public void setFirstname(String firstname) {
58 | this.firstname = firstname;
59 | }
60 |
61 | public String getLastname() {
62 | return lastname;
63 | }
64 |
65 | public void setLastname(String lastname) {
66 | this.lastname = lastname;
67 | }
68 |
69 | public String toString() {
70 | StringBuilder sb = new StringBuilder();
71 | sb.append("Persona: " + id + " - " + firstname + " - " + lastname
72 | + " - " + age);
73 | Iterator eventos = getEvents().iterator();
74 | while (eventos.hasNext())
75 | sb.append(System.getProperty("line.separator") + " Evento : "
76 | + eventos.next().toString());
77 | return sb.toString();
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/ejemplo-hibernate/src/main/java/com/chuidiang/ejemplos/hibernate/ejemplo3/HibernateUtil.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.hibernate.ejemplo3;
2 |
3 | import java.io.File;
4 |
5 | import org.hibernate.SessionFactory;
6 | import org.hibernate.cfg.Configuration;
7 |
8 | public class HibernateUtil {
9 | private static final SessionFactory sessionFactory;
10 | static {
11 | try {
12 | // Create the SessionFactory from hibernate.cfg.xml
13 | sessionFactory = new Configuration().configure(
14 | new File("hibernate3.cfg.xml")).buildSessionFactory();
15 | } catch (Throwable ex) {
16 | // Make sure you log the exception, as it might be swallowed
17 | System.err.println("Initial SessionFactory creation failed." + ex);
18 | throw new ExceptionInInitializerError(ex);
19 | }
20 | }
21 |
22 | public static SessionFactory getSessionFactory() {
23 | return sessionFactory;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/ejemplo-hibernate/src/main/java/com/chuidiang/ejemplos/hibernate/ejemplo4/Event.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chuidiang/chuidiang-ejemplos-google-code/7b01f5c0786b5855de0c4c3688b15d3c57914a28/ejemplo-hibernate/src/main/java/com/chuidiang/ejemplos/hibernate/ejemplo4/Event.java
--------------------------------------------------------------------------------
/ejemplo-hibernate/src/main/java/com/chuidiang/ejemplos/hibernate/ejemplo4/HibernateUtil.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.hibernate.ejemplo4;
2 |
3 | import java.io.File;
4 |
5 | import org.hibernate.SessionFactory;
6 | import org.hibernate.cfg.Configuration;
7 |
8 | public class HibernateUtil {
9 | private static final SessionFactory sessionFactory;
10 | static {
11 | try {
12 | // Create the SessionFactory from hibernate.cfg.xml
13 | sessionFactory = new Configuration().configure(
14 | new File("hibernate4.cfg.xml")).buildSessionFactory();
15 | } catch (Throwable ex) {
16 | // Make sure you log the exception, as it might be swallowed
17 | System.err.println("Initial SessionFactory creation failed." + ex);
18 | throw new ExceptionInInitializerError(ex);
19 | }
20 | }
21 |
22 | public static SessionFactory getSessionFactory() {
23 | return sessionFactory;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/ejemplo-hibernate/src/main/resources/com/chuidiang/ejemplos/hibernate/ejemplo1/Event.hbm.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/ejemplo-hibernate/src/main/resources/com/chuidiang/ejemplos/hibernate/ejemplo2/Person.hbm.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/ejemplo-hibernate/src/main/resources/com/chuidiang/ejemplos/hibernate/ejemplo3/Person.hbm.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/ejemplo-hibernate/src/main/resources/com/chuidiang/ejemplos/hibernate/ejemplo4/Event.hbm.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
14 |
15 |
16 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/ejemplo-hibernate/src/main/resources/com/chuidiang/ejemplos/hibernate/ejemplo4/Person.hbm.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/ejemplo-hibernate/src/main/resources/logback.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
6 |
7 | %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} -%kvp- %msg%n
8 |
9 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/ejemplo-hilos/pom.xml:
--------------------------------------------------------------------------------
1 |
3 | 4.0.0
4 | com.chuidiang.ejemplos
5 | ejemplo-hilos
6 | jar
7 | 1.0-SNAPSHOT
8 | ejemplo-hilos
9 | http://maven.apache.org
10 |
11 |
12 | junit
13 | junit
14 | 3.8.1
15 | test
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/ejemplo-hilos/src/main/java/com/chuidiang/ejemplos/App.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos;
2 |
3 | import java.util.concurrent.locks.Lock;
4 | import java.util.concurrent.locks.ReentrantLock;
5 |
6 |
7 | /**
8 | * Hello world!
9 | *
10 | */
11 | public class App
12 | {
13 | public static void main( String[] args )
14 | {
15 | new App().startExample();
16 | }
17 |
18 | private void startExample() {
19 | Object objectForSynchrnize = new Object();
20 |
21 | synchronized (objectForSynchrnize) {
22 | System.out.println("I'm inside a synchronized block");
23 | }
24 |
25 | Lock aLock = new ReentrantLock();
26 |
27 | aLock.lock();
28 |
29 | try {
30 | System.out.println("I'm inside a synchronized block");
31 | } catch (Exception e){
32 | System.err.println("Error! "+e.getMessage());
33 | } finally {
34 | aLock.unlock();
35 | }
36 |
37 | }
38 |
39 |
40 | }
41 |
--------------------------------------------------------------------------------
/ejemplo-hilos/src/test/java/com/chuidiang/ejemplos/AppTest.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos;
2 |
3 | import junit.framework.Test;
4 | import junit.framework.TestCase;
5 | import junit.framework.TestSuite;
6 |
7 | /**
8 | * Unit test for simple App.
9 | */
10 | public class AppTest
11 | extends TestCase
12 | {
13 | /**
14 | * Create the test case
15 | *
16 | * @param testName name of the test case
17 | */
18 | public AppTest( String testName )
19 | {
20 | super( testName );
21 | }
22 |
23 | /**
24 | * @return the suite of tests being tested
25 | */
26 | public static Test suite()
27 | {
28 | return new TestSuite( AppTest.class );
29 | }
30 |
31 | /**
32 | * Rigourous Test :-)
33 | */
34 | public void testApp()
35 | {
36 | assertTrue( true );
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/ejemplo-izpack/maven-izpack/src/izpack/install.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | maven-izapck
4 | 1.0
5 | http://www.chuidiang.com
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 | El ejecutable y sus ficheros
25 |
26 |
27 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/ejemplo-izpack/maven-izpack/src/main/java/com/chuidiang/App.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang;
2 |
3 | /**
4 | * Hello world!
5 | *
6 | */
7 | public class App
8 | {
9 | public static void main( String[] args )
10 | {
11 | System.out.println( "Hello World!" );
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/ejemplo-izpack/standalone-izpack/APLICACION/bin/un_ejecutable.txt:
--------------------------------------------------------------------------------
1 | Soy el ejecutable
2 |
--------------------------------------------------------------------------------
/ejemplo-izpack/standalone-izpack/APLICACION/doc/enarameo.txt:
--------------------------------------------------------------------------------
1 | Esta es la documentacion en arameo
--------------------------------------------------------------------------------
/ejemplo-izpack/standalone-izpack/APLICACION/doc/undocumento.txt:
--------------------------------------------------------------------------------
1 | un documento
2 |
--------------------------------------------------------------------------------
/ejemplo-izpack/standalone-izpack/instalacion-userinput.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | Chuidiang prueba izpack
4 | 1.0
5 | http:www.chuidiang.com
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 | El ejecutable y sus ficheros
31 |
32 |
33 |
34 |
35 |
36 |
37 | La documentacion
38 |
39 |
40 |
41 |
42 |
--------------------------------------------------------------------------------
/ejemplo-izpack/standalone-izpack/instalacion.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | Chuidiang prueba izpack
4 | 1.0
5 | http://www.chuidiang.com
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 | El ejecutable y sus ficheros
26 |
27 |
28 |
29 |
30 |
31 |
32 | La documentacion
33 |
34 |
35 |
36 |
37 |
--------------------------------------------------------------------------------
/ejemplo-izpack/standalone-izpack/userinput.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/ejemplo-jasperreports/README.md:
--------------------------------------------------------------------------------
1 | # Tonterías varías
2 |
3 | El fichero src/main/reports/report1.jrxml se puede editar con iReport designer http://community.jaspersoft.com/project/ireport-designer
4 |
5 | En ese fichero es donde está todo "el truco", porque la parte java es bastante tonta.
6 |
--------------------------------------------------------------------------------
/ejemplo-jasperreports/pom.xml:
--------------------------------------------------------------------------------
1 |
3 | 4.0.0
4 | com.chuidiang.ejemplos
5 | ejemplo-jasperreports
6 | 0.0.1-SNAPSHOT
7 |
8 |
9 | net.sf.jasperreports
10 | jasperreports
11 | 5.6.0
12 | compile
13 |
14 |
15 |
--------------------------------------------------------------------------------
/ejemplo-jasperreports/src/main/java/com/chuidiang/ejemplos/jasper/Data.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.jasper;
2 |
3 | import java.util.Collection;
4 | import java.util.LinkedList;
5 | import java.util.List;
6 |
7 | public class Data {
8 | public static Collection createBeanCollection() {
9 | List result = new LinkedList();
10 | result.add(new TheData(1,"uno"));
11 | result.add(new TheData(2,"dos"));
12 | result.add(new TheData(3,"tres"));
13 | result.add(new TheData(4,"cuatro"));
14 | result.add(new TheData(5,"cinco"));
15 | result.add(new TheData(6,"seis"));
16 | return result;
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/ejemplo-jasperreports/src/main/java/com/chuidiang/ejemplos/jasper/GenerateReport.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.jasper;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 |
6 | import net.sf.jasperreports.engine.JasperCompileManager;
7 | import net.sf.jasperreports.engine.JasperExportManager;
8 | import net.sf.jasperreports.engine.JasperFillManager;
9 | import net.sf.jasperreports.engine.JasperPrint;
10 | import net.sf.jasperreports.engine.JasperReport;
11 | import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
12 | import net.sf.jasperreports.engine.design.JasperDesign;
13 | import net.sf.jasperreports.engine.xml.JRXmlLoader;
14 | import net.sf.jasperreports.view.JasperViewer;
15 |
16 | public class GenerateReport {
17 |
18 | public static void main(String[] str)
19 | {
20 | try
21 | {
22 | JasperReport jasperReport = null;
23 | JasperPrint jasperPrint = null;
24 | JasperDesign jasperDesign = null;
25 | Map parameters = new HashMap();
26 | jasperDesign = JRXmlLoader.load("src/main/reports/report1.jrxml");
27 | jasperReport = JasperCompileManager.compileReport(jasperDesign);
28 | jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, new JRBeanCollectionDataSource(Data.createBeanCollection()));
29 | JasperExportManager.exportReportToPdfFile(jasperPrint,"target/StudentInfo.pdf");
30 | JasperViewer.viewReport(jasperPrint);
31 | }
32 | catch(Exception ex)
33 | {
34 | System.out.println("EXCEPTION: "+ex);
35 | }
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/ejemplo-jasperreports/src/main/java/com/chuidiang/ejemplos/jasper/TheData.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.jasper;
2 |
3 | public class TheData {
4 | public TheData() {
5 | }
6 | public TheData(int aNumber, String aString) {
7 | this.aNumber = aNumber;
8 | this.aString = aString;
9 | }
10 | private int aNumber;
11 | public int getaNumber() {
12 | return aNumber;
13 | }
14 | public void setaNumber(int aNumber) {
15 | this.aNumber = aNumber;
16 | }
17 | public String getaString() {
18 | return aString;
19 | }
20 | public void setaString(String aString) {
21 | this.aString = aString;
22 | }
23 | private String aString;
24 | }
25 |
--------------------------------------------------------------------------------
/ejemplo-jfreechart/pom.xml:
--------------------------------------------------------------------------------
1 |
3 | 4.0.0
4 | com.chuidiang.ejemplos
5 | ejemplo-jfreechart
6 | jar
7 | 1.0-SNAPSHOT
8 | ejemplo-jfreechart
9 | http://www.chuidiang.com
10 |
11 |
12 | jfree
13 | jfreechart
14 | 1.0.9
15 | compile
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/ejemplo-jfreechart/src/main/java/com/chuidiang/ejemplos/EjemploJFreeBubbleChart.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chuidiang/chuidiang-ejemplos-google-code/7b01f5c0786b5855de0c4c3688b15d3c57914a28/ejemplo-jfreechart/src/main/java/com/chuidiang/ejemplos/EjemploJFreeBubbleChart.java
--------------------------------------------------------------------------------
/ejemplo-jfreechart/src/main/java/com/chuidiang/ejemplos/EjemploJFreeCategoryDataset.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chuidiang/chuidiang-ejemplos-google-code/7b01f5c0786b5855de0c4c3688b15d3c57914a28/ejemplo-jfreechart/src/main/java/com/chuidiang/ejemplos/EjemploJFreeCategoryDataset.java
--------------------------------------------------------------------------------
/ejemplo-jfreechart/src/main/java/com/chuidiang/ejemplos/EjemploJFreeChartAreaChart.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chuidiang/chuidiang-ejemplos-google-code/7b01f5c0786b5855de0c4c3688b15d3c57914a28/ejemplo-jfreechart/src/main/java/com/chuidiang/ejemplos/EjemploJFreeChartAreaChart.java
--------------------------------------------------------------------------------
/ejemplo-jfreechart/src/main/java/com/chuidiang/ejemplos/EjemploJFreeChartBoxAndWhikerChart.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chuidiang/chuidiang-ejemplos-google-code/7b01f5c0786b5855de0c4c3688b15d3c57914a28/ejemplo-jfreechart/src/main/java/com/chuidiang/ejemplos/EjemploJFreeChartBoxAndWhikerChart.java
--------------------------------------------------------------------------------
/ejemplo-jfreechart/src/main/java/com/chuidiang/ejemplos/EjemploJFreeHistogram.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chuidiang/chuidiang-ejemplos-google-code/7b01f5c0786b5855de0c4c3688b15d3c57914a28/ejemplo-jfreechart/src/main/java/com/chuidiang/ejemplos/EjemploJFreeHistogram.java
--------------------------------------------------------------------------------
/ejemplo-jfreechart/src/main/java/com/chuidiang/ejemplos/EjemploJFreeWindPlot.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chuidiang/chuidiang-ejemplos-google-code/7b01f5c0786b5855de0c4c3688b15d3c57914a28/ejemplo-jfreechart/src/main/java/com/chuidiang/ejemplos/EjemploJFreeWindPlot.java
--------------------------------------------------------------------------------
/ejemplo-jndi/pom.xml:
--------------------------------------------------------------------------------
1 |
3 | 4.0.0
4 | com.chuidiang.ejemplos
5 | ejemplo-jndi
6 | 0.0.1-SNAPSHOT
7 |
8 |
9 | jboss
10 | jnpserver
11 | 4.2.2.GA
12 |
13 |
14 | jboss
15 | jbossall-client
16 | 4.2.2.GA
17 |
18 |
19 |
--------------------------------------------------------------------------------
/ejemplo-jndi/src/main/java/com/chuidiang/ejemplos/JndiClient.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos;
2 |
3 | import java.util.Hashtable;
4 |
5 | import javax.naming.Context;
6 | import javax.naming.InitialContext;
7 | import javax.naming.NamingException;
8 |
9 | public class JndiClient {
10 |
11 | public static void main(String[] args) throws NamingException {
12 | final Hashtable env = new Hashtable();
13 |
14 | env.put(Context.INITIAL_CONTEXT_FACTORY,
15 | "org.jnp.interfaces.NamingContextFactory");
16 | env.put(Context.PROVIDER_URL, "jnp://192.168.1.2:5400");
17 |
18 | Context context = new InitialContext(env);
19 |
20 | System.out.println("Application name = "
21 | + context.lookup("java:/config/applicationName"));
22 | System.out.println("someData = " + context.lookup("java:/config/clase"));
23 |
24 | }
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/ejemplo-jndi/src/main/java/com/chuidiang/ejemplos/JndiServer.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos;
2 |
3 | import java.net.InetAddress;
4 | import java.net.UnknownHostException;
5 | import java.util.Date;
6 | import java.util.Hashtable;
7 |
8 | import javax.naming.Context;
9 | import javax.naming.InitialContext;
10 | import javax.naming.NamingException;
11 |
12 | import org.jnp.server.Main;
13 | import org.jnp.server.NamingBeanImpl;
14 |
15 | public class JndiServer {
16 |
17 | public static void main(String[] args) throws Exception {
18 | startServer();
19 | storeSomeData();
20 | System.out.println("Ready");
21 | }
22 |
23 | private static void storeSomeData() throws NamingException {
24 | Hashtable env = new Hashtable();
25 | env.put(Context.INITIAL_CONTEXT_FACTORY,"org.jnp.interfaces.NamingContextFactory");
26 | env.put(Context.PROVIDER_URL, "jnp://192.168.1.2:5400");
27 | Context context = new InitialContext(env);
28 | context.createSubcontext("config");
29 | context.bind("/config/applicationName", "MyApp");
30 | context.bind("/config/clase", new SomeData("pedro",4,new Date()));
31 | }
32 |
33 | private static void startServer() throws Exception, UnknownHostException {
34 | System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
35 |
36 | NamingBeanImpl jnpServer = new NamingBeanImpl();
37 | jnpServer.start();
38 |
39 | Main main = new Main();
40 | main.setNamingInfo(jnpServer);
41 | main.setPort(5400);
42 | main.setBindAddress(InetAddress.getLocalHost().getHostName());
43 | main.start();
44 | }
45 |
46 | }
47 |
--------------------------------------------------------------------------------
/ejemplo-jndi/src/main/java/com/chuidiang/ejemplos/SomeData.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos;
2 |
3 | import java.io.Serializable;
4 | import java.util.Date;
5 |
6 | public class SomeData implements Serializable {
7 | private static final long serialVersionUID = 7137987108991450388L;
8 | private String aString;
9 | private int aInteger;
10 | private Date aDate;
11 |
12 | public SomeData(String aString, int aInteger, Date aDate) {
13 | this.aString = aString;
14 | this.aDate = aDate;
15 | this.aInteger = aInteger;
16 | }
17 |
18 | @Override
19 | public String toString() {
20 | return "SomeData [aString=" + aString + ", aInteger=" + aInteger
21 | + ", aDate=" + aDate + "]";
22 | }
23 |
24 | public String getaString() {
25 | return aString;
26 | }
27 |
28 | public void setaString(String aString) {
29 | this.aString = aString;
30 | }
31 |
32 | public int getaInteger() {
33 | return aInteger;
34 | }
35 |
36 | public void setaInteger(int aInteger) {
37 | this.aInteger = aInteger;
38 | }
39 |
40 | public Date getaDate() {
41 | return aDate;
42 | }
43 |
44 | public void setaDate(Date aDate) {
45 | this.aDate = aDate;
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/ejemplo-jpa/ejemplo-jpa/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 | com.chuidiang.ejemplos
6 | ejemplo-jpa
7 | 0.0.1-SNAPSHOT
8 |
9 |
10 | EclipseLink Repo
11 | http://download.eclipse.org/rt/eclipselink/maven.repo
12 | EclipseLink Repo
13 |
14 |
15 |
16 |
17 | org.apache.derby
18 | derby
19 | 10.8.2.2
20 |
21 |
22 | org.hibernate
23 | hibernate-entitymanager
24 | 5.0.3.Final
25 |
26 |
27 | org.eclipse.persistence
28 | eclipselink
29 | 2.2.1
30 |
31 |
32 | org.eclipse.persistence
33 | javax.persistence
34 | 2.1.0
35 |
36 |
37 |
38 |
--------------------------------------------------------------------------------
/ejemplo-jpa/ejemplo-jpa/src/main/java/com/chuidiang/ejemplos/domain/Employee.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.domain;
2 |
3 | import javax.persistence.Entity;
4 | import javax.persistence.GeneratedValue;
5 | import javax.persistence.Id;
6 |
7 | @Entity
8 | public class Employee {
9 | @Id
10 | @GeneratedValue
11 | private Long id;
12 |
13 |
14 | private String name;
15 |
16 | public Employee() {}
17 |
18 | public Employee(String name) {
19 | this.name = name;
20 | }
21 |
22 | public Long getId() {
23 | return id;
24 | }
25 |
26 | public void setId(Long id) {
27 | this.id = id;
28 | }
29 |
30 | public String getName() {
31 | return name;
32 | }
33 |
34 | public void setName(String name) {
35 | this.name = name;
36 | }
37 |
38 | @Override
39 | public String toString() {
40 | return "Employee [id=" + id + ", name=" + name + "]";
41 | }
42 |
43 | }
44 |
--------------------------------------------------------------------------------
/ejemplo-junit/pom.xml:
--------------------------------------------------------------------------------
1 |
3 | 4.0.0
4 | com.chuidiang.ejemplos
5 | ejemplo-junit
6 | jar
7 | 1.0-SNAPSHOT
8 | ejemplo-junit
9 | https://chuidiang.org
10 |
11 | UTF-8
12 |
13 |
14 |
15 | junit
16 | junit
17 | 4.13.2
18 | test
19 |
20 |
21 |
22 |
23 |
24 |
25 | org.apache.maven.plugins
26 | maven-surefire-plugin
27 | 3.2.2
28 |
29 |
30 |
31 |
32 |
33 | org.apache.maven.plugins
34 | maven-compiler-plugin
35 |
36 | 11
37 | 11
38 |
39 |
40 |
41 | org.jacoco
42 | jacoco-maven-plugin
43 | 0.8.11
44 |
45 |
46 |
47 | prepare-agent
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
--------------------------------------------------------------------------------
/ejemplo-junit/src/main/java/com/chuidiang/ejemplos/Resta.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos;
2 |
3 | /**
4 | * Clase tonta para hacer con ella test de junit
5 | *
6 | * @author Chuidiang
7 | *
8 | */
9 | public class Resta {
10 | public double decrementa(double a) {
11 | return a - 1;
12 | }
13 |
14 | public double getDiferencia(double a, double b) {
15 | return a - b;
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/ejemplo-junit/src/main/java/com/chuidiang/ejemplos/Suma.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos;
2 |
3 | /**
4 | * Clase tonta para poder hacer test de junit con ella
5 | *
6 | * @author Chuidiang
7 | */
8 | public class Suma {
9 | public double getSuma(double a, double b) {
10 | // Se multiplica en vez de sumar a posta, para que los test fallen
11 | return a * b;
12 | }
13 |
14 | public double incrementa(double a) {
15 | return a + 1;
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/ejemplo-junit/src/main/java/com/chuidiang/ejemplos/mazacote/ClaseMazacote.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.mazacote;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * Ejemplo de clase mazacote, dificil de testear. Lo hace todo ella sola y las
7 | * entradas/salidas no son facilmente accesibles.
8 | *
9 | * @author Chuidiang
10 | */
11 | public class ClaseMazacote {
12 |
13 | /**
14 | * Se le pasa un texto a mostrar en pantalla y un scanner para leer la
15 | * entrada, devuelve un double recogido de dicha entrada. Desgraciadamente,
16 | * el metodo es private, por lo que no se puede testear.
17 | *
18 | * @param scanner
19 | * @param textoPeticion
20 | * @return
21 | */
22 | private static double getSumando(Scanner scanner, String textoPeticion) {
23 | boolean correcto;
24 | correcto = false;
25 | double sumando2 = 0;
26 | while (!correcto) {
27 | try {
28 | System.out.println(textoPeticion);
29 | sumando2 = Double.parseDouble(scanner.nextLine());
30 | correcto = true;
31 | } catch (Exception e) {
32 | System.err.println("Eso no vale");
33 | }
34 | }
35 | return sumando2;
36 | }
37 |
38 | /**
39 | * Pide dos sumandos y muestra la suma
40 | *
41 | * @param args
42 | */
43 | public static void main(String[] args) {
44 | Scanner scanner = new Scanner(System.in);
45 | double sumando1 = getSumando(scanner, "Sumando 1:");
46 | double sumando2 = getSumando(scanner, "Sumando 2:");
47 | System.out.println("" + sumando1 + "+" + sumando2 + "="
48 | + (sumando1 + sumando2));
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/ejemplo-junit/src/main/java/com/chuidiang/ejemplos/semi_mazacote/Calculator.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.semi_mazacote;
2 |
3 | /**
4 | * @author Chuidiang
5 | * @date 10/11/2023
6 | */
7 | public class Calculator {
8 | public static int add(int a, int b){
9 | return a+b;
10 | }
11 |
12 | public static int substract (int a, int b){
13 | return a-b;
14 | }
15 |
16 | public static int divide (int a, int b) {
17 | return a/b;
18 | }
19 |
20 | public static int multiply (int a, int b){
21 | return a*b;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/ejemplo-junit/src/main/java/com/chuidiang/ejemplos/semi_mazacote/ClaseSemiMazacote.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.semi_mazacote;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * Main de ejemplo de una clase menos mazacote, m�s f�cil de testear. En vez de
7 | * leer directamnte de teclado y escribir de pantalla, lee de una interface y
8 | * escribe en una interface
9 | *
10 | * @author Chuidiang
11 | */
12 |
13 | public class ClaseSemiMazacote {
14 |
15 | /**
16 | * Instancia la clase Sumador, le facilita implementaciones de las
17 | * interfaces, y la pone a trabajar.
18 | *
19 | * @param args
20 | */
21 | public static void main(String[] args) {
22 |
23 | // Implementacion de IfzScanner, que lee de teclado.
24 | IfzScanner unScanner = new IfzScanner() {
25 | private final Scanner scanner = new Scanner(System.in);
26 |
27 | public String nextLine() {
28 | return scanner.nextLine();
29 | }
30 |
31 | };
32 |
33 | // Implementacion de IfzMuestraResultados, que escribe en pantalla
34 | IfzMuestraResultados muestraResultados = new IfzMuestraResultados() {
35 | public void println(String textoPeticion) {
36 | System.out.println(textoPeticion);
37 | }
38 | };
39 |
40 | // Se crea Sumador y se inicializa.
41 | Sumador sumador = new Sumador();
42 | sumador.setIfzScanner(unScanner);
43 | sumador.setIfzMuestraResultados(muestraResultados);
44 |
45 | // Se le pone a trabajar.
46 | sumador.empiezaATrabajar();
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/ejemplo-junit/src/main/java/com/chuidiang/ejemplos/semi_mazacote/IfzMuestraResultados.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.semi_mazacote;
2 |
3 | /**
4 | * Interface que deben implementar las clases capaces de mostrar resultados por
5 | * algún sitio, como pantalla.
6 | *
7 | * @author Chuidiang
8 | *
9 | */
10 | public interface IfzMuestraResultados {
11 | /** Muestra en algún sitio el String que se le pasa */
12 | void println(String textoPeticion);
13 | }
14 |
--------------------------------------------------------------------------------
/ejemplo-junit/src/main/java/com/chuidiang/ejemplos/semi_mazacote/IfzScanner.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.semi_mazacote;
2 |
3 | /**
4 | * Interface que debe implementar cualquier clase capaz de leer cadenas de texto
5 | * de algún sitio, como teclado
6 | *
7 | * @author Chuidiang
8 | *
9 | */
10 | public interface IfzScanner {
11 | /** Devuelve la siguiente línea */
12 | String nextLine();
13 |
14 | }
15 |
--------------------------------------------------------------------------------
/ejemplo-junit/src/main/java/com/chuidiang/ejemplos/semi_mazacote/Sumador.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.semi_mazacote;
2 |
3 | /**
4 | * Clase encargada de hacer las sumas. Recibe una interface de la que leer
5 | * líneas de texto con los números que debe sumar, hace la suma, y muestra el
6 | * resultado a través de otra interface.
7 | *
8 | * @author Chuidiang
9 | *
10 | */
11 | public class Sumador {
12 | /** Sitio del que leer las l�neas de entrada */
13 | private IfzScanner scanner;
14 |
15 | /** Sitio por el que mostrar los resultados */
16 | private IfzMuestraResultados muestraResultados;
17 |
18 | /**
19 | * Lee los sumandos, realiza la suma, y la muestra, siempre usando las
20 | * interfaces
21 | */
22 | public void empiezaATrabajar() {
23 | double sumando1 = getSumando("Sumando 1:");
24 | double sumando2 = getSumando("Sumando 2:");
25 | muestraResultados.println("" + sumando1 + "+" + sumando2 + "="
26 | + (sumando1 + sumando2));
27 | }
28 |
29 | /**
30 | * Lectura de una linea de IfzScanner e intento de convertira a double,
31 | * repitiendo hasta que la operaci�n tiene �xito.
32 | *
33 | * @param textoPeticion
34 | * @return El double leído
35 | */
36 | private double getSumando(String textoPeticion) {
37 | boolean correcto;
38 | correcto = false;
39 | double sumando2 = 0;
40 | while (!correcto) {
41 | try {
42 | muestraResultados.println(textoPeticion);
43 | sumando2 = Double.parseDouble(scanner.nextLine());
44 | correcto = true;
45 | } catch (Exception e) {
46 | System.err.println("Eso no vale");
47 | }
48 | }
49 | return sumando2;
50 | }
51 |
52 | /** Se le pasa por donde mostrar los resultdos */
53 | public void setIfzMuestraResultados(IfzMuestraResultados muestraResultados) {
54 | this.muestraResultados = muestraResultados;
55 | }
56 |
57 | /** Se le pasa de dónde leer las entradas */
58 | public void setIfzScanner(IfzScanner scanner) {
59 | this.scanner = scanner;
60 | }
61 |
62 | }
63 |
--------------------------------------------------------------------------------
/ejemplo-junit/src/test/java/com/chuidiang/ejemplos/junit45/AllTest.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.junit45;
2 |
3 | import org.junit.runner.RunWith;
4 | import org.junit.runners.Suite;
5 |
6 | /**
7 | * Ejemplo de TestSuite en junit 4.5
8 | *
9 | * Basta hacer una clase cualquiera, aunque no tenga codigo, como esta, con dos
10 | * anotcaciones.
11 | *
12 | * @RunWith(Suite.class) para indicar que esta clase debe ejecutarse como una
13 | * Suite de test de Junit
14 | *
15 | * @SuiteClasses( { TestResta.class, TestSuma.class }) con todas las clases de
16 | * test que queremos que se ejecuten.
17 | *
18 | * @author Chuidiang
19 | *
20 | */
21 | @RunWith(Suite.class)
22 | @Suite.SuiteClasses( { TestResta.class, TestSuma.class })
23 | public class AllTest {
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/ejemplo-junit/src/test/java/com/chuidiang/ejemplos/junit45/CalculatorTest.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.junit45;
2 |
3 | import com.chuidiang.ejemplos.semi_mazacote.Calculator;
4 | import org.junit.Assert;
5 | import org.junit.Test;
6 |
7 | /**
8 | * @author Chuidiang
9 | * @date 10/11/2023
10 | */
11 | public class CalculatorTest {
12 | @Test
13 | public void mustAdd (){
14 | Assert.assertEquals("Add test", 4, Calculator.add(2,2));
15 | }
16 |
17 | @Test
18 | public void mustSubstract(){
19 | Assert.assertEquals("Substract test", 3, Calculator.substract(6,3));
20 | }
21 |
22 | @Test
23 | public void mustMultiply(){
24 | Assert.assertEquals("Multiply test", 6, Calculator.multiply(2,3));
25 | }
26 |
27 | @Test
28 | public void mustDivide(){
29 | Assert.assertEquals("Divide test", 3, Calculator.divide(6,2));
30 | }
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/ejemplo-junit/src/test/java/com/chuidiang/ejemplos/junit45/Main.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.junit45;
2 |
3 | import org.junit.runner.JUnitCore;
4 |
5 | /**
6 | * Ejemplo de como se arranca una suite de test. Desde linea de comando, con el
7 | * classpath configurado, se haria
8 | *
9 | * Con el classpath adecuado
10 | *
11 | * set CLASSPATH=path/junit.jar;path/mi.jar
12 | *
13 | * se ejecuta con
14 | *
15 | * java org.junit.runner.JUnitCore com.chuidiang.ejemplos.junit45.AllTest
16 | *
17 | * @author Chuidiang
18 | */
19 | public class Main {
20 | public static void main(String[] args) {
21 | JUnitCore.main("com.chuidiang.ejemplos.junit45.AllTest");
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/ejemplo-junit/src/test/java/com/chuidiang/ejemplos/junit45/TestResta.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.junit45;
2 |
3 | import com.chuidiang.ejemplos.Resta;
4 | import org.junit.After;
5 | import org.junit.Before;
6 | import org.junit.Test;
7 |
8 | import static org.junit.Assert.assertEquals;
9 |
10 | /**
11 | * Una clase de tests con junit 4.5 El metodo que queramos que se ejecute antes
12 | * de hacer el test, debemos anotarlo con @Before. El que queramos que se
13 | * ejecute despues de los test debemos anotarlo con @After. Los metodos de test
14 | * con @Test. Para poder usar los metodos assert, debemos hacer un
15 | *
16 | * import static org.junit.Assert.*;
17 | *
18 | * @author Chuidiang
19 | */
20 | public class TestResta {
21 | private Resta resta;
22 |
23 | @Test
24 | public void aVerSiDecrementaBien() {
25 | assertEquals("Test decrementa", 1.0, resta.decrementa(2.0), 1e-6);
26 | }
27 |
28 | @Test
29 | public void aVerSiRestaBien() {
30 | assertEquals("Test resta", 1.0, resta.getDiferencia(2.0, 1.0), 1e-6);
31 | }
32 |
33 | @Before
34 | public void paraEjecutarAntes() throws Exception {
35 | resta = new Resta();
36 | }
37 |
38 | @After
39 | public void paraEjecutarDespues() throws Exception {
40 | // Liberar recursos
41 | }
42 |
43 | }
44 |
--------------------------------------------------------------------------------
/ejemplo-junit/src/test/java/com/chuidiang/ejemplos/junit45/TestSuma.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.junit45;
2 |
3 | import com.chuidiang.ejemplos.Suma;
4 | import org.junit.*;
5 |
6 | /**
7 | * Una clase de tests con junit 4.5 El metodo que queramos que se ejecute antes
8 | * de hacer el test, debemos anotarlo con @Before. El que queramos que se
9 | * ejecute despues de los test debemos anotarlo con @After. Los metodos de test
10 | * con @Test. Para poder usar los metodos assert, debemos hacer un
11 | *
12 | * import static org.junit.Assert.*;
13 | *
14 | * @author Chuidiang
15 | */
16 | public class TestSuma {
17 |
18 | private Suma suma;
19 |
20 | @Test
21 | public void aVerSiIncrementaBien() {
22 | Assert.assertEquals("Test incrementa", 2.0, suma.incrementa(1.0), 1e-6);
23 | }
24 |
25 | @Test
26 | @Ignore // este test falla a posta
27 | public void aVerSiSumaBien() {
28 | Assert.assertEquals("Test suma", 2.0, suma.getSuma(1.0, 1.0), 1e-6);
29 | }
30 |
31 | @Before
32 | public void paraEjecutarAntes() throws Exception {
33 | suma = new Suma();
34 | }
35 |
36 | @After
37 | public void paraEjecutarDespues() throws Exception {
38 | // Fin de test. Aqui liberar recursos o borrar rastros del test
39 | }
40 |
41 | }
42 |
--------------------------------------------------------------------------------
/ejemplo-junit/src/test/java/com/chuidiang/ejemplos/poco_mazacote/MockMuestraResultados.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.poco_mazacote;
2 |
3 | import com.chuidiang.ejemplos.semi_mazacote.IfzMuestraResultados;
4 |
5 | import static org.junit.Assert.assertEquals;
6 |
7 | /**
8 | * Una IfzMuestraResultados específica para test. En este test específico sabe
9 | * qué debe mostrar la clase Sumador, así que simplemente va comprobando que lo
10 | * que muestra la clase Sumador es lo esperado.
11 | *
12 | * @author Chuidiang
13 | *
14 | */
15 | public class MockMuestraResultados implements IfzMuestraResultados {
16 |
17 | /** Para saber por qué texto del array vamos */
18 | private int contador = 0;
19 |
20 | /** Textos que esperamos recibir */
21 | private final String[] textosEsperados = { "Sumando 1:", "Sumando 2:",
22 | "1.0+2.0=3.0" };
23 |
24 | /** Devuelve el número de textos recibidos */
25 | public int getContador() {
26 | return contador;
27 | }
28 |
29 | /** Comprueba que el texto recibido coincide con el esperado */
30 | public void println(String textoRecibido) {
31 | assertEquals(textosEsperados[contador++], textoRecibido);
32 | }
33 |
34 | }
35 |
--------------------------------------------------------------------------------
/ejemplo-junit/src/test/java/com/chuidiang/ejemplos/poco_mazacote/MockScanner.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.poco_mazacote;
2 |
3 | import com.chuidiang.ejemplos.semi_mazacote.IfzScanner;
4 |
5 | /**
6 | * Implmentacion de IfzScanner específica para este test. Las lineas devueltas
7 | * son "1" y "2".
8 | *
9 | * @author Chuidiang
10 | *
11 | */
12 | public class MockScanner implements IfzScanner {
13 |
14 | /** Lineas que debe ir devolviendo */
15 | private final String[] lineas = { "1", "2" };
16 |
17 | /** Numero de lineas devueltas */
18 | private int contador = 0;
19 |
20 | /** Devuelve el número de líneas devueltas */
21 | public int getContador() {
22 | return contador;
23 | }
24 |
25 | /** Devuelve la siguiente linea que toca */
26 | public String nextLine() {
27 | return lineas[contador++];
28 | }
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/ejemplo-junit/src/test/java/com/chuidiang/ejemplos/poco_mazacote/TestSumador.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.poco_mazacote;
2 |
3 | import com.chuidiang.ejemplos.semi_mazacote.Sumador;
4 | import org.junit.Before;
5 | import org.junit.Test;
6 |
7 | import static org.junit.Assert.assertEquals;
8 |
9 | /**
10 | * Test de prueba de la clase Sumador
11 | *
12 | * @author Chuidiang
13 | *
14 | */
15 | public class TestSumador {
16 |
17 | /** Clase a probar */
18 | private Sumador sumador;
19 |
20 | /** scanner específico para el test */
21 | private MockScanner scanner;
22 |
23 | /** MuestraResultados específico para el test */
24 | private MockMuestraResultados muestraResultados;
25 |
26 | /**
27 | * Crea el Sumador, los dos Mock e inicializa sumador.
28 | */
29 | @Before
30 | public void inicializacion() {
31 | sumador = new Sumador();
32 | scanner = new MockScanner();
33 | muestraResultados = new MockMuestraResultados();
34 |
35 | sumador.setIfzScanner(scanner);
36 | sumador.setIfzMuestraResultados(muestraResultados);
37 |
38 | }
39 |
40 | /**
41 | * Comprueba que Sumador suma bien.
42 | */
43 | @Test
44 | public final void testEmpiezaATrabajar() {
45 | sumador.empiezaATrabajar();
46 |
47 | // Se comprueba que se han leido las dos lineas del scanner
48 | assertEquals(2, scanner.getContador());
49 |
50 | // Se comprueba que han salido tres lineas por pantalla: para pedir los
51 | // dos sumadores y el resultado.
52 | assertEquals(3, muestraResultados.getContador());
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/ejemplo-modelo-vista-presenter/pom.xml:
--------------------------------------------------------------------------------
1 |
3 | 4.0.0
4 | com.chuidiang
5 | ejemplo-modelo-vista-presenter
6 | jar
7 | 1.0-SNAPSHOT
8 | ejemplo-modelo-vista-presenter
9 | http://www.chuidiang.com
10 |
11 |
12 | junit
13 | junit
14 | 3.8.1
15 | test
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/ejemplo-modelo-vista-presenter/src/main/java/com/chuidiang/ejemplos/mvp/EjemploModeloVistaPresenter.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chuidiang/chuidiang-ejemplos-google-code/7b01f5c0786b5855de0c4c3688b15d3c57914a28/ejemplo-modelo-vista-presenter/src/main/java/com/chuidiang/ejemplos/mvp/EjemploModeloVistaPresenter.java
--------------------------------------------------------------------------------
/ejemplo-modelo-vista-presenter/src/main/java/com/chuidiang/ejemplos/mvp/IfzVista.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chuidiang/chuidiang-ejemplos-google-code/7b01f5c0786b5855de0c4c3688b15d3c57914a28/ejemplo-modelo-vista-presenter/src/main/java/com/chuidiang/ejemplos/mvp/IfzVista.java
--------------------------------------------------------------------------------
/ejemplo-modelo-vista-presenter/src/main/java/com/chuidiang/ejemplos/mvp/Modelo.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.mvp;
2 |
3 | /**
4 | * Clase de Modelo para el ejemplo Modelo-Vista-Presenter.
5 | * Es una clase sencilla para el ejemplo y sabe que numeros son pares o impares.
6 | *
7 | * @author Chuidiang
8 | */
9 | public class Modelo {
10 | /** Tipo pares */
11 | public static final String PARES = "pares";
12 |
13 | /** Tipo impares */
14 | public static final String IMPARES = "impares";
15 |
16 | /** Posibles valores pares */
17 | private static final int[] pares = { 2, 4, 6 };
18 |
19 | /** Posibles valores impares */
20 | private static final int[] impares = { 1, 3, 5 };
21 |
22 | /**
23 | * Devuelve los posibles valores segun el tipo que se le pase.
24 | *
25 | * @param tipo
26 | * PARES o IMPARES
27 | * @return array de valores pares o impares. null si no el tipo no es PARES
28 | * o IMPARES
29 | */
30 | public int[] getPosiblesValores(String tipo) {
31 | if (PARES.equals(tipo))
32 | return pares;
33 | if (IMPARES.equals(tipo))
34 | return impares;
35 | return null;
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/ejemplo-modelo-vista-presenter/src/main/java/com/chuidiang/ejemplos/mvp/Vista.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chuidiang/chuidiang-ejemplos-google-code/7b01f5c0786b5855de0c4c3688b15d3c57914a28/ejemplo-modelo-vista-presenter/src/main/java/com/chuidiang/ejemplos/mvp/Vista.java
--------------------------------------------------------------------------------
/ejemplo-osgi/ejemplo-maven-felix-plugin/OSGI-INF/ThePublicInterface.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/ejemplo-osgi/ejemplo-maven-felix-plugin/src/main/java/com/chuidiang/ejemplos/App.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos;
2 |
3 | /**
4 | * Hello world!
5 | *
6 | */
7 | public class App
8 | {
9 | public static void main( String[] args )
10 | {
11 | System.out.println( "Hello World!" );
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/ejemplo-osgi/ejemplo-maven-felix-plugin/src/main/java/com/chuidiang/ejemplos/api/ThePublicInterface.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.api;
2 |
3 | public interface ThePublicInterface {
4 | void someMethod();
5 | }
6 |
--------------------------------------------------------------------------------
/ejemplo-osgi/ejemplo-maven-felix-plugin/src/main/java/com/chuidiang/ejemplos/impl1/Activator.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.impl1;
2 |
3 | import org.osgi.framework.BundleActivator;
4 | import org.osgi.framework.BundleContext;
5 |
6 |
7 | public class Activator implements BundleActivator {
8 | @Override
9 | public void start(BundleContext bc){
10 | System.out.println("Activator Starting ...");
11 | }
12 |
13 | @Override
14 | public void stop(BundleContext bc) {
15 | System.out.println("Activator Stopping ...");
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/ejemplo-osgi/ejemplo-maven-felix-plugin/src/main/java/com/chuidiang/ejemplos/impl1/TheInterfaceImplementation.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.impl1;
2 |
3 | import org.apache.log4j.BasicConfigurator;
4 | import org.apache.log4j.Logger;
5 |
6 | import com.chuidiang.ejemplos.api.ThePublicInterface;
7 |
8 | public class TheInterfaceImplementation implements ThePublicInterface{
9 |
10 | @Override
11 | public void someMethod() {
12 | System.out.println("Doing some method");
13 | Logger.getLogger(TheInterfaceImplementation.class).info("Reported by log4j");
14 | }
15 |
16 | public void start() {
17 | BasicConfigurator.configure();
18 | someMethod();
19 | }
20 |
21 | public void stop() {
22 | System.out.println("stopping...");
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/ejemplo-osgi/ejemplo-maven-felix-plugin/src/main/resources/un-recurso.txt:
--------------------------------------------------------------------------------
1 | Esto es un fichero de recurso
2 |
--------------------------------------------------------------------------------
/ejemplo-osgi/ejemplo-maven-felix-plugin/src/test/java/com/chuidiang/ejemplos/AppTest.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos;
2 |
3 | import junit.framework.Test;
4 | import junit.framework.TestCase;
5 | import junit.framework.TestSuite;
6 |
7 | /**
8 | * Unit test for simple App.
9 | */
10 | public class AppTest
11 | extends TestCase
12 | {
13 | /**
14 | * Create the test case
15 | *
16 | * @param testName name of the test case
17 | */
18 | public AppTest( String testName )
19 | {
20 | super( testName );
21 | }
22 |
23 | /**
24 | * @return the suite of tests being tested
25 | */
26 | public static Test suite()
27 | {
28 | return new TestSuite( AppTest.class );
29 | }
30 |
31 | /**
32 | * Rigourous Test :-)
33 | */
34 | public void testApp()
35 | {
36 | assertTrue( true );
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/ejemplo-osgi/osgi-app/com.chuidiang.ejemplos.app_main/build.properties:
--------------------------------------------------------------------------------
1 | source.. = src/main/java/,src/main/resources/
2 | output.. = target/classes/
3 | bin.includes = META-INF/,\
4 | .,\
5 | OSGI-INF/
6 |
--------------------------------------------------------------------------------
/ejemplo-osgi/osgi-app/com.chuidiang.ejemplos.app_main/osgi.bnd:
--------------------------------------------------------------------------------
1 | #-----------------------------------------------------------------
2 | # Use this file to add customized Bnd instructions for the bundle
3 | #-----------------------------------------------------------------
4 |
5 | Service-Component: OSGI-INF/component.xml
6 | Import-Package: com.chuidiang.ejemplos.plugin_interface;version="1.0.0.SNAPSHOT",\
7 | javax.swing,org.osgi.framework
8 |
9 |
--------------------------------------------------------------------------------
/ejemplo-osgi/osgi-app/com.chuidiang.ejemplos.app_main/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | ../poms/compiled/
6 | com.chuidiang.ejemplos.osgi-app.build
7 | compiled-bundle-settings
8 | 1.0-SNAPSHOT
9 |
10 |
11 |
12 | com.chuidiang.ejemplos.app_main
13 | com.chuidiang.ejemplos.app_main
14 |
15 |
16 | 4.0.0
17 | com.chuidiang.ejemplos.osgi-app
18 | com.chuidiang.ejemplos.app_main
19 | 1.0-SNAPSHOT
20 |
21 | ${bundle.symbolicName}
22 |
23 | bundle
24 |
25 |
26 |
34 |
35 | org.osgi
36 | osgi_R4_core
37 | true
38 |
39 |
40 | org.osgi
41 | osgi_R4_compendium
42 | true
43 |
44 |
45 | com.chuidiang.ejemplos.osgi-app
46 | com.chuidiang.ejemplos.plugin_interface
47 | 1.0-SNAPSHOT
48 |
49 |
50 |
51 |
--------------------------------------------------------------------------------
/ejemplo-osgi/osgi-app/com.chuidiang.ejemplos.app_main/src/main/java/com/chuidiang/ejemplos/app_main/ApplicationMain.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.app_main;
2 |
3 | import java.util.Map;
4 |
5 | import com.chuidiang.ejemplos.plugin_interface.PluginInterface;
6 |
7 | /**
8 | * Public API representing an example OSGi service
9 | */
10 | public interface ApplicationMain
11 | {
12 | void addPlugin(PluginInterface plugin, Map properties);
13 | void removePlugin(PluginInterface plugin, Map properties);
14 | }
15 |
16 |
--------------------------------------------------------------------------------
/ejemplo-osgi/osgi-app/com.chuidiang.ejemplos.app_main/src/main/java/com/chuidiang/ejemplos/app_main/internal/BundleAndMap.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.app_main.internal;
2 |
3 | import java.util.Map;
4 |
5 | import com.chuidiang.ejemplos.plugin_interface.PluginInterface;
6 |
7 | public class BundleAndMap {
8 | public BundleAndMap(PluginInterface pluginInterface, Map pluginProperties){
9 | this.plugin = pluginInterface;
10 | this.pluginProperties = pluginProperties;
11 | }
12 | public PluginInterface plugin;
13 | public Map pluginProperties;
14 | }
15 |
--------------------------------------------------------------------------------
/ejemplo-osgi/osgi-app/com.chuidiang.ejemplos.app_main/src/main/java/com/chuidiang/ejemplos/app_main/internal/PluginInstallation.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.app_main.internal;
2 |
3 | public interface PluginInstallation {
4 | long installPlugin(String path);
5 |
6 | void uninstall(long bundleId);
7 | }
8 |
--------------------------------------------------------------------------------
/ejemplo-osgi/osgi-app/com.chuidiang.ejemplos.app_main/src/main/resources/OSGI-INF/component.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
7 |
--------------------------------------------------------------------------------
/ejemplo-osgi/osgi-app/com.chuidiang.ejemplos.app_main/src/main/resources/readme.txt:
--------------------------------------------------------------------------------
1 | Bundle resources go here
2 |
--------------------------------------------------------------------------------
/ejemplo-osgi/osgi-app/com.chuidiang.ejemplos.plugin1_v1/build.properties:
--------------------------------------------------------------------------------
1 | source.. = src/main/java/,src/main/resources/
2 | output.. = target/classes/
3 | bin.includes = META-INF/,.,target/pax-eclipse/
4 |
--------------------------------------------------------------------------------
/ejemplo-osgi/osgi-app/com.chuidiang.ejemplos.plugin1_v1/osgi.bnd:
--------------------------------------------------------------------------------
1 | #-----------------------------------------------------------------
2 | # Use this file to add customized Bnd instructions for the bundle
3 | #-----------------------------------------------------------------
4 |
5 | Import-Package: com.chuidiang.ejemplos.plugin_interface;version="1.0-SNAPSHOT",\
6 | org.osgi.framework,javax.swing
7 | Service-Component: OSGI-INF/component.xml
8 |
9 |
--------------------------------------------------------------------------------
/ejemplo-osgi/osgi-app/com.chuidiang.ejemplos.plugin1_v1/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 | ../poms/compiled/
8 | com.chuidiang.ejemplos.osgi-app.build
9 | compiled-bundle-settings
10 | 1.0-SNAPSHOT
11 |
12 |
13 |
14 | com.chuidiang.ejemplos.plugin1
15 | com.chuidiang.ejemplos.plugin1
16 |
17 |
18 | 4.0.0
19 | com.chuidiang.ejemplos.osgi-app
20 | com.chuidiang.ejemplos.plugin1
21 | 1.0-SNAPSHOT
22 |
23 | ${bundle.symbolicName}
24 |
25 | bundle
26 |
27 |
28 |
31 |
32 | org.osgi
33 | osgi_R4_core
34 | true
35 |
36 |
37 | org.osgi
38 | osgi_R4_compendium
39 | true
40 |
41 |
42 | com.chuidiang.ejemplos.osgi-app
43 | com.chuidiang.ejemplos.plugin_interface
44 | 1.0-SNAPSHOT
45 |
46 |
47 |
48 |
49 |
50 |
--------------------------------------------------------------------------------
/ejemplo-osgi/osgi-app/com.chuidiang.ejemplos.plugin1_v1/src/main/java/com/chuidiang/ejemplos/plugin1/internal/ExampleServiceImpl.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.plugin1.internal;
2 |
3 | import java.awt.Component;
4 | import java.awt.FlowLayout;
5 | import java.awt.event.ActionEvent;
6 | import java.awt.event.ActionListener;
7 |
8 | import javax.swing.JButton;
9 | import javax.swing.JLabel;
10 | import javax.swing.JPanel;
11 |
12 | import com.chuidiang.ejemplos.plugin_interface.PluginInterface;
13 |
14 | /**
15 | * Internal implementation of our example OSGi service
16 | */
17 | public final class ExampleServiceImpl implements PluginInterface {
18 |
19 | private JPanel panel;
20 | private JButton button;
21 | private JLabel label;
22 | private int counter=0;
23 | public void start() {
24 |
25 | System.out.println("plugin1 v1 starting");
26 | panel = new JPanel(new FlowLayout());
27 | button = new JButton("Click me");
28 | panel.add(button);
29 | label = new JLabel(Integer.toString(counter));
30 | panel.add(label);
31 | button.addActionListener(new ActionListener() {
32 |
33 | @Override
34 | public void actionPerformed(ActionEvent arg0) {
35 | counter++;
36 | label.setText(Integer.toString(counter));
37 |
38 | }
39 | });
40 | }
41 |
42 | public void stop() {
43 | System.out.println("plugin1 v1 stoping");
44 | }
45 |
46 | @Override
47 | public String getName() {
48 | // TODO Auto-generated method stub
49 | return "I'm plugin1, version 1";
50 | }
51 |
52 | @Override
53 | public Component getComponent() {
54 | return panel;
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/ejemplo-osgi/osgi-app/com.chuidiang.ejemplos.plugin1_v1/src/main/resources/OSGI-INF/component.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/ejemplo-osgi/osgi-app/com.chuidiang.ejemplos.plugin1_v1/src/main/resources/readme.txt:
--------------------------------------------------------------------------------
1 | Bundle resources go here
2 |
--------------------------------------------------------------------------------
/ejemplo-osgi/osgi-app/com.chuidiang.ejemplos.plugin1_v2/build.properties:
--------------------------------------------------------------------------------
1 | source.. = src/main/java/,src/main/resources/
2 | output.. = target/classes/
3 | bin.includes = META-INF/,.,target/pax-eclipse/
4 |
--------------------------------------------------------------------------------
/ejemplo-osgi/osgi-app/com.chuidiang.ejemplos.plugin1_v2/osgi.bnd:
--------------------------------------------------------------------------------
1 | #-----------------------------------------------------------------
2 | # Use this file to add customized Bnd instructions for the bundle
3 | #-----------------------------------------------------------------
4 |
5 | Import-Package: com.chuidiang.ejemplos.plugin_interface;version="1.0-SNAPSHOT",\
6 | org.osgi.framework,javax.swing
7 | Service-Component: OSGI-INF/component.xml
8 |
--------------------------------------------------------------------------------
/ejemplo-osgi/osgi-app/com.chuidiang.ejemplos.plugin1_v2/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 | ../poms/compiled/
8 | com.chuidiang.ejemplos.osgi-app.build
9 | compiled-bundle-settings
10 | 1.0-SNAPSHOT
11 |
12 |
13 |
14 | com.chuidiang.ejemplos.plugin1
15 | com.chuidiang.ejemplos.plugin1
16 |
17 |
18 | 4.0.0
19 | com.chuidiang.ejemplos.osgi-app
20 | com.chuidiang.ejemplos.plugin1
21 | 2.0-SNAPSHOT
22 |
23 | ${bundle.symbolicName}
24 |
25 | bundle
26 |
27 |
28 |
31 |
32 | org.osgi
33 | osgi_R4_core
34 | true
35 |
36 |
37 | org.osgi
38 | osgi_R4_compendium
39 | true
40 |
41 |
42 | com.chuidiang.ejemplos.osgi-app
43 | com.chuidiang.ejemplos.plugin_interface
44 | 1.0-SNAPSHOT
45 |
46 |
47 |
48 |
49 |
50 |
--------------------------------------------------------------------------------
/ejemplo-osgi/osgi-app/com.chuidiang.ejemplos.plugin1_v2/src/main/java/com/chuidiang/ejemplos/plugin1/internal/ExampleServiceImpl.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.plugin1.internal;
2 |
3 | import java.awt.Component;
4 | import java.awt.FlowLayout;
5 | import java.awt.event.ActionEvent;
6 | import java.awt.event.ActionListener;
7 |
8 | import javax.swing.JButton;
9 | import javax.swing.JLabel;
10 | import javax.swing.JPanel;
11 |
12 | import com.chuidiang.ejemplos.plugin_interface.PluginInterface;
13 |
14 | /**
15 | * Internal implementation of our example OSGi service
16 | */
17 | public final class ExampleServiceImpl
18 | implements PluginInterface
19 | {
20 | private JPanel panel;
21 | private JButton button;
22 | private JLabel label;
23 | private int counter=0;
24 | public void start() {
25 |
26 | System.out.println("plugin1 v2 starting");
27 | panel = new JPanel(new FlowLayout());
28 | button = new JButton("Click me");
29 | panel.add(button);
30 | label = new JLabel(Integer.toString(counter));
31 | panel.add(label);
32 | button.addActionListener(new ActionListener() {
33 |
34 | @Override
35 | public void actionPerformed(ActionEvent arg0) {
36 | counter++;
37 | counter++; // v2 increments twice.
38 | label.setText(Integer.toString(counter));
39 |
40 | }
41 | });
42 | }
43 |
44 | public void stop() {
45 | System.out.println("plugin1 v2 stopping");
46 | }
47 |
48 | @Override
49 | public String getName() {
50 | return "I'm plugin1, version 2";
51 | }
52 |
53 | @Override
54 | public Component getComponent() {
55 | return panel;
56 | }
57 | }
58 |
59 |
--------------------------------------------------------------------------------
/ejemplo-osgi/osgi-app/com.chuidiang.ejemplos.plugin1_v2/src/main/resources/readme.txt:
--------------------------------------------------------------------------------
1 | Bundle resources go here
2 |
--------------------------------------------------------------------------------
/ejemplo-osgi/osgi-app/com.chuidiang.ejemplos.plugin2/build.properties:
--------------------------------------------------------------------------------
1 | source.. = src/main/java/,src/main/resources/
2 | output.. = target/classes/
3 | bin.includes = META-INF/,.,target/pax-eclipse/
4 |
--------------------------------------------------------------------------------
/ejemplo-osgi/osgi-app/com.chuidiang.ejemplos.plugin2/osgi.bnd:
--------------------------------------------------------------------------------
1 | #-----------------------------------------------------------------
2 | # Use this file to add customized Bnd instructions for the bundle
3 | #-----------------------------------------------------------------
4 |
5 | Import-Package: com.chuidiang.ejemplos.plugin_interface;version="1.0-SNAPSHOT",\
6 | org.osgi.framework,javax.swing
7 | Service-Component: OSGI-INF/component.xml
8 |
9 |
--------------------------------------------------------------------------------
/ejemplo-osgi/osgi-app/com.chuidiang.ejemplos.plugin2/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 | ../poms/compiled/
8 | com.chuidiang.ejemplos.osgi-app.build
9 | compiled-bundle-settings
10 | 1.0-SNAPSHOT
11 |
12 |
13 |
14 | com.chuidiang.ejemplos.plugin2
15 | com.chuidiang.ejemplos.plugin2
16 |
17 |
18 | 4.0.0
19 | com.chuidiang.ejemplos.osgi-app
20 | com.chuidiang.ejemplos.plugin2
21 | 1.0-SNAPSHOT
22 |
23 | ${bundle.symbolicName}
24 |
25 | bundle
26 |
27 |
28 |
31 |
32 | org.osgi
33 | osgi_R4_core
34 | true
35 |
36 |
37 | org.osgi
38 | osgi_R4_compendium
39 | true
40 |
41 |
42 | com.chuidiang.ejemplos.osgi-app
43 | com.chuidiang.ejemplos.plugin_interface
44 | 1.0-SNAPSHOT
45 |
46 |
47 |
48 |
49 |
--------------------------------------------------------------------------------
/ejemplo-osgi/osgi-app/com.chuidiang.ejemplos.plugin2/src/main/java/com/chuidiang/ejemplos/plugin2/internal/ExampleServiceImpl.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.plugin2.internal;
2 |
3 | import java.awt.Component;
4 | import java.awt.FlowLayout;
5 | import java.awt.event.ActionEvent;
6 | import java.awt.event.ActionListener;
7 |
8 | import javax.swing.JButton;
9 | import javax.swing.JPanel;
10 | import javax.swing.JTextField;
11 |
12 | import com.chuidiang.ejemplos.plugin_interface.PluginInterface;
13 |
14 | /**
15 | * Internal implementation of our example OSGi service
16 | */
17 | public final class ExampleServiceImpl
18 | implements PluginInterface
19 | {
20 |
21 | private JPanel panel;
22 | private JTextField operand1;
23 | private JTextField operand2;
24 | private JButton addButton;
25 | private JTextField result;
26 |
27 | public void stop(){
28 |
29 | }
30 |
31 | public void start() {
32 | panel = new JPanel(new FlowLayout());
33 | operand1 = new JTextField(5);
34 | operand2 = new JTextField(5);
35 | addButton = new JButton("+");
36 | result = new JTextField(5);
37 | panel.add(operand1);
38 | panel.add(operand2);
39 | panel.add(addButton);
40 | panel.add(result);
41 |
42 | addButton.addActionListener(new ActionListener() {
43 |
44 | @Override
45 | public void actionPerformed(ActionEvent arg0) {
46 | try {
47 | int value1 = Integer.parseInt(operand1.getText());
48 | int value2 = Integer.parseInt(operand2.getText());
49 | result.setText(Integer.toString(value1+value2));
50 | } catch (Exception e){
51 | System.err.println("Some input is wrong");
52 | }
53 |
54 | }
55 | });
56 | }
57 |
58 | @Override
59 | public String getName() {
60 | return "plugin2";
61 | }
62 |
63 | @Override
64 | public Component getComponent() {
65 | return panel;
66 | }
67 | }
68 |
69 |
--------------------------------------------------------------------------------
/ejemplo-osgi/osgi-app/com.chuidiang.ejemplos.plugin2/src/main/resources/OSGI-INF/component.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/ejemplo-osgi/osgi-app/com.chuidiang.ejemplos.plugin2/src/main/resources/readme.txt:
--------------------------------------------------------------------------------
1 | Bundle resources go here
2 |
--------------------------------------------------------------------------------
/ejemplo-osgi/osgi-app/com.chuidiang.ejemplos.plugin_interface/.settings/org.eclipse.jdt.core.prefs:
--------------------------------------------------------------------------------
1 | #Sat Oct 25 12:11:13 CEST 2014
2 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7
3 | eclipse.preferences.version=1
4 | org.eclipse.jdt.core.compiler.source=1.7
5 | org.eclipse.jdt.core.compiler.compliance=1.7
6 |
--------------------------------------------------------------------------------
/ejemplo-osgi/osgi-app/com.chuidiang.ejemplos.plugin_interface/build.properties:
--------------------------------------------------------------------------------
1 | source.. = src/main/java/,src/main/resources/
2 | output.. = target/classes/
3 | bin.includes = META-INF/,.
4 |
--------------------------------------------------------------------------------
/ejemplo-osgi/osgi-app/com.chuidiang.ejemplos.plugin_interface/osgi.bnd:
--------------------------------------------------------------------------------
1 | #-----------------------------------------------------------------
2 | # Use this file to add customized Bnd instructions for the bundle
3 | #-----------------------------------------------------------------
4 |
5 |
6 |
--------------------------------------------------------------------------------
/ejemplo-osgi/osgi-app/com.chuidiang.ejemplos.plugin_interface/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | ../poms/compiled/
6 | com.chuidiang.ejemplos.osgi-app.build
7 | compiled-bundle-settings
8 | 1.0-SNAPSHOT
9 |
10 |
11 |
12 | com.chuidiang.ejemplos.plugin_interface
13 | com.chuidiang.ejemplos.plugin_interface
14 |
15 |
16 | 4.0.0
17 | com.chuidiang.ejemplos.osgi-app
18 | com.chuidiang.ejemplos.plugin_interface
19 | 1.0-SNAPSHOT
20 |
21 | ${bundle.symbolicName}
22 |
23 | bundle
24 |
25 |
26 |
35 |
36 | org.osgi
37 | osgi_R4_core
38 | true
39 |
40 |
41 | org.osgi
42 | osgi_R4_compendium
43 | true
44 |
45 |
46 |
47 |
--------------------------------------------------------------------------------
/ejemplo-osgi/osgi-app/com.chuidiang.ejemplos.plugin_interface/src/main/java/com/chuidiang/ejemplos/plugin_interface/PluginInterface.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.plugin_interface;
2 |
3 | import java.awt.Component;
4 |
5 | /**
6 | * Public API representing an example OSGi service
7 | */
8 | public interface PluginInterface
9 | {
10 | String getName();
11 |
12 | Component getComponent();
13 | }
14 |
15 |
--------------------------------------------------------------------------------
/ejemplo-osgi/osgi-app/com.chuidiang.ejemplos.plugin_interface/src/main/resources/readme.txt:
--------------------------------------------------------------------------------
1 | Bundle resources go here
2 |
--------------------------------------------------------------------------------
/ejemplo-osgi/osgi-app/poms/wrappers/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 | com.chuidiang.ejemplos.osgi-app.build
7 | shared-plugin-settings
8 | 1.0-SNAPSHOT
9 |
10 |
11 | 4.0.0
12 | wrapper-bundle-settings
13 |
14 | osgi-app - wrapper instructions
15 |
16 |
19 |
20 |
21 | Simple OSGi wrapper around third-party jar(s)
22 |
23 |
24 |
25 |
26 |
27 | pom
28 |
29 |
30 |
31 |
32 |
35 | org.apache.felix
36 | maven-bundle-plugin
37 |
38 |
39 | ${bundle.symbolicName}
40 | ${wrapped.version}
41 |
44 | <_exportcontents>*
45 | !*
46 |
49 | <_include>-osgi.bnd
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
--------------------------------------------------------------------------------
/ejemplo-osgi/osgi-app/provision/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 | com.chuidiang.ejemplos
7 | osgi-app
8 | 1.0-SNAPSHOT
9 |
10 |
11 | 4.0.0
12 | com.chuidiang.ejemplos.osgi-app.build
13 | provision
14 |
15 | osgi-app - imported bundles
16 |
17 | pom
18 |
19 |
24 |
25 |
26 | org.apache.felix
27 | org.apache.felix.scr
28 | 1.8.2
29 |
30 |
31 |
32 |
33 |
--------------------------------------------------------------------------------
/ejemplo-socket-ssl/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 | .classpath
3 | .project
4 | .settings
5 | *~
6 |
--------------------------------------------------------------------------------
/ejemplo-socket-ssl/pom.xml:
--------------------------------------------------------------------------------
1 |
3 | 4.0.0
4 |
5 | com.chuidiang.ejemplos
6 | ejemplo-socket-ssl
7 | 1.0-SNAPSHOT
8 | jar
9 |
10 | ejemplo-socket-ssl
11 | http://maven.apache.org
12 |
13 |
14 | UTF-8
15 |
16 |
17 |
18 |
19 | junit
20 | junit
21 | 3.8.1
22 | test
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/ejemplo-socket-ssl/src/main/certs/client/ClientPublicKey.cer:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chuidiang/chuidiang-ejemplos-google-code/7b01f5c0786b5855de0c4c3688b15d3c57914a28/ejemplo-socket-ssl/src/main/certs/client/ClientPublicKey.cer
--------------------------------------------------------------------------------
/ejemplo-socket-ssl/src/main/certs/client/clientKey.jks:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chuidiang/chuidiang-ejemplos-google-code/7b01f5c0786b5855de0c4c3688b15d3c57914a28/ejemplo-socket-ssl/src/main/certs/client/clientKey.jks
--------------------------------------------------------------------------------
/ejemplo-socket-ssl/src/main/certs/client/clientTrustedCerts.jks:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chuidiang/chuidiang-ejemplos-google-code/7b01f5c0786b5855de0c4c3688b15d3c57914a28/ejemplo-socket-ssl/src/main/certs/client/clientTrustedCerts.jks
--------------------------------------------------------------------------------
/ejemplo-socket-ssl/src/main/certs/server/ServerPublicKey.cer:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chuidiang/chuidiang-ejemplos-google-code/7b01f5c0786b5855de0c4c3688b15d3c57914a28/ejemplo-socket-ssl/src/main/certs/server/ServerPublicKey.cer
--------------------------------------------------------------------------------
/ejemplo-socket-ssl/src/main/certs/server/serverKey.jks:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chuidiang/chuidiang-ejemplos-google-code/7b01f5c0786b5855de0c4c3688b15d3c57914a28/ejemplo-socket-ssl/src/main/certs/server/serverKey.jks
--------------------------------------------------------------------------------
/ejemplo-socket-ssl/src/main/certs/server/serverTrustedCerts.jks:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chuidiang/chuidiang-ejemplos-google-code/7b01f5c0786b5855de0c4c3688b15d3c57914a28/ejemplo-socket-ssl/src/main/certs/server/serverTrustedCerts.jks
--------------------------------------------------------------------------------
/ejemplo-socket-ssl/src/main/java/com/chuidiang/ejemplos/AppCustom.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos;
2 |
3 |
4 | /**
5 | * Example with SSL sockets using system properties.
6 | */
7 | public class AppCustom {
8 | public static void main(String[] args) throws Exception {
9 | new SSLCustomServer(5557).start();
10 |
11 | new SSLCustomClient("localhost",5557).start();
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/ejemplo-socket-ssl/src/main/java/com/chuidiang/ejemplos/AppDefault.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos;
2 |
3 | import java.io.IOException;
4 |
5 | /**
6 | * Example with SSL sockets using system properties.
7 | */
8 | public class AppDefault {
9 | public static void main(String[] args) throws IOException {
10 | System.setProperty("javax.net.ssl.keyStore", "src/main/certs/server/serverKey.jks");
11 | System.setProperty("javax.net.ssl.keyStorePassword","servpass");
12 | // System.setProperty("javax.net.ssl.trustStore", "src/main/certs/server/serverTrustedCerts.jks");
13 | // System.setProperty("javax.net.ssl.trustStorePassword", "servpass");
14 | System.setProperty("javax.net.ssl.trustStore", "src/main/certs/client/clientTrustedCerts.jks");
15 | System.setProperty("javax.net.ssl.trustStorePassword", "clientpass");
16 |
17 | new SSLDefaultServerSocket(5557).start();
18 |
19 | // System.setProperty("javax.net.ssl.keyStore", "src/main/certs/client/clientKey.jks");
20 | // System.setProperty("javax.net.ssl.keyStorePassword","clientpass");
21 | // System.setProperty("javax.net.ssl.trustStore", "src/main/certs/client/clientTrustedCerts.jks");
22 | // System.setProperty("javax.net.ssl.trustStorePassword", "clientpass");
23 | new SSLDefaultClientSocket("localhost",5557).start();
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/ejemplo-socket-ssl/src/main/java/com/chuidiang/ejemplos/SSLCustomClient.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos;
2 |
3 | import java.io.BufferedReader;
4 | import java.io.FileInputStream;
5 | import java.io.IOException;
6 | import java.io.InputStreamReader;
7 | import java.io.PrintWriter;
8 | import java.security.KeyStore;
9 |
10 | import javax.net.ssl.KeyManager;
11 | import javax.net.ssl.KeyManagerFactory;
12 | import javax.net.ssl.SSLContext;
13 | import javax.net.ssl.SSLSocket;
14 | import javax.net.ssl.SSLSocketFactory;
15 | import javax.net.ssl.TrustManager;
16 | import javax.net.ssl.TrustManagerFactory;
17 |
18 | public class SSLCustomClient {
19 | private SSLSocket client;
20 |
21 | public SSLCustomClient(String address, int port) throws Exception {
22 |
23 | KeyStore keyStore = KeyStore.getInstance("JKS");
24 | keyStore.load(new FileInputStream("src/main/certs/client/clientKey.jks"),
25 | "clientpass".toCharArray());
26 |
27 | KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
28 | kmf.init(keyStore, "clientpass".toCharArray());
29 |
30 | KeyStore trustedStore = KeyStore.getInstance("JKS");
31 | trustedStore.load(new FileInputStream(
32 | "src/main/certs/client/clientTrustedCerts.jks"), "clientpass"
33 | .toCharArray());
34 |
35 | TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
36 | tmf.init(trustedStore);
37 |
38 | SSLContext sc = SSLContext.getInstance("TLS");
39 | TrustManager[] trustManagers = tmf.getTrustManagers();
40 | KeyManager[] keyManagers = kmf.getKeyManagers();
41 | sc.init(keyManagers, trustManagers, null);
42 |
43 | SSLSocketFactory ssf = sc.getSocketFactory();
44 | client = (SSLSocket) ssf.createSocket(address, port);
45 | client.startHandshake();
46 | }
47 |
48 | public void start() {
49 | Util.startClientWorking(client);
50 | }
51 |
52 | }
53 |
--------------------------------------------------------------------------------
/ejemplo-socket-ssl/src/main/java/com/chuidiang/ejemplos/SSLCustomServer.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos;
2 |
3 | import java.io.FileInputStream;
4 | import java.security.KeyStore;
5 |
6 | import javax.net.ssl.KeyManager;
7 | import javax.net.ssl.KeyManagerFactory;
8 | import javax.net.ssl.SSLContext;
9 | import javax.net.ssl.SSLServerSocket;
10 | import javax.net.ssl.SSLServerSocketFactory;
11 | import javax.net.ssl.SSLSocket;
12 | import javax.net.ssl.TrustManager;
13 | import javax.net.ssl.TrustManagerFactory;
14 |
15 | public class SSLCustomServer {
16 | private SSLServerSocket serverSocket;
17 |
18 | public SSLCustomServer(int port) throws Exception {
19 |
20 | KeyStore keyStore = KeyStore.getInstance("JKS");
21 | keyStore.load(new FileInputStream("src/main/certs/server/serverKey.jks"),
22 | "servpass".toCharArray());
23 |
24 | KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
25 | kmf.init(keyStore, "servpass".toCharArray());
26 |
27 | KeyStore trustedStore = KeyStore.getInstance("JKS");
28 | trustedStore.load(new FileInputStream(
29 | "src/main/certs/server/serverTrustedCerts.jks"), "servpass"
30 | .toCharArray());
31 |
32 | TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
33 | tmf.init(trustedStore);
34 |
35 | SSLContext sc = SSLContext.getInstance("TLS");
36 | TrustManager[] trustManagers = tmf.getTrustManagers();
37 | KeyManager[] keyManagers = kmf.getKeyManagers();
38 | sc.init(keyManagers, trustManagers, null);
39 |
40 | SSLServerSocketFactory ssf = sc.getServerSocketFactory();
41 | serverSocket = (SSLServerSocket) ssf.createServerSocket(port);
42 |
43 | }
44 |
45 | public void start() {
46 | Util.startServerWorking(serverSocket);
47 | }
48 |
49 | }
50 |
--------------------------------------------------------------------------------
/ejemplo-socket-ssl/src/main/java/com/chuidiang/ejemplos/SSLDefaultClientSocket.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos;
2 |
3 | import java.io.BufferedReader;
4 | import java.io.IOException;
5 | import java.io.InputStreamReader;
6 | import java.io.PrintWriter;
7 | import java.net.Socket;
8 | import java.net.UnknownHostException;
9 |
10 | import javax.net.ssl.SSLSocketFactory;
11 |
12 | public class SSLDefaultClientSocket {
13 | Socket client = null;
14 |
15 | public SSLDefaultClientSocket(String server, int port)
16 | throws UnknownHostException, IOException {
17 | SSLSocketFactory clientFactory = (SSLSocketFactory) SSLSocketFactory
18 | .getDefault();
19 | client = clientFactory.createSocket(server, port);
20 | }
21 |
22 | public void start() {
23 | Util.startClientWorking(client);
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/ejemplo-socket-ssl/src/main/java/com/chuidiang/ejemplos/SSLDefaultServerSocket.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos;
2 |
3 | import java.io.IOException;
4 | import java.net.ServerSocket;
5 |
6 | import javax.net.ssl.SSLServerSocketFactory;
7 |
8 | public class SSLDefaultServerSocket {
9 | private ServerSocket serverSocket;
10 |
11 | public SSLDefaultServerSocket(int port) throws IOException {
12 | SSLServerSocketFactory serverFactory = (SSLServerSocketFactory) SSLServerSocketFactory
13 | .getDefault();
14 | serverSocket = serverFactory.createServerSocket(port);
15 | }
16 |
17 | public void start() {
18 | Util.startServerWorking(serverSocket);
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/ejemplo-socket-ssl/src/test/java/com/chuidiang/ejemplos/AppTest.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos;
2 |
3 | import junit.framework.Test;
4 | import junit.framework.TestCase;
5 | import junit.framework.TestSuite;
6 |
7 | /**
8 | * Unit test for simple AppDefault.
9 | */
10 | public class AppTest
11 | extends TestCase
12 | {
13 | /**
14 | * Create the test case
15 | *
16 | * @param testName name of the test case
17 | */
18 | public AppTest( String testName )
19 | {
20 | super( testName );
21 | }
22 |
23 | /**
24 | * @return the suite of tests being tested
25 | */
26 | public static Test suite()
27 | {
28 | return new TestSuite( AppTest.class );
29 | }
30 |
31 | /**
32 | * Rigourous Test :-)
33 | */
34 | public void testApp()
35 | {
36 | assertTrue( true );
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/ejemplo_cxf/pom.xml:
--------------------------------------------------------------------------------
1 |
3 | 4.0.0
4 | com.chuidiang.ejemplos
5 | ejemplo_cxf
6 | 1.0-SNAPSHOT
7 | war
8 | Simple CXF project using spring configuration
9 | Simple CXF project using spring configuration
10 |
11 |
12 | org.apache.cxf
13 | cxf-rt-frontend-jaxws
14 | 2.5.2
15 |
16 |
17 | org.apache.cxf
18 | cxf-rt-transports-http
19 | 2.5.2
20 |
21 |
23 |
24 | org.apache.cxf
25 | cxf-rt-ws-security
26 | 2.5.2
27 |
28 |
29 | org.apache.cxf
30 | cxf-rt-transports-http-jetty
31 | 2.5.2
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 | org.apache.maven.plugins
41 | maven-compiler-plugin
42 |
43 | 1.5
44 | 1.5
45 |
46 |
47 |
48 | org.apache.maven.plugins
49 | maven-eclipse-plugin
50 |
51 | [artifactId]-[version]
52 | true
53 | true
54 | 2.0
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
--------------------------------------------------------------------------------
/ejemplo_cxf/src/main/java/com/chuidiang/ejemplos/cxf/Calculadora.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.cxf;
2 |
3 | import javax.jws.WebParam;
4 | import javax.jws.WebService;
5 | import javax.xml.ws.Holder;
6 |
7 | @WebService
8 | public interface Calculadora {
9 | double suma(@WebParam(name = "sum1") Holder a,
10 | @WebParam(name = "sum2") double b);
11 |
12 | double resta(double a, double b);
13 |
14 | }
15 |
--------------------------------------------------------------------------------
/ejemplo_cxf/src/main/java/com/chuidiang/ejemplos/cxf/CalculadoraImpl.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.cxf;
2 |
3 | import javax.jws.WebParam;
4 | import javax.jws.WebService;
5 | import javax.xml.ws.Holder;
6 |
7 | @WebService(endpointInterface = "com.chuidiang.ejemplos.cxf.Calculadora")
8 | public class CalculadoraImpl implements Calculadora {
9 |
10 | public double suma(@WebParam(name = "sum1") Holder a,
11 | @WebParam(name = "sum2") double b) {
12 | a.value = a.value + 1;
13 | return a.value + b - 1;
14 | }
15 |
16 | public double resta(double a, double b) {
17 | return a - b;
18 | }
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/ejemplo_cxf/src/main/java/com/chuidiang/ejemplos/cxf/Resultado.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.cxf;
2 |
3 | import javax.jws.WebParam;
4 | import javax.jws.WebService;
5 |
6 | @WebService
7 | public class Resultado {
8 |
9 | public void sumaResponse(@WebParam(name = "return") double sumaResponse,
10 | @WebParam(name = "sum1") double arg1) {
11 | System.out.println(sumaResponse);
12 | System.out.println(arg1);
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/ejemplo_cxf/src/main/webapp/WEB-INF/beans.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
9 |
10 |
11 |
12 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/ejemplo_cxf/src/main/webapp/WEB-INF/web.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
6 |
7 |
8 |
9 |
10 | contextConfigLocation
11 | WEB-INF/beans.xml
12 |
13 |
14 |
15 |
16 | org.springframework.web.context.ContextLoaderListener
17 |
18 |
19 |
20 |
21 | CXFServlet
22 | CXF Servlet
23 |
24 | org.apache.cxf.transport.servlet.CXFServlet
25 |
26 | 1
27 |
28 |
29 |
30 | CXFServlet
31 | /*
32 |
33 |
34 |
--------------------------------------------------------------------------------
/ejemplo_cxf/src/test/java/com/chuidiang/ejemplos/cxf/ServerCalculadora.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.cxf;
2 |
3 | import org.apache.cxf.interceptor.LoggingInInterceptor;
4 | import org.apache.cxf.interceptor.LoggingOutInterceptor;
5 | import org.apache.cxf.jaxws.EndpointImpl;
6 | import org.apache.cxf.ws.addressing.WSAddressingFeature;
7 |
8 | public class ServerCalculadora {
9 |
10 | /**
11 | * @param args
12 | */
13 | public static void main(String[] args) {
14 |
15 | EndpointImpl endpoint = (EndpointImpl) EndpointImpl.create(
16 |
17 | new CalculadoraImpl());
18 |
19 | endpoint.getFeatures().add(new WSAddressingFeature());
20 | endpoint.publish("http://localhost:8080/ejemplo_cxf/Calculadora");
21 |
22 | LoggingInInterceptor logIn = new LoggingInInterceptor();
23 | logIn.setPrettyLogging(true);
24 | endpoint.getInInterceptors().add(logIn);
25 | LoggingOutInterceptor logOut = new LoggingOutInterceptor();
26 | logOut.setPrettyLogging(true);
27 | endpoint.getOutInterceptors().add(logOut);
28 | }
29 |
30 | }
--------------------------------------------------------------------------------
/ejemplos-android/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
8 |
9 |
12 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/ejemplos-android/proguard-project.txt:
--------------------------------------------------------------------------------
1 | # To enable ProGuard in your project, edit project.properties
2 | # to define the proguard.config property as described in that file.
3 | #
4 | # Add project specific ProGuard rules here.
5 | # By default, the flags in this file are appended to flags specified
6 | # in ${sdk.dir}/tools/proguard/proguard-android.txt
7 | # You can edit the include path and order by changing the ProGuard
8 | # include property in project.properties.
9 | #
10 | # For more details, see
11 | # http://developer.android.com/guide/developing/tools/proguard.html
12 |
13 | # Add any project specific keep options here:
14 |
15 | # If your project uses WebView with JS, uncomment the following
16 | # and specify the fully qualified class name to the JavaScript interface
17 | # class:
18 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
19 | # public *;
20 | #}
21 |
--------------------------------------------------------------------------------
/ejemplos-android/project.properties:
--------------------------------------------------------------------------------
1 | # This file is automatically generated by Android Tools.
2 | # Do not modify this file -- YOUR CHANGES WILL BE ERASED!
3 | #
4 | # This file must be checked in Version Control Systems.
5 | #
6 | # To customize properties used by the Ant build system edit
7 | # "ant.properties", and override values to adapt the script to your
8 | # project structure.
9 | #
10 | # To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
11 | #proguard.config=${sdk.dir}\tools\proguard\proguard-android.txt:proguard-project.txt
12 |
13 | # Project target.
14 | target=android-15
15 |
--------------------------------------------------------------------------------
/ejemplos-android/res/drawable-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chuidiang/chuidiang-ejemplos-google-code/7b01f5c0786b5855de0c4c3688b15d3c57914a28/ejemplos-android/res/drawable-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/ejemplos-android/res/drawable-ldpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chuidiang/chuidiang-ejemplos-google-code/7b01f5c0786b5855de0c4c3688b15d3c57914a28/ejemplos-android/res/drawable-ldpi/ic_launcher.png
--------------------------------------------------------------------------------
/ejemplos-android/res/drawable-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chuidiang/chuidiang-ejemplos-google-code/7b01f5c0786b5855de0c4c3688b15d3c57914a28/ejemplos-android/res/drawable-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/ejemplos-android/res/drawable-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chuidiang/chuidiang-ejemplos-google-code/7b01f5c0786b5855de0c4c3688b15d3c57914a28/ejemplos-android/res/drawable-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/ejemplos-android/res/layout/formulario.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
12 |
13 |
17 |
18 |
25 |
26 |
33 |
34 |
35 |
--------------------------------------------------------------------------------
/ejemplos-android/res/layout/main.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
12 |
13 |
18 |
19 |
20 |
24 |
25 |
--------------------------------------------------------------------------------
/ejemplos-android/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Hello World, AndroidHolaMundoActivity!
5 | AndroidHolaMundo
6 |
7 |
--------------------------------------------------------------------------------
/ejemplos-android/src/com/chuidiang/ejemplos/android/AndroidHolaMundoActivity.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.android;
2 |
3 | import android.app.Activity;
4 | import android.app.DialogFragment;
5 | import android.app.Fragment;
6 | import android.app.FragmentManager;
7 | import android.app.FragmentTransaction;
8 | import android.os.Bundle;
9 | import android.view.View;
10 | import android.view.View.OnClickListener;
11 | import android.widget.Button;
12 | import android.widget.TextView;
13 |
14 | import com.chuidiang.ejemplos.android.DialogoFragment.FormularioListener;
15 |
16 | public class AndroidHolaMundoActivity extends Activity implements
17 | FormularioListener {
18 | /** Called when the activity is first created. */
19 | @Override
20 | public void onCreate(Bundle savedInstanceState) {
21 | super.onCreate(savedInstanceState);
22 | setContentView(R.layout.main);
23 |
24 | Button boton = (Button) findViewById(R.id.buton);
25 | boton.setOnClickListener(new OnClickListener() {
26 |
27 | @Override
28 | public void onClick(View v) {
29 | FragmentManager fm = getFragmentManager();
30 | DialogFragment editor = (DialogFragment) fm
31 | .findFragmentByTag("editor");
32 | if (null == editor) {
33 | editor = new DialogoFragment();
34 | }
35 | editor.show(fm, "editor");
36 | }
37 | });
38 | }
39 |
40 | @Override
41 | public void pulsado(int resultado, String texto) {
42 | TextView tv = (TextView) findViewById(R.id.textView);
43 | if (resultado == DialogoFragment.OK) {
44 | tv.setText(texto);
45 | }
46 | FragmentManager fm = getFragmentManager();
47 | Fragment editor = fm.findFragmentByTag("editor");
48 | FragmentTransaction ft = fm.beginTransaction();
49 | ft.remove(editor);
50 | ft.commit();
51 | }
52 | }
--------------------------------------------------------------------------------
/ejemplos-android/src/com/chuidiang/ejemplos/android/DialogoFragment.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chuidiang/chuidiang-ejemplos-google-code/7b01f5c0786b5855de0c4c3688b15d3c57914a28/ejemplos-android/src/com/chuidiang/ejemplos/android/DialogoFragment.java
--------------------------------------------------------------------------------
/ejemplos-java-mysql/paisaje.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chuidiang/chuidiang-ejemplos-google-code/7b01f5c0786b5855de0c4c3688b15d3c57914a28/ejemplos-java-mysql/paisaje.jpg
--------------------------------------------------------------------------------
/ejemplos-java-mysql/pom.xml:
--------------------------------------------------------------------------------
1 |
3 | 4.0.0
4 | com.chuidiang
5 | ejemplos-java-mysql
6 | jar
7 | 1.0-SNAPSHOT
8 | ejemplos-java-mysql
9 | http://www.chuidiang.com
10 |
11 |
12 | mysql
13 | mysql-connector-java
14 | 5.1.6
15 | compile
16 |
17 |
18 | junit
19 | junit
20 | 3.8.1
21 | test
22 |
23 |
24 | commons-dbcp
25 | commons-dbcp
26 | 1.2.2
27 | compile
28 |
29 |
30 |
31 |
--------------------------------------------------------------------------------
/ejemplos-java-mysql/src/main/config/datasource_config.properties:
--------------------------------------------------------------------------------
1 | # Propiedades para la conexion a base de datos con BasicDataSource
2 | driverClassName=com.mysql.jdbc.Driver
3 | username=hibernate
4 | password=hibernate
5 | url=jdbc:mysql://localhost/hibernate
6 | validationQuery=select 1
--------------------------------------------------------------------------------
/ejemplos-java-mysql/src/main/java/com/chuidiang/ejemplos/mysql/Conexion.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chuidiang/chuidiang-ejemplos-google-code/7b01f5c0786b5855de0c4c3688b15d3c57914a28/ejemplos-java-mysql/src/main/java/com/chuidiang/ejemplos/mysql/Conexion.java
--------------------------------------------------------------------------------
/ejemplos-java-mysql/src/main/java/com/chuidiang/ejemplos/mysql/Dato.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.mysql;
2 |
3 | import java.io.Serializable;
4 | import java.util.Date;
5 |
6 | /**
7 | * Un dato serializable, para poder insertarlo en base de datos.
8 | *
9 | * @author Chuidiang
10 | */
11 | public class Dato implements Serializable {
12 | /**
13 | * serial uid
14 | */
15 | private static final long serialVersionUID = -48390394042382173L;
16 |
17 | /** Un campo fecha */
18 | private Date fecha;
19 |
20 | /** Un campo int */
21 | private int valor;
22 |
23 | /** Un campo String */
24 | private String cadena;
25 |
26 | public Date getFecha() {
27 | return fecha;
28 | }
29 |
30 | public void setFecha(Date fecha) {
31 | this.fecha = fecha;
32 | }
33 |
34 | public int getValor() {
35 | return valor;
36 | }
37 |
38 | public void setValor(int valor) {
39 | this.valor = valor;
40 | }
41 |
42 | public String getCadena() {
43 | return cadena;
44 | }
45 |
46 | public void setCadena(String cadena) {
47 | this.cadena = cadena;
48 | }
49 |
50 | /**
51 | * Para poder sacar por pantalla rapidamente el contenido de la clase
52 | */
53 | public String toString() {
54 | return fecha + " " + valor + " " + cadena;
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/ejemplos-java-mysql/src/main/java/com/chuidiang/ejemplos/mysql/DatoGrande.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chuidiang/chuidiang-ejemplos-google-code/7b01f5c0786b5855de0c4c3688b15d3c57914a28/ejemplos-java-mysql/src/main/java/com/chuidiang/ejemplos/mysql/DatoGrande.java
--------------------------------------------------------------------------------
/ejemplos-java-mysql/src/main/java/com/chuidiang/ejemplos/mysql/ImagenesEnBaseDatos.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chuidiang/chuidiang-ejemplos-google-code/7b01f5c0786b5855de0c4c3688b15d3c57914a28/ejemplos-java-mysql/src/main/java/com/chuidiang/ejemplos/mysql/ImagenesEnBaseDatos.java
--------------------------------------------------------------------------------
/ejemplos-java-mysql/src/main/java/com/chuidiang/ejemplos/mysql/ObjectsEnBaseDatos.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chuidiang/chuidiang-ejemplos-google-code/7b01f5c0786b5855de0c4c3688b15d3c57914a28/ejemplos-java-mysql/src/main/java/com/chuidiang/ejemplos/mysql/ObjectsEnBaseDatos.java
--------------------------------------------------------------------------------
/ejemplos-java-mysql/src/main/java/com/chuidiang/ejemplos/preparedstatement_mysql/EjemploPreparedStatement.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chuidiang/chuidiang-ejemplos-google-code/7b01f5c0786b5855de0c4c3688b15d3c57914a28/ejemplos-java-mysql/src/main/java/com/chuidiang/ejemplos/preparedstatement_mysql/EjemploPreparedStatement.java
--------------------------------------------------------------------------------
/ejemplos-java-mysql/src/main/java/com/chuidiang/ejemplos/preparedstatement_mysql/RendimientoPreparedStatement.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chuidiang/chuidiang-ejemplos-google-code/7b01f5c0786b5855de0c4c3688b15d3c57914a28/ejemplos-java-mysql/src/main/java/com/chuidiang/ejemplos/preparedstatement_mysql/RendimientoPreparedStatement.java
--------------------------------------------------------------------------------
/ejemplos-java-mysql/src/test/java/com/chuidiang/AppTest.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang;
2 |
3 | import junit.framework.Test;
4 | import junit.framework.TestCase;
5 | import junit.framework.TestSuite;
6 |
7 | /**
8 | * Unit test for simple App.
9 | */
10 | public class AppTest
11 | extends TestCase
12 | {
13 | /**
14 | * Create the test case
15 | *
16 | * @param testName name of the test case
17 | */
18 | public AppTest( String testName )
19 | {
20 | super( testName );
21 | }
22 |
23 | /**
24 | * @return the suite of tests being tested
25 | */
26 | public static Test suite()
27 | {
28 | return new TestSuite( AppTest.class );
29 | }
30 |
31 | /**
32 | * Rigourous Test :-)
33 | */
34 | public void testApp()
35 | {
36 | assertTrue( true );
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/ejemplos-jaxb/src/main/java/com/chuidiang/ejemplos/UnaClase.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos;
2 |
3 | import javax.xml.bind.annotation.XmlElement;
4 | import javax.xml.bind.annotation.XmlRootElement;
5 |
6 | @XmlRootElement(name="La_Clase")
7 | public class UnaClase {
8 | @XmlElement(name="El_Atributo")
9 | private String unAtributo;
10 |
11 |
12 | public void setUnAtributo(String unAtributo) {
13 | this.unAtributo = unAtributo;
14 | }
15 |
16 |
17 | String getUnAtributo() {
18 | return this.unAtributo;
19 | }
20 | }
--------------------------------------------------------------------------------
/ejemplos-jaxb/src/test/java/com/chuidiang/ejemplos/AppTest.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos;
2 |
3 | import junit.framework.Test;
4 | import junit.framework.TestCase;
5 | import junit.framework.TestSuite;
6 |
7 | /**
8 | * Unit test for simple App.
9 | */
10 | public class AppTest
11 | extends TestCase
12 | {
13 | /**
14 | * Create the test case
15 | *
16 | * @param testName name of the test case
17 | */
18 | public AppTest( String testName )
19 | {
20 | super( testName );
21 | }
22 |
23 | /**
24 | * @return the suite of tests being tested
25 | */
26 | public static Test suite()
27 | {
28 | return new TestSuite( AppTest.class );
29 | }
30 |
31 | /**
32 | * Rigourous Test :-)
33 | */
34 | public void testApp()
35 | {
36 | assertTrue( true );
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/ejemplos-swing/pom.xml:
--------------------------------------------------------------------------------
1 |
3 | 4.0.0
4 | com.chuidiang.ejemplos
5 | ejemplos-swing
6 | jar
7 | 1.0-SNAPSHOT
8 | ejemplos-swing
9 | http://maven.apache.org
10 |
11 |
12 | junit
13 | junit
14 | 3.8.1
15 | test
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/ejemplos-swing/src/main/java/com/chuidiang/ejemplos/option_pane_dialog_modal/DialogoModal.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chuidiang/chuidiang-ejemplos-google-code/7b01f5c0786b5855de0c4c3688b15d3c57914a28/ejemplos-swing/src/main/java/com/chuidiang/ejemplos/option_pane_dialog_modal/DialogoModal.java
--------------------------------------------------------------------------------
/ejemplos-swing/src/main/java/com/chuidiang/ejemplos/option_pane_dialog_modal/EjemplosJOptionPane.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chuidiang/chuidiang-ejemplos-google-code/7b01f5c0786b5855de0c4c3688b15d3c57914a28/ejemplos-swing/src/main/java/com/chuidiang/ejemplos/option_pane_dialog_modal/EjemplosJOptionPane.java
--------------------------------------------------------------------------------
/ejemplos-swing/src/main/java/com/chuidiang/ejemplos/swing_worker/Principal1.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chuidiang/chuidiang-ejemplos-google-code/7b01f5c0786b5855de0c4c3688b15d3c57914a28/ejemplos-swing/src/main/java/com/chuidiang/ejemplos/swing_worker/Principal1.java
--------------------------------------------------------------------------------
/ejemplos-swing/src/main/java/com/chuidiang/ejemplos/swing_worker/Principal2.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chuidiang/chuidiang-ejemplos-google-code/7b01f5c0786b5855de0c4c3688b15d3c57914a28/ejemplos-swing/src/main/java/com/chuidiang/ejemplos/swing_worker/Principal2.java
--------------------------------------------------------------------------------
/ejemplos-swing/src/main/java/com/chuidiang/ejemplos/swing_worker/Worker1.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chuidiang/chuidiang-ejemplos-google-code/7b01f5c0786b5855de0c4c3688b15d3c57914a28/ejemplos-swing/src/main/java/com/chuidiang/ejemplos/swing_worker/Worker1.java
--------------------------------------------------------------------------------
/ejemplos-swing/src/test/java/com/chuidiang/ejemplos/AppTest.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos;
2 |
3 | import junit.framework.Test;
4 | import junit.framework.TestCase;
5 | import junit.framework.TestSuite;
6 |
7 | /**
8 | * Unit test for simple App.
9 | */
10 | public class AppTest
11 | extends TestCase
12 | {
13 | /**
14 | * Create the test case
15 | *
16 | * @param testName name of the test case
17 | */
18 | public AppTest( String testName )
19 | {
20 | super( testName );
21 | }
22 |
23 | /**
24 | * @return the suite of tests being tested
25 | */
26 | public static Test suite()
27 | {
28 | return new TestSuite( AppTest.class );
29 | }
30 |
31 | /**
32 | * Rigourous Test :-)
33 | */
34 | public void testApp()
35 | {
36 | assertTrue( true );
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/hibernate-herencia/pom.xml:
--------------------------------------------------------------------------------
1 |
4 |
5 | 4.0.0
6 | com.chuidiang.ejemplos
7 | EjemplosHibernate
8 | 1.0-SNAPSHOT
9 | jar
10 | hibernate-herencia
11 | http://maven.apache.org
12 |
13 | UTF-8
14 |
15 |
16 |
17 | org.hibernate
18 | hibernate-core
19 | 4.1.4.Final
20 | compile
21 |
22 |
23 | mysql
24 | mysql-connector-java
25 | 5.1.20
26 |
27 |
28 |
--------------------------------------------------------------------------------
/hibernate-herencia/src/main/java/com/chuidiang/ejemplos/HibernateUtil.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos;
2 |
3 | import org.hibernate.SessionFactory;
4 | import org.hibernate.cfg.Configuration;
5 | import org.hibernate.service.ServiceRegistry;
6 | import org.hibernate.service.ServiceRegistryBuilder;
7 |
8 | public class HibernateUtil {
9 |
10 | private static final SessionFactory sessionFactory = buildSessionFactory();
11 |
12 | private static SessionFactory buildSessionFactory() {
13 | try {
14 | Configuration configuration = new Configuration();
15 | configuration.configure();
16 | ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
17 | .applySettings(configuration.getProperties())
18 | .buildServiceRegistry();
19 | return configuration.buildSessionFactory(serviceRegistry);
20 |
21 | } catch (Throwable ex) {
22 | System.err.println("Initial SessionFactory creation failed." + ex);
23 | throw new ExceptionInInitializerError(ex);
24 | }
25 | }
26 |
27 | public static SessionFactory getSessionFactory() {
28 | return sessionFactory;
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/hibernate-herencia/src/main/java/com/chuidiang/ejemplos/Hija1.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos;
2 |
3 | public class Hija1 extends Padre {
4 | int atributoHija1;
5 |
6 |
7 | public int getAtributoHija1() {
8 | return atributoHija1;
9 | }
10 |
11 |
12 | public void setAtributoHija1(int atributoHija1) {
13 | this.atributoHija1 = atributoHija1;
14 | }
15 |
16 |
17 | @Override
18 | public String diQuienEres() {
19 | return "Soy Hijo1 y tengo un atributoHija1="+atributoHija1;
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/hibernate-herencia/src/main/java/com/chuidiang/ejemplos/Hija2.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos;
2 |
3 | public class Hija2 extends Padre {
4 |
5 | boolean atributoHija2;
6 |
7 |
8 | public boolean isAtributoHija2() {
9 | return atributoHija2;
10 | }
11 |
12 |
13 | public void setAtributoHija2(boolean atributoHija2) {
14 | this.atributoHija2 = atributoHija2;
15 | }
16 |
17 |
18 | @Override
19 | public String diQuienEres() {
20 | return "Soy Hijo2 y tengo un atributoHija2=" + atributoHija2;
21 | }
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/hibernate-herencia/src/main/java/com/chuidiang/ejemplos/MainEjemploTablaPorSubclase.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos;
2 |
3 | import java.util.Date;
4 | import java.util.List;
5 |
6 | import org.hibernate.Session;
7 |
8 |
9 | public class MainEjemploTablaPorSubclase {
10 | public static void main(String[] args) {
11 | insertaAlgunDato();
12 | consultaDatos();
13 | }
14 |
15 | private static void consultaDatos() {
16 | Session s = HibernateUtil.getSessionFactory().openSession();
17 | List datos = s.createQuery("from Padre").list();
18 | for (Padre dato : datos) {
19 | System.out.println(dato.getId());
20 | System.out.println(dato.getAtributoPadre());
21 | System.out.println(dato.getDate());
22 | System.out.println(dato.diQuienEres());
23 | }
24 | s.close();
25 | }
26 |
27 | private static void insertaAlgunDato() {
28 | Session s = HibernateUtil.getSessionFactory().openSession();
29 | try {
30 | Hija1 d1 = new Hija1();
31 | d1.setDate(new Date());
32 | d1.setAtributoPadre("titulo");
33 | d1.setAtributoHija1(22);
34 |
35 | Hija2 d2 = new Hija2();
36 | d2.setDate(new Date());
37 | d2.setAtributoPadre("otro titulo");
38 | d2.setAtributoHija2(true);
39 |
40 | s.beginTransaction();
41 | s.save(d1);
42 | s.save(d2);
43 | s.getTransaction().commit();
44 | } catch (Exception e) {
45 | e.printStackTrace();
46 | } finally {
47 | s.close();
48 | }
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/hibernate-herencia/src/main/java/com/chuidiang/ejemplos/Padre.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos;
2 |
3 | import java.util.Date;
4 |
5 |
6 | public abstract class Padre {
7 | public long getId() {
8 | return id;
9 | }
10 | public void setId(long id) {
11 | this.id = id;
12 | }
13 | public Date getDate() {
14 | return date;
15 | }
16 | public void setDate(Date date) {
17 | this.date = date;
18 | }
19 | public String getAtributoPadre() {
20 | return atributoPadre;
21 | }
22 | public void setAtributoPadre(String atributoPadre) {
23 | this.atributoPadre = atributoPadre;
24 | }
25 |
26 | private long id;
27 |
28 | private Date date;
29 | private String atributoPadre;
30 |
31 | public abstract String diQuienEres();
32 | }
33 |
--------------------------------------------------------------------------------
/hibernate-herencia/src/main/resources/com/chuidiang/ejemplos/tabla_por_jerarquia/Padre.hbm.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
16 |
17 |
18 |
19 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/hibernate-herencia/src/main/resources/com/chuidiang/ejemplos/tabla_por_subclase/Padre.hbm.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/hibernate-herencia/src/main/resources/com/chuidiang/ejemplos/tabla_por_subclase_concreta/Padre.hbm.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/hibernate-herencia/src/main/resources/hibernate.cfg.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
15 |
16 | com.mysql.jdbc.Driver
17 | jdbc:mysql://localhost:3306/pruebas
18 | root
19 |
20 |
21 | create
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/mbean/src/com/chuidiang/ejemplos/mbean/Hello.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.mbean;
2 |
3 | /**
4 | * A mbean implementation. It must implement a mbean interface
5 | * ( A interface which name ends with "MBean" ). The class must
6 | * have the same name as the interface, but without the trailing
7 | * "MBean"
8 | *
9 | * Something implements SomethingMBean
10 | *
11 | * @author chuidiang
12 | *
13 | */
14 | public class Hello implements HelloMBean {
15 | private int counter=0;
16 | @Override
17 | public int getCounter() {
18 | return counter;
19 | }
20 |
21 | @Override
22 | public void reset() {
23 | counter=0;
24 | }
25 |
26 | public void increment() {
27 | counter++;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/mbean/src/com/chuidiang/ejemplos/mbean/HelloMBean.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.mbean;
2 |
3 | /**
4 | * MBean interface example. It must end with "MBean"
5 | * @author chuidiang
6 | *
7 | */
8 | public interface HelloMBean {
9 | int getCounter();
10 | void reset();
11 | }
12 |
--------------------------------------------------------------------------------
/mbean/src/com/chuidiang/ejemplos/mbean/PruebaMBean.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.mbean;
2 |
3 | import java.lang.management.ManagementFactory;
4 |
5 | import javax.management.MBeanServer;
6 | import javax.management.ObjectName;
7 |
8 | public class PruebaMBean {
9 |
10 | public static void main(String[] args) throws Exception {
11 | MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
12 | ObjectName name = new ObjectName("com.example:type=Hello");
13 | Hello mbean = new Hello();
14 | mbs.registerMBean(mbean, name);
15 |
16 | while (true){
17 | mbean.increment();
18 | Thread.sleep(1000);
19 | }
20 | }
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/organizador-fotos/pom.xml:
--------------------------------------------------------------------------------
1 |
3 | 4.0.0
4 | com.chuidiang.organizador_fotos
5 | OrganizadorFotos
6 | 0.0.1-SNAPSHOT
7 | Organizador Fotos
8 |
9 |
10 | com.drewnoakes
11 | metadata-extractor
12 | 2.8.1
13 | compile
14 |
15 |
16 | commons-io
17 | commons-io
18 | 2.4
19 | compile
20 |
21 |
22 |
--------------------------------------------------------------------------------
/organizador-fotos/src/main/java/com/chuidiang/organizador_fotos/RenamePhotos.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.organizador_fotos;
2 |
3 | import java.io.File;
4 | import java.io.IOException;
5 | import java.util.Arrays;
6 |
7 | import org.apache.commons.io.FileUtils;
8 |
9 | public class RenamePhotos {
10 |
11 | public static void main(String[] args) {
12 | RenamePhotos rename = new RenamePhotos();
13 | String path = "D:/JAVIER/Google Drive/FOTOS_FECHA/2003/10/31";
14 | String text = "Maria y Nuria 2003";
15 | rename.rename(path, text);
16 |
17 | }
18 |
19 | private void rename(String path, String text) {
20 | File directory = new File(path);
21 | if (!directory.canRead()){
22 | System.err.println("Can't read "+path);
23 | return;
24 | }
25 |
26 | if (directory.isDirectory()){
27 | File [] files = directory.listFiles();
28 | for (File file : files){
29 | renameFile(file.getAbsolutePath(), text);
30 | }
31 | } else {
32 | renameFile(path,text);
33 | }
34 |
35 | }
36 |
37 | private void renameFile(String file, String text) {
38 | File photo = new File(file);
39 | if (!photo.isFile()){
40 | return;
41 | }
42 | if (!photo.canRead()){
43 | return;
44 | }
45 |
46 | String name = photo.getName();
47 | String [] tokens = name.split("\\.");
48 | String newName = tokens[0]+"-"+text+"."+tokens[1];
49 |
50 |
51 | try {
52 | // FileUtils.moveFile(photo, new File(photo.getParentFile(),newName));
53 | System.out.println(photo+ " -> "+ new File(photo.getParentFile(),newName));
54 | FileUtils.moveFile(photo, new File(photo.getParentFile(),newName));
55 | } catch (IOException e) {
56 | System.err.println("Error renaming file "+e.getMessage());
57 | }
58 | }
59 |
60 | }
61 |
--------------------------------------------------------------------------------
/pruebas-geotools/src/com/chuidiang/ejemplos/geotools/GeotoolsMain.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chuidiang/chuidiang-ejemplos-google-code/7b01f5c0786b5855de0c4c3688b15d3c57914a28/pruebas-geotools/src/com/chuidiang/ejemplos/geotools/GeotoolsMain.java
--------------------------------------------------------------------------------
/pruebas-geotools/src/com/chuidiang/ejemplos/geotools/PanelCapas.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.geotools;
2 |
3 | import java.awt.FlowLayout;
4 | import java.awt.event.ActionEvent;
5 | import java.awt.event.ActionListener;
6 |
7 | import javax.swing.JCheckBox;
8 | import javax.swing.JPanel;
9 |
10 | import org.geotools.map.Layer;
11 |
12 | public class PanelCapas extends JPanel{
13 |
14 | public PanelCapas(Layer[] layers) {
15 | super(new FlowLayout());
16 |
17 | for (Layer layer : layers) {
18 | JCheckBox checkBox = new JCheckBox(layer.getTitle(),layer.isVisible());
19 | checkBox.addActionListener(new LayerListener(layer));
20 | add(checkBox);
21 | }
22 | }
23 |
24 |
25 | class LayerListener implements ActionListener {
26 | private Layer layer;
27 | public LayerListener(Layer layer) {
28 | this.layer=layer;
29 | }
30 | @Override
31 | public void actionPerformed(ActionEvent event) {
32 | if (((JCheckBox)event.getSource()).isSelected()){
33 | layer.setVisible(true);
34 | } else {
35 | layer.setVisible(false);
36 | }
37 |
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/pruebas-worldwind/src/com/chuidiang/ejemplos/worldwind/MiPoligono.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.worldwind;
2 |
3 | import gov.nasa.worldwind.avlist.AVKey;
4 | import gov.nasa.worldwind.geom.Position;
5 | import gov.nasa.worldwind.render.BasicShapeAttributes;
6 | import gov.nasa.worldwind.render.Material;
7 | import gov.nasa.worldwind.render.Polygon;
8 | import gov.nasa.worldwind.render.ShapeAttributes;
9 |
10 | import java.util.ArrayList;
11 |
12 | public class MiPoligono {
13 | private Polygon poly;
14 | public MiPoligono() {
15 | // Set the basic attributes of your polygon
16 | ShapeAttributes normalAttributes = new BasicShapeAttributes();
17 | normalAttributes.setInteriorMaterial(Material.YELLOW);
18 | normalAttributes.setOutlineWidth(2);
19 | normalAttributes.setOutlineOpacity(0.5);
20 | normalAttributes.setDrawInterior(true);
21 | normalAttributes.setDrawOutline(true);
22 |
23 | // Set the coordinates (in degrees) to draw your polygon
24 | // To radians just change the method the class Position
25 | // to fromRadians().
26 | ArrayList positions = new ArrayList();
27 | positions.add(Position.fromDegrees(52, 10, 5e4));
28 | positions.add(Position.fromDegrees(55, 11, 5e4));
29 | positions.add(Position.fromDegrees(52, 14, 5e4));
30 |
31 | poly = new Polygon(positions);
32 |
33 | poly.setAttributes(normalAttributes);
34 | // Tooltip text of the polygon
35 | poly.setValue(AVKey.DISPLAY_NAME, "My first polygon");
36 | }
37 |
38 | public Polygon getPolygon(){
39 | return poly;
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/pruebas-worldwind/src/org/chuidiang/chuwiki/worldwind/CapaIconos.java:
--------------------------------------------------------------------------------
1 | package org.chuidiang.chuwiki.worldwind;
2 |
3 | import gov.nasa.worldwind.avlist.AVKey;
4 | import gov.nasa.worldwind.awt.WorldWindowGLCanvas;
5 | import gov.nasa.worldwind.geom.Position;
6 | import gov.nasa.worldwind.layers.IconLayer;
7 | import gov.nasa.worldwind.render.UserFacingIcon;
8 | import gov.nasa.worldwindx.examples.ApplicationTemplate;
9 | import gov.nasa.worldwindx.examples.LayerPanel;
10 |
11 | import java.awt.Dimension;
12 | import java.io.File;
13 |
14 | public class CapaIconos {
15 | private WorldWindowGLCanvas wwd;
16 | private IconLayer capa;
17 | private final double LATITUD_INICIAL = 40.25;
18 | private final double LONGITUD_INICIAL = -3.25;
19 | private final double MAXIMO_DESPLAZAMIENTO = 0.1;
20 |
21 | private String iconos[] = { "Status-weather-clear-icon.png",
22 | "Status-weather-clouds-icon.png",
23 | "Status-weather-showers-scattered-day-icon.png",
24 | "Status-weather-showers-scattered-icon.png",
25 | "Status-weather-storm-night-icon.png"
26 | };
27 |
28 | public CapaIconos(WorldWindowGLCanvas wwd, LayerPanel panelCapas) {
29 | this.wwd = wwd;
30 |
31 | capa = new IconLayer();
32 | capa.setName("Iconos");
33 | ApplicationTemplate.insertBeforeCompass(wwd, capa);
34 | panelCapas.update(wwd);
35 | }
36 |
37 | public void pintaIconos() {
38 | for (String icono : iconos) {
39 |
40 | UserFacingIcon userIcon = new UserFacingIcon("files/forecast/"
41 | + icono, Position.fromDegrees(LATITUD_INICIAL + Math.random()
42 | * MAXIMO_DESPLAZAMIENTO - (MAXIMO_DESPLAZAMIENTO / 2.0),
43 | LONGITUD_INICIAL + Math.random() * MAXIMO_DESPLAZAMIENTO
44 | - (MAXIMO_DESPLAZAMIENTO / 2.0)));
45 | userIcon.setSize(new Dimension(64, 64));
46 | userIcon.setValue(AVKey.DISPLAY_NAME, "el tiempo");
47 | capa.addIcon(userIcon);
48 | }
49 | wwd.redraw();
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/pruebas-worldwind/src/org/chuidiang/chuwiki/worldwind/CapaPoligonos.java:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chuidiang/chuidiang-ejemplos-google-code/7b01f5c0786b5855de0c4c3688b15d3c57914a28/pruebas-worldwind/src/org/chuidiang/chuwiki/worldwind/CapaPoligonos.java
--------------------------------------------------------------------------------
/python-ejemplos/editor.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on 28/04/2012
3 |
4 | @author: Chuidiang
5 | '''
6 | from ScrolledText import ScrolledText
7 | from Tkconstants import INSERT, W, N, E, S, END
8 | from Tkinter import Button, StringVar, Tk, Label
9 | import tkFileDialog
10 |
11 | def cargar():
12 | fichero = tkFileDialog.askopenfilename()
13 | nombreFichero.set(fichero)
14 | f = open(fichero)
15 | contenido.delete(1.0, END)
16 | contenido.insert(INSERT, f.read())
17 | f.close()
18 |
19 | def salvar():
20 | fichero = tkFileDialog.asksaveasfilename()
21 | f = open(fichero,"w")
22 | f.write(contenido.get(1.0, END))
23 | f.close()
24 |
25 | if __name__ == '__main__':
26 |
27 | ventana = Tk()
28 | ventana.title("Editor tonto de textos")
29 |
30 | t = Label(ventana)
31 | t.grid(row=0, column=2, sticky=W + E, columnspan=2)
32 |
33 | nombreFichero = StringVar()
34 | t["textvariable"] = nombreFichero
35 |
36 | botonLoad = Button(ventana, text="Load", command=cargar)
37 | botonLoad.grid(row=0, column=0, sticky=W)
38 |
39 | botonSave = Button(ventana, text="Save", command=salvar)
40 | botonSave.grid(row=0, column=1, sticky=W)
41 |
42 | contenido = ScrolledText(ventana)
43 | contenido.grid(row=1, columnspan=3, sticky=W + E + N + S)
44 |
45 | ventana.grid_columnconfigure(2, weight=1)
46 | ventana.grid_rowconfigure(1, weight=1)
47 | ventana.mainloop()
48 |
--------------------------------------------------------------------------------
/python-gmail/enviar-gmail-compuesto.py:
--------------------------------------------------------------------------------
1 | # Javier Abellan. 17 Febrero 2009
2 | # Ejemplo de envio de un mail con imagen adjunta con python y gmail.
3 |
4 | import smtplib
5 | import mimetypes
6 |
7 | from email.MIMEMultipart import MIMEMultipart
8 | from email.MIMEText import MIMEText
9 | from email.MIMEImage import MIMEImage
10 | from email.Encoders import encode_base64
11 |
12 | # Construimos un mensaje Multipart, con un texto y una imagen adjunta
13 | mensaje = MIMEMultipart()
14 | mensaje['From']="usuario@gmail.com"
15 | mensaje['To']="destinatario@gmail.com"
16 | mensaje['Subject']="Tienes un correo"
17 |
18 | # Adjuntamos el texto
19 | mensaje.attach(MIMEText("""Este es el mensaje
20 | de las narices"""))
21 |
22 | # Adjuntamos la imagen
23 | file = open("Chuidiang-64.gif", "rb")
24 | contenido = MIMEImage(file.read())
25 | contenido.add_header('Content-Disposition', 'attachment; filename = "Chuidiang-64.gif"')
26 | mensaje.attach(contenido)
27 |
28 | # Establecemos conexion con el servidor smtp de gmail
29 | mailServer = smtplib.SMTP('smtp.gmail.com',587)
30 | mailServer.ehlo()
31 | mailServer.starttls()
32 | mailServer.ehlo()
33 | mailServer.login("usuario@gmail.com","password")
34 |
35 | # Enviamos el correo, con los campos from y to.
36 | mailServer.sendmail("usuario@gmail.com",
37 | "destinatario@gmail.com",
38 | mensaje.as_string())
39 |
40 | # Cierre de la conexion
41 | mailServer.close()
42 |
--------------------------------------------------------------------------------
/python-gmail/enviar-gmail.py:
--------------------------------------------------------------------------------
1 | # Javier Abellan. 17 Feb 2009
2 | # Ejemplo de envio de un correo simple con python y gmail.
3 |
4 | import smtplib
5 | import mimetypes
6 |
7 | from email.MIMEText import MIMEText
8 | from email.Encoders import encode_base64
9 |
10 | # Construimos el mensaje simple
11 | mensaje = MIMEText("""Este es el mensaje
12 | de las narices""")
13 | mensaje['From']="usuario@gmail.com"
14 | mensaje['To']="destinatario@gmail.com"
15 | mensaje['Subject']="Tienes un correo"
16 |
17 | # Establecemos conexion con el servidor smtp de gmail
18 | mailServer = smtplib.SMTP('smtp.gmail.com',587)
19 | mailServer.ehlo()
20 | mailServer.starttls()
21 | mailServer.ehlo()
22 | mailServer.login("usuario@gmail.com","password")
23 |
24 | # Envio del mensaje
25 | mailServer.sendmail("usuario@gmail.com",
26 | "destinatario@gmail.com",
27 | mensaje.as_string())
28 |
29 | # Cierre de la conexion
30 | mailServer.close()
31 |
--------------------------------------------------------------------------------
/python-gmail/lee-gmail.py:
--------------------------------------------------------------------------------
1 | # Javier Abellan. 17 Feb 2009
2 | # Ejemplo de lectura de correos con python y gmail.
3 | import poplib
4 | from email.Parser import Parser
5 |
6 | # Se establece conexion con el servidor pop de gmail
7 | m = poplib.POP3_SSL('pop.gmail.com',995)
8 | m.user('usuario@gmail.com')
9 | m.pass_('password')
10 |
11 | # Se obtiene el numero de mensajes pendientes y se hace un
12 | # bucle para cada mensaje
13 | numero = len(m.list()[1])
14 | for i in range (numero):
15 | print "Mensaje numero"+str(i+1)
16 | print "--------------------"
17 | # Se lee el mensaje
18 | response, headerLines, bytes = m.retr(i+1)
19 | # Se mete todo el mensaje en un unico string
20 | mensaje='\n'.join(headerLines)
21 | # Se parsea el mensaje
22 | p = Parser()
23 | email = p.parsestr(mensaje)
24 | # Se sacan por pantalla los campos from, to y subject
25 | print "From: "+email["From"]
26 | print "To: "+email["To"]
27 | print "Subject: "+email["Subject"]
28 | # Si es un mensaje compuesto
29 | if (email.is_multipart()):
30 | # bucle para cada parte del mensaje
31 | for part in email.get_payload():
32 | # Se mira el mime type de la parte
33 | tipo = part.get_content_type()
34 | if ("text/plain" == tipo):
35 | # Si es texto plano, se saca por pantalla
36 | print part.get_payload(decode=True)
37 | if ("image/gif" == tipo):
38 | # Si es imagen, se extrae el nombre del fichero
39 | # adjunto y se guarda la imagen
40 | nombre_fichero = part.get_filename()
41 | fp = open('recibido_'+nombre_fichero,'wb')
42 | fp.write(part.get_payload(decode=True))
43 | fp.close()
44 | else:
45 | # Si es mensaje simple
46 | tipo = email.get_content_type()
47 | if ("text/plain" == tipo):
48 | # Si es texto plano, se escribe en pantalla
49 | print email.get_payload(decode=True)
50 |
51 | # Cierre de la conexion
52 | m.quit()
53 |
--------------------------------------------------------------------------------
/python-hilos/src/thread_hilo_lock.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on 20/02/2009
3 | @author: Chuidiang
4 |
5 | Ejemplo de un hilo con bloqueo.
6 | Un main lanza un hilo y un lock sirve para hacer que el hilo espere
7 | el permiso del main para continuar y para que el main espere que el hilo
8 | termine antes de terminar el programa
9 | '''
10 |
11 | import thread
12 | import time
13 |
14 | # Numero de hilos que han terminado
15 | hilo_terminado = False
16 |
17 | # Funcion que se ejecuta en un hilo
18 |
19 | def funcion (inicio, fin, bloqueo):
20 | global hilo_terminado
21 | # El hilo espera el bloqueo
22 | print "Hilo: Pido bloqueo"
23 | bloqueo.acquire()
24 | print "Hilo: Empiezo "+str(inicio)+" "+str(fin)
25 | hilo_terminado = True
26 | print "Hilo: y termino"
27 | bloqueo.release()
28 |
29 |
30 | if __name__ == '__main__':
31 | # Pedimos un lock y lo bloqueamos
32 | bloqueo = thread.allocate_lock()
33 | bloqueo.acquire()
34 | # Lanzamos un hilo, que se quedara en espera
35 | thread.start_new_thread(funcion, (3,11,bloqueo))
36 | # Hacemos una espera de dos segundos para asegurarnos que
37 | # entra el hilo
38 | time.sleep(2)
39 | #Liberamos el bloqueo
40 | print "Principal: Libero bloqueo"
41 | bloqueo.release()
42 | # Espera a que termine el hilo, esperando la liberacion
43 | # del bloqueo
44 | bloqueo.acquire()
45 | bloqueo.release()
46 | print "Fin de programa"
47 |
48 |
--------------------------------------------------------------------------------
/python-hilos/src/thread_hilo_simple.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on 20/02/2009
3 | @author: Chuidiang
4 |
5 | Ejemplo de un hilo. Dos bucles, uno en un hilo y otro en
6 | el principal, contando simultaneamente.
7 | '''
8 |
9 | import thread
10 | import time
11 |
12 | # Indica si ha terminado el hilo
13 | hilo_terminado = False
14 |
15 | # Funcion que se ejecuta en un hilo
16 | def funcion (inicio, fin):
17 | global hilo_terminado
18 | # Bucle de inicio a fin, con espera de un segundo
19 | for valor in range(inicio,fin):
20 | print "Hilo : "+str(valor)
21 | time.sleep(0.1)
22 | # marca hilo terminado
23 | hilo_terminado = True
24 | print "Terminado hilo "
25 |
26 |
27 | if __name__ == '__main__':
28 | # Lanzamos un hilo
29 | thread.start_new_thread(funcion, (3,11))
30 | # y nos ponemos a contar, en paralelo con lo que haga
31 | # el hilo
32 | for i in range(1,5):
33 | print "Principal : "+str(i)
34 | time.sleep(0.1)
35 | # Espera a que termine el hilo
36 | while (not hilo_terminado):
37 | pass
38 |
39 |
--------------------------------------------------------------------------------
/python-hilos/src/threading_hilo_condition.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on 24/02/2009
3 | @author: Chuidiang
4 |
5 | Ejemplo de hilo usando Condition para esperar que haya datos
6 | diponibles. El main genera esos datos y despierta al hilo cada vez.
7 | '''
8 |
9 | from threading import Thread, Condition
10 | import time
11 |
12 | # Hilo que espera los datos.
13 | class MiHilo (Thread):
14 | # Se le pasa una lista de datos y la Condition
15 | # para espera de los mismos.
16 | def __init__(self,lista,condicion):
17 | Thread.__init__(self)
18 | self.lista = lista
19 | self.condicion = condicion
20 | # Para saber cuando terminar el hilo
21 | self.fin=False
22 |
23 | def run(self):
24 | self.condicion.acquire()
25 | # Mientras no haya que terminar
26 | while not self.fin:
27 | # Esperar por datos
28 | self.condicion.wait()
29 | # Si no hay que terminar se escriben los datos
30 | # que haya en la lista
31 | if not self.fin:
32 | while len(lista)>0:
33 | print self.lista.pop(0)
34 | self.condicion.release()
35 |
36 | if __name__ == '__main__':
37 | # Creacion de la lista, la Condition y el hilo
38 | lista =[]
39 | condicion = Condition()
40 | hilo = MiHilo(lista, condicion)
41 | hilo.start()
42 |
43 | # Bucle
44 | for i in range (0,10):
45 | # Cogemos la condicion
46 | condicion.acquire()
47 | # Ponemos un par de datos en la lista
48 | lista.append(i)
49 | lista.append("numero "+str(i))
50 | # Avisamos que estan listos
51 | condicion.notify()
52 | # Y dejamos al hilo continuar
53 | condicion.release()
54 | time.sleep(1)
55 | # Mandamos al hilo que termine
56 | hilo.fin=True
57 | condicion.acquire()
58 | condicion.notify()
59 | condicion.release()
60 |
--------------------------------------------------------------------------------
/python-hilos/src/threading_hilo_event.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on 24/02/2009
3 | @author: Chuidiang
4 |
5 | Ejemplo de hilos con evento.
6 | El main crea un Event y un hilo al que le pasa el Event.
7 | El hilo se queda esperando por el Event.
8 | El main, tras dos segundos, activa el Event, entrando el hilo
9 | '''
10 |
11 | from threading import Thread, Event
12 | import time
13 |
14 | # Hilo a arrancar
15 | class MiHilo(Thread):
16 | # Se le pasa un numero identificador del hilo y un event
17 | def __init__(self, evento):
18 | Thread.__init__(self)
19 | self.evento=evento
20 |
21 | # Espera al event
22 | def run(self):
23 | self.evento.wait()
24 | print "Entra hilo "
25 |
26 | if __name__ == '__main__':
27 | # Crea el evento
28 | evento = Event()
29 | # Arranca el hilo
30 | hilo=MiHilo(evento)
31 | hilo.start()
32 | # Espera dos segundos y activa el evento
33 | time.sleep(2)
34 | print "Hago evento.set()"
35 | evento.set()
--------------------------------------------------------------------------------
/python-hilos/src/threading_hilo_lock.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on 23/02/2009
3 | @author: Chuidiang
4 |
5 | Ejemplo simple de hilo usando la clase Thread del
6 | modulo threading y la clase Lock
7 | '''
8 |
9 | from threading import Thread, Lock
10 | import time
11 |
12 | # Hacemos una clase que herede de Thread.
13 | # Si definimos un constructor __init__(), debemos
14 | # obligatoriamente llamar al metodo __init__() de
15 | # la clase Thread. Si no hacemos constructor, no
16 | # es necesario.
17 | class MiHilo(Thread):
18 | # Se le pasa como ultimo parametro el Lock
19 | def __init__ (self, inicio, fin, bloqueo):
20 | Thread.__init__(self)
21 | self.inicio = inicio
22 | self.fin = fin
23 | self.bloqueo = bloqueo
24 |
25 | # Metodo que se ejecutara en un hilo
26 | def run (self):
27 | # Espera por Lock
28 | bloqueo.acquire()
29 | # Comienza la cuenta
30 | for i in range(self.inicio,self.fin):
31 | print "contador = "+str(i)
32 | time.sleep(0.2)
33 | bloqueo.release()
34 |
35 | # Crea el hilo y lo arranca. Luego se pone a contar
36 | if __name__ == '__main__':
37 | # Creacion del Lock y bloqueo del mismo
38 | bloqueo = Lock()
39 | bloqueo.acquire()
40 |
41 | # Arranque del hilo
42 | hilo = MiHilo(0,10, bloqueo)
43 | hilo.start()
44 |
45 | # Hacemos esperar al hilo
46 | time.sleep(1)
47 | # Un bucle
48 | for i in range (10,20):
49 | print "main = "+str(i)
50 | time.sleep(0.1)
51 |
52 | # Liberamos el bloqueo para que el hilo comience
53 | bloqueo.release()
--------------------------------------------------------------------------------
/python-hilos/src/threading_hilo_rlock.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on 23/02/2009
3 | @author: Chuidiang
4 |
5 | Ejemplo simple de hilo usando la clase Thread del
6 | modulo threading y la clase RLock
7 | '''
8 |
9 | from threading import Thread, RLock
10 | import time
11 |
12 | # Hacemos una clase que herede de Thread.
13 | # Si definimos un constructor __init__(), debemos
14 | # obligatoriamente llamar al metodo __init__() de
15 | # la clase Thread. Si no hacemos constructor, no
16 | # es necesario.
17 | class MiHilo(Thread):
18 | # Se le pasa como ultimo parametro el Lock
19 | def __init__ (self, inicio, fin, bloqueo):
20 | Thread.__init__(self)
21 | self.inicio = inicio
22 | self.fin = fin
23 | self.bloqueo = bloqueo
24 |
25 | # Metodo que se ejecutara en un hilo
26 | def run (self):
27 | # Espera por Lock
28 | bloqueo.acquire()
29 | # Comienza la cuenta
30 | for i in range(self.inicio,self.fin):
31 | print "contador = "+str(i)
32 | time.sleep(0.2)
33 | bloqueo.release()
34 |
35 | # Crea el hilo y lo arranca. Luego se pone a contar
36 | if __name__ == '__main__':
37 | # Creacion del Lock y bloqueo del mismo
38 | bloqueo = RLock()
39 | bloqueo.acquire()
40 |
41 | # Arranque del hilo
42 | hilo = MiHilo(0,10, bloqueo)
43 | hilo.start()
44 |
45 | # Hacemos esperar al hilo
46 | time.sleep(1)
47 | # Un bucle y llamamos a acquire() muchas veces
48 | for i in range (10,20):
49 | print "main = "+str(i)
50 | bloqueo.acquire()
51 | time.sleep(0.1)
52 |
53 | # Liberamos el bloqueo una sola vez, el hilo no
54 | # comienza
55 | bloqueo.release()
56 | print "El hilo todavia no ha comenzado"
57 |
58 | # LLamamos a tantos release() con acquire() antes
59 | for i in range(10,20):
60 | bloqueo.release()
--------------------------------------------------------------------------------
/python-hilos/src/threading_hilo_semaphore.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on 24/02/2009
3 | @author: Chuidiang
4 |
5 | Ejemplo de hilos con semaforos. El main prepara un semaforo que
6 | solo permite cinco hilos activos simultaneamente. El main arranca
7 | 10 hilos y les pasa el semaforo. Cada hilo espera el semaforo, un
8 | tiempo aleatorio y termina.
9 | En la salida del programa vemos que los cinco primeros hilos entran
10 | inmediatamante y segun van terminando, va entrando el siguiente
11 | '''
12 |
13 | from threading import Thread, Semaphore
14 | import time, random
15 |
16 | # Hilo a arrancar
17 | class MiHilo(Thread):
18 | # Se le pasa un numero identificador del hilo y un semaforo
19 | def __init__(self, numero_hilo, semaforo):
20 | Thread.__init__(self)
21 | self.semaforo=semaforo
22 | self.numero_hilo = numero_hilo
23 |
24 | def run(self):
25 | # Espera al semaforo
26 | semaforo.acquire()
27 | print "Entra hilo "+str(self.numero_hilo)
28 | # Pierde un tiempo aleatorio
29 | time.sleep(random.randrange(1,10,1))
30 | print "Fin hilo " + str(self.numero_hilo)
31 | # Pone verde el semaforo para el siguiente y
32 | # termina
33 | semaforo.release()
34 |
35 | if __name__ == '__main__':
36 | random.seed()
37 | # Semaforo que permite pasar a cinco simultaneamente
38 | semaforo = Semaphore(5)
39 | # Se arrancan diez hilos
40 | for i in range(0,10):
41 | hilo=MiHilo(i,semaforo)
42 | hilo.start()
43 | print "Arrancado hilo "+str(i)
--------------------------------------------------------------------------------
/python-hilos/src/threading_hilo_simple.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on 23/02/2009
3 | @author: Chuidiang
4 |
5 | Ejemplo simple de hilo usando la clase Thread del
6 | modulo threading
7 | '''
8 |
9 | from threading import Thread
10 | import time
11 |
12 | # Hacemos una clase que herede de Thread.
13 | # Si definimos un constructor __init__(), debemos
14 | # obligatoriamente llamar al metodo __init__() de
15 | # la clase Thread. Si no hacemos constructor, no
16 | # es necesario.
17 | class MiHilo(Thread):
18 | def __init__ (self, inicio, fin):
19 | Thread.__init__(self)
20 | self.inicio = inicio
21 | self.fin = fin
22 |
23 | # Metodo que se ejecutara en un hilo
24 | def run (self):
25 | for i in range(self.inicio,self.fin):
26 | print "contador = "+str(i)
27 | time.sleep(0.2)
28 |
29 | # Crea el hilo y lo arranca. Luego se pone a contar
30 | if __name__ == '__main__':
31 | # Creacion de la clase MiHilo y arranque de la misma
32 | hilo = MiHilo(0,10)
33 | hilo.start()
34 | # Un bucle
35 | for i in range (10,20):
36 | print "main = "+str(i)
37 | time.sleep(0.1)
--------------------------------------------------------------------------------
/python-socket/src/cliente.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on 20/02/2009
3 | @author: Chuidiang
4 | Ejemplo de cliente de socket.
5 | Establece conexion con el servidor, envia "hola", recibe y escribe la
6 | respuesta, espera 2 segundos, envia "adios", recibe y escribe la respuesta
7 | y cierrra la conexion
8 | '''
9 | import socket
10 | import time
11 |
12 | if __name__ == '__main__':
13 | # Se establece la conexion
14 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
15 | s.connect(("localhost", 8000))
16 |
17 | # Se envia "hola"
18 | s.send("hola")
19 |
20 | # Se recibe la respuesta y se escribe en pantalla
21 | datos = s.recv(1000)
22 | print datos
23 |
24 | # Espera de 2 segundos
25 | time.sleep(2)
26 |
27 | # Se envia "adios"
28 | s.send("adios")
29 |
30 | # Se espera respuesta, se escribe en pantalla y se cierra la
31 | # conexion
32 | datos = s.recv(1000)
33 | print datos
34 | s.close()
35 |
--------------------------------------------------------------------------------
/python-socket/src/servidor.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on 20/02/2009
3 | @author: Chuidiang
4 |
5 |
6 | Ejemplo de socket en python. Un servidor que acepta clientes.
7 | Si el cliente envia "hola", el servidor contesta "pues hola".
8 | Si el cliente envia "adios", el servidor contesta "pues adios" y
9 | cierra la conexion.
10 | El servidor no acepta multiples clientes simultaneamente.
11 | '''
12 |
13 | import socket
14 |
15 | if __name__ == '__main__':
16 | # Se prepara el servidor
17 | server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
18 | server.bind(("", 8000))
19 | server.listen(1)
20 | print "Esperando clientes..."
21 |
22 | # bucle para atender clientes
23 | while 1:
24 |
25 | # Se espera a un cliente
26 | socket_cliente, datos_cliente = server.accept()
27 |
28 | # Se escribe su informacion
29 | print "conectado "+str(datos_cliente)
30 |
31 | # Bucle indefinido hasta que el cliente envie "adios"
32 | seguir = True
33 | while seguir:
34 | # Espera por datos
35 | peticion = socket_cliente.recv(1000)
36 |
37 | # Contestacion a "hola"
38 | if ("hola"==peticion):
39 | print str(datos_cliente)+ " envia hola: contesto"
40 | socket_cliente.send("pues hola")
41 |
42 | # Contestacion y cierre a "adios"
43 | if ("adios"==peticion):
44 | print str(datos_cliente)+ " envia adios: contesto y desconecto"
45 | socket_cliente.send("pues adios")
46 | socket_cliente.close()
47 | print "desconectado "+str(datos_cliente)
48 | seguir = False
49 |
--------------------------------------------------------------------------------
/scala/camel-scala/src/main/java/com/chuidiang/ejemplos/App.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos;
2 |
3 | /**
4 | * Hello world!
5 | *
6 | */
7 | public class App
8 | {
9 | public static void main( String[] args )
10 | {
11 | System.out.println( "Hello World!" );
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/scala/camel-scala/src/main/scala/com/chuidiang/ejemplos/data/Data.scala:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.data
2 |
3 | import java.nio.ByteBuffer
4 |
5 | class Data(var value:Int, var string:String) {
6 |
7 | def getBytes() : Array[Byte] = {
8 |
9 | val buffer = ByteBuffer.allocate(4+string.getBytes.length)
10 | buffer.putInt(value)
11 | for (byte <- string.getBytes){
12 | buffer.put(byte)
13 | }
14 | println(new String(buffer.array()))
15 | buffer.array()
16 | }
17 |
18 | def fromBytes(bytes:Array[Byte]) = {
19 | val buffer = ByteBuffer.wrap(bytes)
20 | value = buffer.getInt
21 | string = new String(bytes,4,bytes.length-4)
22 |
23 | println ("value="+value)
24 | println ("string="+string)
25 | }
26 |
27 | override def toString():String = {
28 | value + " "+string
29 | }
30 |
31 | def getLength() : Int = {
32 | return 4 + string.getBytes().length
33 | }
34 | }
35 |
36 | object TestData extends App {
37 | val originalData = new Data(33,"adios")
38 | val constructedData = new Data(0,"")
39 | constructedData.fromBytes(originalData.getBytes())
40 | println ( constructedData)
41 | }
--------------------------------------------------------------------------------
/scala/camel-scala/src/main/scala/com/chuidiang/ejemplos/data/DataClientSocketExample.scala:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.data
2 |
3 | import java.io.BufferedReader
4 | import java.io.InputStreamReader
5 | import java.io.PrintWriter
6 | import java.net.Socket
7 | import java.net.SocketException
8 | import java.io.InputStream
9 |
10 | object DataClientSocketExample {
11 | def main(args: Array[String]): Unit = {
12 | new DataClient(55556)
13 | }
14 | }
15 |
16 | class DataClient(val port: Int) {
17 | val socket = new Socket("localhost", port)
18 | val reader = socket.getInputStream
19 | val writer =socket.getOutputStream
20 |
21 | new DataLectorThread(reader).start
22 |
23 | for (i <- 0 until 10) {
24 | val data = new Data(i,"Juan")
25 | val msgToSend = new Protocol(data)
26 | writer.write(msgToSend.getBytes())
27 |
28 | Thread.sleep(1000)
29 | }
30 | socket.close
31 | }
32 |
33 | class DataLectorThread(reader: InputStream) extends Thread {
34 | override def run() = {
35 | var continue = true
36 | try {
37 | while (continue) {
38 | reader.read()
39 | // val line = Option(reader.readLine())
40 | // line match {
41 | // case Some(line) => println("Client Received "+line)
42 | // case _ => continue=false; println("is null")
43 | // }
44 | }
45 | } catch {
46 | case e: SocketException => println(e.getMessage)
47 | }
48 | }
49 | }
--------------------------------------------------------------------------------
/scala/camel-scala/src/main/scala/com/chuidiang/ejemplos/data/DataDecoder.scala:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.data
2 |
3 | import org.jboss.netty.buffer.ChannelBuffer
4 | import com.chuidiang.ejemplos.data.ProtocolConstants._
5 | import org.jboss.netty.channel.Channel
6 | import org.jboss.netty.channel.ChannelHandlerContext
7 | import org.jboss.netty.handler.codec.oneone.OneToOneDecoder
8 | import com.chuidiang.ejemplos.data.ProtocolConstants._
9 |
10 | /** It converts bytes to Data */
11 | class DataDecoder() extends OneToOneDecoder {
12 |
13 |
14 |
15 | override def decode(
16 | ctx: ChannelHandlerContext, channel: Channel, msg: Object): Object = {
17 |
18 | msg match {
19 | case channelBuffer: ChannelBuffer =>
20 |
21 | val firstIndex = channelBuffer.readerIndex()
22 |
23 | var aByte = channelBuffer.readByte()
24 | while (aByte != MAGIC_NUMBER && channelBuffer.readable()) {
25 | aByte = channelBuffer.readByte()
26 | }
27 | if (aByte != MAGIC_NUMBER || channelBuffer.readableBytes() < 1) {
28 | // channelBuffer.readerIndex(firstIndex)
29 | return null;
30 | }
31 | val length = channelBuffer.readByte()
32 | if (channelBuffer.readableBytes() < length + 1) {
33 | channelBuffer.readerIndex(firstIndex)
34 | return null
35 | }
36 |
37 | val data = new Data(0, "")
38 | data.fromBytes(extractFrame(channelBuffer, channelBuffer.readerIndex(), length).array())
39 |
40 | val checksum = channelBuffer.readByte()
41 | if (checksum != getChecksum(data.getBytes())) {
42 | channelBuffer.readerIndex(firstIndex+1)
43 | return decode(ctx,channel,msg)
44 | }
45 |
46 | return data
47 |
48 | case _ => msg
49 | }
50 | return null
51 | }
52 |
53 | def extractFrame(buffer: ChannelBuffer, index: Int, length: Int): ChannelBuffer = {
54 | val frame = buffer.factory().getBuffer(length);
55 | frame.writeBytes(buffer, index, length);
56 | return frame;
57 | }
58 | }
59 |
60 |
--------------------------------------------------------------------------------
/scala/camel-scala/src/main/scala/com/chuidiang/ejemplos/data/DataEncoder.scala:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.data
2 |
3 | import org.jboss.netty.buffer.ChannelBuffer
4 | import org.jboss.netty.buffer.ChannelBuffers
5 | import org.jboss.netty.channel.Channel
6 | import org.jboss.netty.channel.ChannelHandlerContext
7 | import org.jboss.netty.handler.codec.oneone.OneToOneEncoder
8 |
9 | class DataEncoder() extends OneToOneEncoder {
10 | override def encode(
11 | ctx:ChannelHandlerContext, channel:Channel, msg:Object):Object = {
12 | msg match {
13 | case data:Data => createChannel(data)
14 | case _ => throw new NullPointerException("Data expected")
15 | }
16 | }
17 |
18 | def createChannel(data:Data): ChannelBuffer = {
19 | val bytes = Array[Byte](33.toByte, data.getLength().toByte)
20 | bytes :+ data.getBytes()
21 | bytes :+ ProtocolConstants.getChecksum(data.getBytes())
22 | ChannelBuffers.wrappedBuffer(bytes)
23 | }
24 | }
--------------------------------------------------------------------------------
/scala/camel-scala/src/main/scala/com/chuidiang/ejemplos/data/DataExample.scala:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.data
2 |
3 | import org.apache.camel.builder.RouteBuilder
4 | import org.apache.camel.impl.DefaultCamelContext
5 | import org.apache.camel.impl.SimpleRegistry
6 | import org.apache.log4j.BasicConfigurator
7 | import org.apache.log4j.Logger
8 | import org.apache.log4j.Level
9 |
10 | object DataExample extends App {
11 | BasicConfigurator.configure()
12 | Logger.getRootLogger.setLevel(Level.INFO)
13 | val registry = new SimpleRegistry;
14 | registry.put("FromDecoder", new DataDecoder)
15 | registry.put("FromEncoder", new DataEncoder)
16 | registry.put("ToDecoder", new DataDecoder)
17 | registry.put("ToEncoder", new DataEncoder)
18 |
19 | val camelContext = new DefaultCamelContext(registry)
20 |
21 | camelContext.addRoutes(new RouteBuilder {
22 | override def configure : Unit = {
23 | from("netty:tcp://localhost:55556?decoder=#FromDecoder&encoder=#FromEncoder").to(
24 | // from("netty:tcp://localhost:55556?textline=true").to(
25 | "netty:tcp://localhost:55558?decoder=#ToDecoder&encoder=#ToEncoder")
26 | // from("netty:tcp://localhost:55556?textline=true") to "netty:tcp://localhost:55558?textline=true"
27 | }
28 | })
29 | camelContext.start
30 | Console.in.read()
31 | }
32 |
33 |
--------------------------------------------------------------------------------
/scala/camel-scala/src/main/scala/com/chuidiang/ejemplos/data/Util.scala:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.data
2 |
3 | import java.nio.ByteBuffer
4 |
5 |
6 | object Util {
7 | }
--------------------------------------------------------------------------------
/scala/camel-scala/src/main/scala/com/chuidiang/ejemplos/string/CamelExample.scala:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.string
2 |
3 | import org.apache.camel.builder.RouteBuilder
4 | import org.apache.camel.impl.DefaultCamelContext
5 | import org.apache.camel.impl.SimpleRegistry
6 | import org.apache.log4j.BasicConfigurator
7 | import org.apache.log4j.Logger
8 | import org.apache.log4j.Level
9 |
10 | object CamelExample extends App {
11 | BasicConfigurator.configure()
12 | Logger.getRootLogger.setLevel(Level.INFO)
13 | val registry = new SimpleRegistry;
14 | registry.put("FromDecoder", new CustomDecoder("FromDecoder"))
15 | registry.put("FromEncoder", new CustomEncoder("FromEncoder"))
16 | registry.put("ToDecoder", new CustomDecoder("ToDecoder"))
17 | registry.put("ToEncoder", new CustomEncoder("ToEncoder"))
18 |
19 | val camelContext = new DefaultCamelContext(registry)
20 |
21 | camelContext.addRoutes(new RouteBuilder {
22 | override def configure : Unit = {
23 | from("netty:tcp://localhost:55556?decoder=#FromDecoder&encoder=#FromEncoder").to(
24 | // from("netty:tcp://localhost:55556?textline=true").to(
25 | "netty:tcp://localhost:55558?decoder=#ToDecoder&encoder=#ToEncoder")
26 | // from("netty:tcp://localhost:55556?textline=true") to "netty:tcp://localhost:55558?textline=true"
27 | }
28 | })
29 | camelContext.start
30 | Console.in.read()
31 | }
32 |
33 |
--------------------------------------------------------------------------------
/scala/camel-scala/src/main/scala/com/chuidiang/ejemplos/string/CustomDecoder.scala:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.string
2 |
3 | import org.jboss.netty.handler.codec.oneone.OneToOneDecoder
4 | import org.jboss.netty.channel.ChannelHandlerContext
5 | import org.jboss.netty.channel.Channel
6 | import org.jboss.netty.buffer.ChannelBuffer
7 | import java.nio.charset.Charset
8 | import org.apache.camel.component.netty.ChannelHandlerFactory
9 | import org.jboss.netty.channel.ChannelHandler
10 |
11 | /** It converts bytes to String */
12 | class CustomDecoder(val name: String) extends OneToOneDecoder with ChannelHandlerFactory {
13 | override def decode(
14 | ctx: ChannelHandlerContext, channel: Channel, msg: Object): Object = {
15 | println(name + " -> " + msg)
16 | msg match {
17 | case channel: ChannelBuffer =>
18 | var eolPosition = channel.indexOf(channel.readerIndex(), channel.writerIndex(), '\n'.toByte)
19 | if (eolPosition > -1) {
20 | val length = eolPosition - channel.readerIndex()
21 | val frame = extractFrame(channel, channel.readerIndex(), length - 1)
22 | channel.skipBytes(length + 1)
23 | println(name + " Sending " + frame.toString(Charset.defaultCharset()))
24 | return frame.toString(Charset.defaultCharset())
25 | }
26 | return null
27 |
28 | channel.toString(Charset.defaultCharset())
29 | case _ => msg
30 | }
31 | }
32 |
33 | override def newChannelHandler(): ChannelHandler = {
34 | new CustomDecoder(name)
35 | }
36 |
37 | def extractFrame(buffer: ChannelBuffer, index: Int, length: Int): ChannelBuffer = {
38 | val frame = buffer.factory().getBuffer(length);
39 | frame.writeBytes(buffer, index, length);
40 | return frame;
41 | }
42 | }
43 |
44 |
--------------------------------------------------------------------------------
/scala/camel-scala/src/main/scala/com/chuidiang/ejemplos/string/CustomEncoder.scala:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.string
2 |
3 | import java.nio.ByteOrder
4 | import org.jboss.netty.buffer.BigEndianHeapChannelBuffer
5 | import org.jboss.netty.buffer.ChannelBuffer
6 | import org.jboss.netty.buffer.LittleEndianHeapChannelBuffer
7 | import org.jboss.netty.channel.Channel
8 | import org.jboss.netty.channel.ChannelHandlerContext
9 | import org.jboss.netty.handler.codec.oneone.OneToOneEncoder
10 | import org.jboss.netty.channel.ChannelHandler
11 | import org.apache.camel.component.netty.ChannelHandlerFactory
12 |
13 | class CustomEncoder(val name:String) extends OneToOneEncoder with ChannelHandlerFactory {
14 | override def encode(
15 | ctx:ChannelHandlerContext, channel:Channel, msg:Object):Object = {
16 | println(name+" -> "+msg)
17 | val endian = ctx.getChannel().getConfig().getBufferFactory().getDefaultOrder()
18 | msg match {
19 | case string:String => createChannel(string,endian)
20 | case bigEndian:BigEndianHeapChannelBuffer => bigEndian
21 | case _ => throw new NullPointerException("string")
22 | }
23 | }
24 |
25 | def createChannel(string:String, endian:ByteOrder): ChannelBuffer = {
26 | if (endian == ByteOrder.BIG_ENDIAN){
27 | return new BigEndianHeapChannelBuffer((string+"\r\n").getBytes)
28 | }
29 | return new LittleEndianHeapChannelBuffer((string+"\r\n").getBytes)
30 | }
31 | override def newChannelHandler() : ChannelHandler = {
32 | new CustomEncoder(name)
33 | }
34 | }
--------------------------------------------------------------------------------
/scala/camel-scala/src/main/scala/com/chuidiang/ejemplos/string/CustomFrameDecoder.scala:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.string
2 |
3 | import org.jboss.netty.buffer.ChannelBuffer
4 | import org.jboss.netty.channel.Channel
5 | import org.jboss.netty.channel.ChannelHandlerContext
6 | import org.jboss.netty.handler.codec.frame.FrameDecoder
7 | import java.nio.charset.Charset
8 | import org.jboss.netty.channel.ChannelHandler
9 | import org.apache.camel.component.netty.ChannelHandlerFactory
10 |
11 | class CustomFrameDecoder(val name:String) extends FrameDecoder with ChannelHandlerFactory {
12 | override def decode(ctx: ChannelHandlerContext, channel: Channel, buffer: ChannelBuffer): Object = {
13 | println(name+" -> "+buffer)
14 | var eolPosition = buffer.indexOf(buffer.readerIndex(), buffer.writerIndex(), '\n'.toByte)
15 | if (eolPosition > -1) {
16 | val length = eolPosition - buffer.readerIndex()
17 | val frame = extractFrame(buffer, buffer.readerIndex(), length - 1)
18 | buffer.skipBytes(length + 1)
19 | println(name + " Sending " + frame.toString(Charset.defaultCharset()))
20 | return frame.toString(Charset.defaultCharset())
21 | }
22 | return null
23 | }
24 |
25 | override def newChannelHandler() : ChannelHandler = {
26 | new CustomFrameDecoder(name)
27 | }
28 |
29 | }
--------------------------------------------------------------------------------
/scala/camel-scala/src/main/scala/com/chuidiang/ejemplos/string/ScalaClientSocketExample.scala:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.string
2 |
3 | import java.io.BufferedReader
4 | import java.io.InputStreamReader
5 | import java.io.PrintWriter
6 | import java.net.Socket
7 | import java.net.SocketException
8 |
9 | object ScalaClientSocketExample {
10 | def main(args: Array[String]): Unit = {
11 | new Client(55556)
12 | }
13 | }
14 |
15 | class Client(val port: Int) {
16 | val socket = new Socket("localhost", port)
17 | val reader = new BufferedReader(new InputStreamReader(socket.getInputStream))
18 | val writer = new PrintWriter(socket.getOutputStream)
19 |
20 | new LectorThread(reader).start
21 |
22 | for (i <- 0 until 10) {
23 | writer.println("Juan" + i)
24 | writer.flush
25 | Thread.sleep(1000)
26 | }
27 | socket.close
28 | }
29 |
30 | class LectorThread(reader: BufferedReader) extends Thread {
31 | override def run() = {
32 | var continue = true
33 | try {
34 | while (continue) {
35 | val line = Option(reader.readLine())
36 | line match {
37 | case Some(line) => println("Client Received "+line)
38 | case _ => continue=false; println("is null")
39 | }
40 | }
41 | } catch {
42 | case e: SocketException => println(e.getMessage)
43 | }
44 | }
45 | }
--------------------------------------------------------------------------------
/scala/camel-scala/src/main/scala/com/chuidiang/ejemplos/string/ScalaServerSocketExample.scala:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos.string
2 |
3 | import java.net._
4 | import java.io.BufferedReader
5 | import java.io.InputStreamReader
6 | import java.io.PrintWriter
7 |
8 | object ScalaServerSocketExample {
9 | def main(args: Array[String]): Unit = {
10 | new Server(55558).start
11 | }
12 | }
13 |
14 | class ClientThread(private val socket: Socket) extends Thread {
15 |
16 | override def run() = {
17 | val reader = new BufferedReader(new InputStreamReader(socket.getInputStream))
18 | val writer = new PrintWriter(socket.getOutputStream)
19 | val thread = new ServerLectorThread(reader, writer)
20 | thread.start
21 | thread.join
22 | socket.close
23 | }
24 | }
25 |
26 | class Server(val port: Int) extends Thread {
27 | override def run = {
28 | val serverSocket = new ServerSocket(port)
29 | while (true) {
30 | val socket = serverSocket.accept
31 | new ClientThread(socket).start
32 | }
33 | }
34 | }
35 |
36 | class ServerLectorThread(reader: BufferedReader, writer: PrintWriter) extends Thread {
37 | override def run() = {
38 | var line: String = null
39 | while ((line = reader.readLine()) != null) {
40 | println("Received " + line)
41 | writer.println("Hello " + line + "!")
42 | writer.flush
43 | }
44 | }
45 | }
--------------------------------------------------------------------------------
/scala/camel-scala/src/test/java/com/chuidiang/ejemplos/AppTest.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos;
2 |
3 | import junit.framework.Test;
4 | import junit.framework.TestCase;
5 | import junit.framework.TestSuite;
6 |
7 | /**
8 | * Unit test for simple App.
9 | */
10 | public class AppTest
11 | extends TestCase
12 | {
13 | /**
14 | * Create the test case
15 | *
16 | * @param testName name of the test case
17 | */
18 | public AppTest( String testName )
19 | {
20 | super( testName );
21 | }
22 |
23 | /**
24 | * @return the suite of tests being tested
25 | */
26 | public static Test suite()
27 | {
28 | return new TestSuite( AppTest.class );
29 | }
30 |
31 | /**
32 | * Rigourous Test :-)
33 | */
34 | public void testApp()
35 | {
36 | assertTrue( true );
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/scala/maven-scala/src/main/java/com/chuidiang/ejemplos/App.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos;
2 |
3 | /**
4 | * Hello world!
5 | *
6 | */
7 | public class App
8 | {
9 | public static void main( String[] args )
10 | {
11 | System.out.println( "Hello World!" );
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/scala/maven-scala/src/main/scala/Hello.scala:
--------------------------------------------------------------------------------
1 | object Hello {
2 | def main (args: Array[String]): Unit = {
3 | println("Hello!!")
4 | }
5 | }
6 |
7 | class Adder {
8 | def add (a:Double, b:Double) : Double = a+b
9 | }
10 |
--------------------------------------------------------------------------------
/scala/maven-scala/src/test/java/com/chuidiang/ejemplos/AppTest.java:
--------------------------------------------------------------------------------
1 | package com.chuidiang.ejemplos;
2 |
3 | import junit.framework.Test;
4 | import junit.framework.TestCase;
5 | import junit.framework.TestSuite;
6 |
7 | /**
8 | * Unit test for simple App.
9 | */
10 | public class AppTest
11 | extends TestCase
12 | {
13 | /**
14 | * Create the test case
15 | *
16 | * @param testName name of the test case
17 | */
18 | public AppTest( String testName )
19 | {
20 | super( testName );
21 | }
22 |
23 | /**
24 | * @return the suite of tests being tested
25 | */
26 | public static Test suite()
27 | {
28 | return new TestSuite( AppTest.class );
29 | }
30 |
31 | /**
32 | * Rigourous Test :-)
33 | */
34 | public void testApp()
35 | {
36 | assertTrue( true );
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/scala/maven-scala/src/test/scala/HelloTest.scala:
--------------------------------------------------------------------------------
1 |
2 |
3 | import org.scalatest._
4 | import org.scalatest.Matchers
5 |
6 | /*
7 | * @author Chuidiang
8 | */
9 | class HelloTest extends FlatSpec with Matchers {
10 | "The sum 1+4" should "be 5 " in {
11 | var a = new Adder
12 | a.add(1.0,4.0) should be (5)
13 | }
14 |
15 | "The sum 3+3" should "be 6 " in {
16 | var a = new Adder
17 | a.add(3,3) should be (6)
18 | }
19 | }
--------------------------------------------------------------------------------