1. Insertar un LinearLayout (horizontal)
2. Agregar dos botones
3. A un boton, ponerle layout:width: 0 y layout:weight: .80
4. Al otro ponerle layout:width: 0 y layout:weight: .20
Cambiar el estilo de la aplicacion en Android Studio
Editar el archivo \src\main\res\values\styles.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="android:Theme.Light">
<!-- Customize your theme here. -->
</style>
</resources>
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="android:Theme.Light">
<!-- Customize your theme here. -->
</style>
</resources>
Barcode scanner con ZBarScanner en Android Studio
[El codigo fuente esta en Google Drive, en la carpeta Android Studio]
https://github.com/dm77/ZBarScanner
https://github.com/dm77/ZBarScanner
Ejemplo de lista clickeable con Android Studio
package com.example.crusso_pc.app1;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MyActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
ListView lv = (ListView) findViewById(R.id.lista1);
String[] values = new String[] { "Android List View",
"Adapter implementation",
"Simple List View In Android",
"Create List View Android",
"Android Example",
"List View Source Code",
"List View Array Adapter",
"Android Example List View"
};
/* Tambien se puede hacer con arrraylists!
ArrayList<String> values =
new ArrayList<String>();
values.add(matricula);
values.add("matricula1");
values.add("matricula2");
values.add("matricula3");
values.add("matricula4");
*/
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parentAdapter, View view, int position,
long id) {
// We know the View is a TextView so we can cast it
TextView clickedView = (TextView) view;
Toast.makeText(MyActivity.this, "Item with id [" + id + "] - Position [" + position + "] - Planet [" + clickedView.getText() + "]", Toast.LENGTH_SHORT).show();
}
});
}
}
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MyActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
ListView lv = (ListView) findViewById(R.id.lista1);
String[] values = new String[] { "Android List View",
"Adapter implementation",
"Simple List View In Android",
"Create List View Android",
"Android Example",
"List View Source Code",
"List View Array Adapter",
"Android Example List View"
};
/* Tambien se puede hacer con arrraylists!
ArrayList<String> values =
new ArrayList<String>();
values.add(matricula);
values.add("matricula1");
values.add("matricula2");
values.add("matricula3");
values.add("matricula4");
*/
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parentAdapter, View view, int position,
long id) {
// We know the View is a TextView so we can cast it
TextView clickedView = (TextView) view;
Toast.makeText(MyActivity.this, "Item with id [" + id + "] - Position [" + position + "] - Planet [" + clickedView.getText() + "]", Toast.LENGTH_SHORT).show();
}
});
}
}
Android Studio 0.8.1 - step by step
1. Ir al SDK manager, ejecutando c:\android-studio\sdk\tools\android.bat (invocar el SDK manager asi
evita el error "sdk manager a folder failed to be moved")
2. Instalar Android 4.1.2 (api 16) y las android sdk tools, sdk platform-tools y sdk build-tools
3. Crear un nuevo AVD (Android virtual device) con estos settings
Device: Nexus 4
Target: Android 4.1.2 - API Level 16
CPU/ABI: ARM (armeabi-v7a)
Skin: Skin with dynamic hardware controls
5. Abrir el android studio, crear un nuevo proyecto con la version de SDK 16.
6. El apk lo genera automaticamente en esta ruta
C:\Users\CRUSSO_PC\AndroidStudioProjects\App1\app\build\outputs\apk\app-debug.apk
(se puede pasar al cel e instalarla)
(Si un componente (ej, calendarView) no se puede usar por un problema con la version de SDK:
Ir al archivo AndroidManifest.xml (en la raiz del proyecto), y hacer click en "uses sdk",
y cambiar la "min sdk version" a 11 por ej.
evita el error "sdk manager a folder failed to be moved")
2. Instalar Android 4.1.2 (api 16) y las android sdk tools, sdk platform-tools y sdk build-tools
3. Crear un nuevo AVD (Android virtual device) con estos settings
Device: Nexus 4
Target: Android 4.1.2 - API Level 16
CPU/ABI: ARM (armeabi-v7a)
Skin: Skin with dynamic hardware controls
5. Abrir el android studio, crear un nuevo proyecto con la version de SDK 16.
6. El apk lo genera automaticamente en esta ruta
C:\Users\CRUSSO_PC\AndroidStudioProjects\App1\app\build\outputs\apk\app-debug.apk
(se puede pasar al cel e instalarla)
(Si un componente (ej, calendarView) no se puede usar por un problema con la version de SDK:
Ir al archivo AndroidManifest.xml (en la raiz del proyecto), y hacer click en "uses sdk",
y cambiar la "min sdk version" a 11 por ej.
Obtener cotizaciones de Mercado Libre con gson
package PaqueteAplicacion;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import com.google.gson.Gson;
public class Aplicacion {
public static void main(String[] args) throws MalformedURLException, IOException {
String uri = "https://api.mercadolibre.com/currency_conversions/search?from=USD&to=UYU";
URL url = new URL(uri);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/json");
if (connection.getResponseCode() != 200) {
throw new RuntimeException("Error : HTTP error code : "
+ connection.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(connection.getInputStream())));
String output = br.readLine();
Gson gson = new Gson();
Cotizacion person = gson.fromJson(output, Cotizacion.class);
System.out.println(person.getRatio());
connection.disconnect();
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import com.google.gson.Gson;
public class Aplicacion {
public static void main(String[] args) throws MalformedURLException, IOException {
String uri = "https://api.mercadolibre.com/currency_conversions/search?from=USD&to=UYU";
URL url = new URL(uri);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/json");
if (connection.getResponseCode() != 200) {
throw new RuntimeException("Error : HTTP error code : "
+ connection.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(connection.getInputStream())));
String output = br.readLine();
Gson gson = new Gson();
Cotizacion person = gson.fromJson(output, Cotizacion.class);
System.out.println(person.getRatio());
connection.disconnect();
}
}
package PaqueteAplicacion;
import java.math.BigDecimal;
public class Cotizacion {
private BigDecimal ratio;
private String mercado_pago_ratio;
public BigDecimal getRatio() {
return ratio;
}
public void setRatio(BigDecimal ratio) {
this.ratio = ratio;
}
public String getMercado_pago_ratio() {
return mercado_pago_ratio;
}
public void setMercado_pago_ratio(String mercado_pago_ratio) {
this.mercado_pago_ratio = mercado_pago_ratio;
}
}
Ejemplos de archivos de configuracion correctos en Java EE
C:\_KARINA\Fuentes\Obligatorio\AppAchilles\AppAchilles-ejb\setup\glassfish-resources.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE resources PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 Resource Definitions//EN" "http://glassfish.org/dtds/glassfish-resources_1_5.dtd">
<resources>
<jdbc-connection-pool allow-non-component-callers="false" associate-with-thread="false" connection-creation-retry-attempts="0" connection-creation-retry-interval-in-seconds="10" connection-leak-reclaim="false" connection-leak-timeout-in-seconds="0" connection-validation-method="auto-commit" datasource-classname="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" fail-all-connections="false" idle-timeout-in-seconds="300" is-connection-validation-required="false" is-isolation-level-guaranteed="true" lazy-connection-association="false" lazy-connection-enlistment="false" match-connections="false" max-connection-usage-count="0" max-pool-size="32" max-wait-time-in-millis="60000" name="pool-achilles" non-transactional-connections="false" pool-resize-quantity="2" res-type="javax.sql.DataSource" statement-timeout-in-seconds="-1" steady-pool-size="8" validate-atmost-once-period-in-seconds="0" wrap-jdbc-objects="false">
<property name="serverName" value="localhost"/>
<property name="portNumber" value="3306"/>
<property name="databaseName" value="achilles"/>
<property name="User" value="root"/>
<property name="Password" value="root"/>
<property name="URL" value="jdbc:mysql://localhost:3306/achilles?zeroDateTimeBehavior=convertToNull"/>
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
</jdbc-connection-pool>
<jdbc-resource enabled="true" jndi-name="jdbc/achilles" object-type="user" pool-name="pool-achilles"/>
</resources>
C:\_KARINA\Fuentes\Obligatorio\AppAchilles\AppAchilles-ejb\src\conf\persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="AppAchillesPU" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>jdbc/achilles</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
</properties>
</persistence-unit>
</persistence>
RESTful web services con NetBeans 7.4
1. Crear un Enterprise Application (File / New Project / Java Web / Web Application)
2. Crear una Web Application (File / New Project / Java EE / Enterprise Application) [elegir como Enterprise Application la creada en el paso 1)
3. Sobre el Web Application, click derecho y New / RESTful Web Services from Patterns...
4. Simple Root Resource
5. Como nombre de package, uy.com.prueba.servicios
6. Ingresar el Path (ej /servicio1)
7. Ingresar el nombre de la clase (ej, PruebaResource)
8. Elegir el mime type (ej, text/plain)
9. En el metodo que esta debajo del @GET, agregar el codigo
return "hola";
10. Boton derecho en el web application, y deploy.
11. Ir a un browser y poner
http://localhost:8080/WebApplication2/webresources/servicio1
2. Crear una Web Application (File / New Project / Java EE / Enterprise Application) [elegir como Enterprise Application la creada en el paso 1)
3. Sobre el Web Application, click derecho y New / RESTful Web Services from Patterns...
4. Simple Root Resource
5. Como nombre de package, uy.com.prueba.servicios
6. Ingresar el Path (ej /servicio1)
7. Ingresar el nombre de la clase (ej, PruebaResource)
8. Elegir el mime type (ej, text/plain)
9. En el metodo que esta debajo del @GET, agregar el codigo
return "hola";
10. Boton derecho en el web application, y deploy.
11. Ir a un browser y poner
http://localhost:8080/WebApplication2/webresources/servicio1
Ejemplos de JPA - Guia #2 [COMPLETA]
0. Crear la base de datos achilles (ir a Inicio / Programas / MySql / MySql Server 5.6 / MySql 5.6 Command Line Client
Poner el password (root)
Poner Show Databases; (enter)
Si ya no existe achilles,
Create Database achilles;
exit
1. Creo el AppAchilles y dejo marcado que cree el modulo EJB
2. Creo el dominio (desmarco que cree la main class)
3. Creo la clase Categoria, y le pongo como package: uy.com.achilles.dominio
4. En la ficha Services, crear una nueva coneccion a la base achilles (poner root root en el usr y pwd)
5. Sobre el EJB crear un persistence unit (OJO!! A LA CONEXION NOMBRARLA ASI: java:app/achilles (SINO, FALLA EL DEPLOY)
6. Sobre el EJB, new / entity class (nombre CategoriaEntity, y package uy.com.achilles.entidades)
7. Agregar los atributos en la entidad creada (para eso ver los que estan en el dominio y copiarlos)
8. Agregar los decoradores que falten para los nombres de las tablas, campos, etc (@Table(name="CATEGORIA"), @OneToOne, etc)
9. Hacer Clean and Build de AppAchilles
10. Hacer Deploy de AppAchilles
Va a dar un error: SEVERE: Exception while deploying the app [AppAchilles] : Application [AppAchilles] contains no valid components
[ESTO ES PORQUE EL EJB NO TIENE NINGUN SESSION BEAN!!!]
11. Crear un session bean dentro del EJB
12. Hacer clean and build del EJB
13. Hacer deploy del EJB
[SI NO CREA LAS TABLAS ES PORQUE ES NECESARIO IMPLEMENTAR EL SESSION BEAN!!! AHI ES DONDE SE ESPECIFICA EL PERSISTENCE CONTEXT]
14. Crear el Session Bean (stateless, local)
15. Crear un Web Service dentrod de EJB (elegir la opcion de crearlo a partir de un SB existente)
16. Crear una nueva java app. llamada ClientePrueba
17. Dentro de ella, crear un webservice client, que apunte al WSDL del servicio creado en el paso 15.
18. Agregar el codigo:
CategoriaWS port = new CategoriaWS_Service().getCategoriaWSPort();
Categoria cat = new Categoria();
cat.setId(new Long(1));
cat.setNombre("categoria1");
cat.setDimensiones("10x10x10");
cat.setNotas("Notas cat 1");
port.alta(cat);
Poner el password (root)
Poner Show Databases; (enter)
Si ya no existe achilles,
Create Database achilles;
exit
1. Creo el AppAchilles y dejo marcado que cree el modulo EJB
2. Creo el dominio (desmarco que cree la main class)
3. Creo la clase Categoria, y le pongo como package: uy.com.achilles.dominio
4. En la ficha Services, crear una nueva coneccion a la base achilles (poner root root en el usr y pwd)
5. Sobre el EJB crear un persistence unit (OJO!! A LA CONEXION NOMBRARLA ASI: java:app/achilles (SINO, FALLA EL DEPLOY)
6. Sobre el EJB, new / entity class (nombre CategoriaEntity, y package uy.com.achilles.entidades)
7. Agregar los atributos en la entidad creada (para eso ver los que estan en el dominio y copiarlos)
8. Agregar los decoradores que falten para los nombres de las tablas, campos, etc (@Table(name="CATEGORIA"), @OneToOne, etc)
9. Hacer Clean and Build de AppAchilles
10. Hacer Deploy de AppAchilles
Va a dar un error: SEVERE: Exception while deploying the app [AppAchilles] : Application [AppAchilles] contains no valid components
[ESTO ES PORQUE EL EJB NO TIENE NINGUN SESSION BEAN!!!]
11. Crear un session bean dentro del EJB
12. Hacer clean and build del EJB
13. Hacer deploy del EJB
[SI NO CREA LAS TABLAS ES PORQUE ES NECESARIO IMPLEMENTAR EL SESSION BEAN!!! AHI ES DONDE SE ESPECIFICA EL PERSISTENCE CONTEXT]
14. Crear el Session Bean (stateless, local)
15. Crear un Web Service dentrod de EJB (elegir la opcion de crearlo a partir de un SB existente)
16. Crear una nueva java app. llamada ClientePrueba
17. Dentro de ella, crear un webservice client, que apunte al WSDL del servicio creado en el paso 15.
18. Agregar el codigo:
CategoriaWS port = new CategoriaWS_Service().getCategoriaWSPort();
Categoria cat = new Categoria();
cat.setId(new Long(1));
cat.setNombre("categoria1");
cat.setDimensiones("10x10x10");
cat.setNotas("Notas cat 1");
port.alta(cat);
Cargar dropdownlist combo en MVC con una lista desde LINQ
@Html.DropDownListFor(m => m.Cheque.Bancos, new SelectList(Model.Cheque.Bancos, "Value", "Text"))
Cheque chq = new Cheque();
chq.Bancos = CargarBancos();
private IEnumerable<SelectListItem> CargarBancos()
{
IEnumerable<SelectListItem> ll;
using (var db = new X_XEntities())
{
var b = from t in db.BCT_DES
where t.TIPDESTAB == 5
select new { t.CODDESTAB, t.DESCORTAB };
ll = b.Select(aa => new SelectListItem
{
Text = aa.DESCORTAB,
Value = aa.CODDESTAB.ToString()
}).ToList();
}
return ll;
}
Ejemplos de JPA - Guia #1
http://wiki.netbeans.org/SimpleJPAApplicationWithNetbeans
EJEMPLO DE JPA
==============
1. Crear Enterprise Application (AppGestionPersona) [desmarcar Create EJB module y Create web app module]
2. Crear dominio con nombre Dominio.java (java application), desmarcar "Create Main Class" [Agregar el CODIGO 0]
3. Crear paquete uy.edu.ort.dominio (en el proyecto creado anteriormente)
4. Crear clase Persona dentro del paquete recien creado.
5. Crear un modulo EJB (Nombre: AppGestionPersonaPersistencia-ejb) y agregarlo al enterprise application creado anteriormente.
6. Agregar la libreria EclipseLink (click derecho en Libraries dentro del EJB y Add Library...)
7. Agregar el mysql-connector-java-5.1.13-bin.jar (click derecho en Libraries dentro del EJB y Add JAR/Folder...)
8. Agregar el proyecto Dominio (click derecho en Libraries dentro del EJB y Add Project... y elegir Dominio)
9. Crear la base de datos en MySql (nombre prueba1)
10. Crear una conexion a la base de datos:
Click en la ficha Services
Click derecho en Databases / New Connection
Elegir el driver MySql
Poner los parametros de acceso a la bd (usuario root, pwd root, y el nombre de la base de datos prueba1)
11. Crear un Persistence Unit (Click derecho sobre AppGestionPersonaPersistencia-ejb, New / Other / Persistence
12. Ponerle nombre GestionPersonaPU y elegir como Persistence Provider: EclipseLink (JPA...)
13. En data source, poner New Data Source...
14. Ponerle nombre: jdbc/prueba
15. En el combo de Database Connection, elegir la conexion creada anteriormente
16. En Table Generation Strategy marcar Drop and Create
[[PARA BORRAR CONEXIONES YA EXISTENTES:
a. Editar el archivo glassfish-resources.xml (ubicado dentro de la carpeta setup de la ruta donde esta el ejb)
b. Borrar la linea que dice jdbc-resource...
c. Ir al Enterprise Beans, en la ficha Services, en Databases, ubicar la conexion, hacerle Disconnect y luego borrarla.
]]
CREACION DEL ENTITY BEAN
========================
17. Crear un paquete uy.edu.ort.gestion.persona.entidades (click derecho sobre el ejb, New / Java Package... y luego Finish)
18. Sobre el paquete recien creado, boton derecho, New / Entity Class, y en class name, poner PersonaEntity
19. Editar el PersonaEntity.java recien creado y agregar este codigo en los imports (arriba del todo):
import javax.persistence.Table;
import javax.persistence.Column;
20. Agregar el codigo de la Entity Personas [CODIGO 1]
CREACION DEL SESION BEAN
========================
21. Crear el paquete uy.edu.ort.gestion.persona.negocio (click derecho sobre el ejb, New / Java Package... y luego Finish)
22. Crear un session bean PersonaSB, de tipo Stateless e interfaz Local (click derecho en el paquete creado en el paso anterior, New /
Session Bean)
23. ESTE PASO CREA DOS FUENTES: PersonaSB.java y PersonaSBLocal.java. Este ultimo es la interfaz.
24. Agregar el codigo a la interfaz (PersonaSBLocal.java) [CODIGO 2] (OBSERVAR EN EL CODIGO QUE HAY QUE HACER UN IMPORTS
DE LA CLASE PERSONA, PORQUE SINO NO SE PUEDE USAR EL OBJETO PERSONA)
25. Agregar el codigo al Session Bean (PersonaSB.java). [CODIGO 3]
CREACION DEL WEB SERVICE
========================
EN ESTE PASO SE CREA UN WEB SERVICE A PARTIR DE LOS METODOS DEL SESSION BEAN
26. Crear el paquete uy.edu.ort.gestion.persona.ws (click derecho sobre el EJB, New / Java Package... y luego Finish)
27. Click derecho en el paquete recien creado, New / Web Service
28. Ponerle nombre PersonaWS
29. Marcar Create Web Service from Existing Session Bean y luego dar Browse, y elegir PersonaSB (esto crea el codigo automaticamente en
base a lo que tenga el Session Bean)
DEPLOY
======
30. Click derecho sobre la Enterprise Application (AppGestionPersona) y luego Clean and Build.
Si dice BUILD SUCCESSFUL...
31. Click derecho sobre la AppGestionPersona, y luego DEPLOY.
VERIFICACION DEL DEPLOY
=======================
Para ver si el deploy quedo bien:
32. Abrir el administrador de glassfish (http://localhost:4848) [LOCALHOST O LA DIRECCION DONDE ESTE EL SERVIDOR GLASSFISH!!]
33. Click en Applications... Tiene que aparecer AppGestionPersona
34. Click en AppGestionPersona
35. Click en View Endpoint (abajo a la derecha)
36. Click en /PersonaWS/PersonaWS?Tester
37. Click en http://direccion_que_aparezca:8080/PersonaWS/PersonaWS?Tester
[CREAR UN CLIENTE PARA PROBAR LA APLICACION]
38. Crear un paquete dentro de ClientePrueba que se llame uy.edu.ort.cliente
39. Crear un nuevo proyecto en NetBeans (menu File / New Project / Java / Java Application)
40. Llamarlo ClientePrueba y dejar marcada la opcion "Create Main Class". En el nombre del main class poner uy.edu.ort.cliente.ClientePrueba (esto ya crea el paquete y deja el .java ahi adentro)
41. Agregar el [CODIGO 4]
42. Sobre el paquete donde esta el ClientePrueba.java, click derecho y crear un Cliente Web Service con la WSDL generada anteriormente [para saber la wsdl se puede ir al servidor glassfish]. Para esto marcar WSDL URL e indicar la url del wsdl:
http://localhost:8080/PersonaWS/PersonaWS?wsdl
[ESTA URL SE PUEDE VER EN EL ADMIN DE GLASSFISH]
43. Elegir el paquete donde estara el webservice (uy.edu.ort.cliente)
PARA PROBAR EL CLIENTE, CLICK DERECHO SOBRE ClientePrueba.java, y Run.
[CODIGO 0]
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package uy.edu.ort.dominio;
/**
*
* @author CRUSSO_PC
*/
public class Persona {
private long id;
private String nombre;
private String apellido;
private String direccion;
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getApellido(){
return apellido;
}
public void setApellido(String apellido) {
this.apellido = apellido;
}
public String getDireccion(){
return direccion;
}
public void setDireccion(String direccion)
{
this.direccion = direccion;
}
}
[CODIGO 1]
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package uy.edu.ort.gestion.persona.entidades;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
*
* @author CRUSSO_PC
*/
@Entity
@Table(name="PERSONAS")
public class PersonaEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="ID")
private Long id;
@Column(name="NOMBRE", nullable=false)
private String nombre;
@Column(name="APELLIDO", nullable=false)
private String apellido;
@Column(name="DIRECCION", nullable=false)
private String direccion;
public Long getId() {
return id;
}
public String getNombre(){
return nombre;
}
public void setNombre(String nombre){
this.nombre = nombre;
}
public String getApellido(){
return apellido;
}
public void setApellido(String apellido){
this.apellido = apellido;
}
public String getDireccion() {
return direccion;
}
public void setDireccion(String direccion){
this.direccion = direccion;
}
public void setId(Long id) {
this.id = id;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof PersonaEntity)) {
return false;
}
PersonaEntity other = (PersonaEntity) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "uy.edu.ort.gestion.persona.entidades.PersonaEntity[ id=" + id + " ]";
}
}
[FIN CODIGO 1]
[CODIGO 2]
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package uy.edu.ort.gestion.persona.negocio;
import javax.ejb.Local;
import uy.edu.ort.dominio.Persona;
/**
*
* @author CRUSSO_PC
*/
@Local
public interface PersonaSBLocal {
public void alta(Persona persona);
public void eliminar(Persona persona);
public void modificar(Persona persona);
}
[FIN DEL CODIGO 2]
[CODIGO 3]
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package uy.edu.ort.gestion.persona.negocio;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import uy.edu.ort.dominio.Persona;
import uy.edu.ort.gestion.persona.entidades.PersonaEntity;
/**
*
* @author CRUSSO_PC
*/
@Stateless
public class PersonaSB implements PersonaSBLocal {
@PersistenceContext
EntityManager em;
@Override
public void alta(Persona persona)
{
PersonaEntity personaEntity = new PersonaEntity();
personaEntity.setDireccion(persona.getDireccion());
personaEntity.setNombre(persona.getNombre());
personaEntity.setApellido(persona.getApellido());
em.persist(personaEntity);
}
@Override
public void eliminar(Persona persona)
{
}
@Override
public void modificar(Persona persona)
{
}
// Add business logic below. (Right-click in editor and choose
// "Insert Code > Add Business Method")
}
[FIN DEL CODIGO 3]
[CODIGO 4]
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package uy.edu.ort.cliente;
/**
*
* @author CRUSSO_PC
*/
public class ClientePrueba {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
PersonaWS port = new PersonaWS_Service().getPersonaWSPort();
Persona persona = new Persona();
persona.setDireccion("Lejos");
persona.setNombre("Juan");
persona.setApellido("Perez");
port.alta(persona);
System.out.println("Fin!!");
}
}
[FIN DEL CODIGO 4]
Errores y soluciones de deployment en Java EE
EL ARCHIVO GLASSFISH-RESOURCES.XML ES IMPORTANTE!
ES EL QUE TIENE TODAS LAS CONEXIONES DE BD.
SI HAY ERRORES DE DEPLOYMENT REFERIDOS A LAS CONEXIONES, HAY QUE REVISAR ESTE ARCHIVO (ESTA DENTRO DEL EJB, EN LA CARPETA SETUP)
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'OPTION SQL_SELECT_LIMIT=DEFAULT' at line 1
=======================================================================
Verificar que se está utilizando la version mysql-connector-java-5.1.23.jar
Y verificar que está copiado en estas ubicaciones:
c:\glassfish4\glassfish\domains\<dominio>\lib
c:\glassfish4\glassfish\domains\<dominio>\lib\ext
Test de webservices REST
==================
Hay que elegir correctamente el proyecto para test. La 1ra pantalla muestra como NO funciona, la 2da es la correcta (siempre elegir el proyecto con "Web Test Client in Project..."
Si da errores de FileNotFoundException (ej, que no puede encontrar el build.xml, etc)
==========================================================
Revisar las propiedades de cada proyecto, y ver si hay "missing files" en algun lado
Si da error: java.lang.Exception: Virtual server server already has a web module Web1
==========================================================
1. Hacer undeploy de la aplicacion (si es que esta deployed en glassfish)
2. Bajar servidor Glassfish
3. Borrar el contenido de la carpeta: C:\glassfish4\glassfish\domains\domain1\generated
4. Subir el servidor Glassfish
5. Hacer el deploy nuevamente
Si no encuentra el WADL cuando se quiere testear un webservice REST
=================================================
Revisar el archivo persistence.xml
Debe ser parecido a este:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="Web1PU" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>jdbc/achilles</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.schema-generation.database.action" value="create"/>
</properties>
</persistence-unit>
</persistence>
Si da error de Application contains no valid components
======================================
El EJB debe contener por lo menos un Session Bean!!! sino da este error.
Si no se puede hacer el deploy
=====================
Verificar que no este intentando crear las tablas y ya estan en la base de datos.
Si no hace insert...
============
Verificar si esta marcado Use Java Transaction APIs (JTA) en persistence.xml.
Si esta marcado, los begin, commit y rollback los maneja JPA, por lo cual no hay que ponerlos.
Si no se puede hacer deploy y aparece este mensaje:
===================================
There is no installed container capable of handling this application
En el enterprise application, click derecho, Add Java EE Module
Seleccionar el módulo EJB.
Luego hacer deploy de nuevo.
Como hacer deploy utilizando el glassfish server:
================================
Click derecho sobre el enterprise application.
Clean and Build
Esto genera un archivo .ear dentro de la carpeta dist:
Por ejemplo:
C:\_KARINA\EJB2\AppGestionPersona\dist\AppGestionPersona.ear
OJO!!! si el deploy luego falla, puede que el NetBeans no haya podido generar el .ear.
En este caso:
Abrir la carpeta dist de cada una de las aplicaciones que componen la solución
Borrar todo el contenido de la carpeta "dist" [si no deja borrarlo, puede ser que el archivo lo tenga capturado el java, para eso hacer control
alt suprimir, task manager, y matar todos los java que haya... Si se hace esto hay que levantar de nuevo el servidor de aplicaciones, porque es uno
de esos javas qeu matamos recién]
Volver a hacer clean and build
[DEPLOY]
OJO!! ANTES DE HACER EL DEPLOY RECORDAR CREAR LA BASE DE DATOS!!
Renombrar el .ear generado a .zip, abrirlo y copiar el archivo glassfish-resources.xml (que esta en la carpeta del EJB), a la carpeta META-INF. (luego renombrarlo nuevamente a .ear)
OJO!!!! al archivo glassfish-resources.xml hay que configurarle el password antes de incluirlo en META-INF (en la property name="Password")
OJO!!! El nombre del datasource que se defina en el persistence unit en el netbeans debe ser asi: java:app/achilles
(The solution is making the resource an application-wide resource. Make sure you make the JNDI name prefixed with java:app/. And so,
in your case, it'll be java:app/Vodafone. This should be done in both your persistence.xml file and
in the WEB-INF/glassfish-resources.xml file also)
Para hacer el deploy desde el Glassfish:
1. Abrir Glassfish como administrador: http://localhost:4848 (usuario admin, passwd root)
2. Click en Applications
3. Click en Deploy...
4. Seleccionar "packaged file to be uploaded to the server"
5. Seleccionar el archivo .ear que se generó dentro de la carpeta "dist" del enterprise application (ej: C:\_KARINA\EJB2\AppGestionPersona\dist\AppGestionPersona.ear)
6. Dar OK
ES EL QUE TIENE TODAS LAS CONEXIONES DE BD.
SI HAY ERRORES DE DEPLOYMENT REFERIDOS A LAS CONEXIONES, HAY QUE REVISAR ESTE ARCHIVO (ESTA DENTRO DEL EJB, EN LA CARPETA SETUP)
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'OPTION SQL_SELECT_LIMIT=DEFAULT' at line 1
=======================================================================
Verificar que se está utilizando la version mysql-connector-java-5.1.23.jar
Y verificar que está copiado en estas ubicaciones:
c:\glassfish4\glassfish\domains\<dominio>\lib
c:\glassfish4\glassfish\domains\<dominio>\lib\ext
Test de webservices REST
==================
Hay que elegir correctamente el proyecto para test. La 1ra pantalla muestra como NO funciona, la 2da es la correcta (siempre elegir el proyecto con "Web Test Client in Project..."
Si da errores de FileNotFoundException (ej, que no puede encontrar el build.xml, etc)
==========================================================
Revisar las propiedades de cada proyecto, y ver si hay "missing files" en algun lado
Si da error: java.lang.Exception: Virtual server server already has a web module Web1
==========================================================
1. Hacer undeploy de la aplicacion (si es que esta deployed en glassfish)
2. Bajar servidor Glassfish
3. Borrar el contenido de la carpeta: C:\glassfish4\glassfish\domains\domain1\generated
4. Subir el servidor Glassfish
5. Hacer el deploy nuevamente
Si no encuentra el WADL cuando se quiere testear un webservice REST
=================================================
Revisar el archivo persistence.xml
Debe ser parecido a este:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="Web1PU" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>jdbc/achilles</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.schema-generation.database.action" value="create"/>
</properties>
</persistence-unit>
</persistence>
Si da error de Application contains no valid components
======================================
El EJB debe contener por lo menos un Session Bean!!! sino da este error.
Si no se puede hacer el deploy
=====================
Verificar que no este intentando crear las tablas y ya estan en la base de datos.
============
Verificar si esta marcado Use Java Transaction APIs (JTA) en persistence.xml.
Si esta marcado, los begin, commit y rollback los maneja JPA, por lo cual no hay que ponerlos.
Si no se puede hacer deploy y aparece este mensaje:
===================================
There is no installed container capable of handling this application
En el enterprise application, click derecho, Add Java EE Module
Seleccionar el módulo EJB.
Luego hacer deploy de nuevo.
Como hacer deploy utilizando el glassfish server:
================================
Click derecho sobre el enterprise application.
Clean and Build
Esto genera un archivo .ear dentro de la carpeta dist:
Por ejemplo:
C:\_KARINA\EJB2\AppGestionPersona\dist\AppGestionPersona.ear
OJO!!! si el deploy luego falla, puede que el NetBeans no haya podido generar el .ear.
En este caso:
Abrir la carpeta dist de cada una de las aplicaciones que componen la solución
Borrar todo el contenido de la carpeta "dist" [si no deja borrarlo, puede ser que el archivo lo tenga capturado el java, para eso hacer control
alt suprimir, task manager, y matar todos los java que haya... Si se hace esto hay que levantar de nuevo el servidor de aplicaciones, porque es uno
de esos javas qeu matamos recién]
Volver a hacer clean and build
[DEPLOY]
OJO!! ANTES DE HACER EL DEPLOY RECORDAR CREAR LA BASE DE DATOS!!
Renombrar el .ear generado a .zip, abrirlo y copiar el archivo glassfish-resources.xml (que esta en la carpeta del EJB), a la carpeta META-INF. (luego renombrarlo nuevamente a .ear)
OJO!!!! al archivo glassfish-resources.xml hay que configurarle el password antes de incluirlo en META-INF (en la property name="Password")
OJO!!! El nombre del datasource que se defina en el persistence unit en el netbeans debe ser asi: java:app/achilles
(The solution is making the resource an application-wide resource. Make sure you make the JNDI name prefixed with java:app/. And so,
in your case, it'll be java:app/Vodafone. This should be done in both your persistence.xml file and
in the WEB-INF/glassfish-resources.xml file also)
Para hacer el deploy desde el Glassfish:
1. Abrir Glassfish como administrador: http://localhost:4848 (usuario admin, passwd root)
2. Click en Applications
3. Click en Deploy...
4. Seleccionar "packaged file to be uploaded to the server"
5. Seleccionar el archivo .ear que se generó dentro de la carpeta "dist" del enterprise application (ej: C:\_KARINA\EJB2\AppGestionPersona\dist\AppGestionPersona.ear)
6. Dar OK
Ejemplo MVC
Controllers / ClienteController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.Models;
using LibX.X;
using LibX.X.X.cifIO;
namespace MvcApplication1.Controllers
{
public class ClientesController : Controller
{
//
// GET: /FormularioClientes/
public ActionResult Formulario()
{
Parametros p = new Parametros();
ViewBag.doccli = p.comboBCT("TIPDOC");
ViewBag.paises = p.comboBCT("PAIS");
return View();
}
public ActionResult Listado(FormCollection form)
{
SqlDb odb = new SqlDb();
odb.AbrirDB();
odb.BeginTran();
ViewBag.doccli = form["doccli"];
cli.doccli = int.Parse(form["doccli"].ToString());
cli.numcli = long.Parse(form["numcli"].ToString());
cli.digcli = form["digcli"].ToString();
Cliente c = new Cliente();
try
{
cli.LeerCliente(odb);
c.doccli = cli.doccli;
c.numcli = cli.numcli;
c.nomabr = cli.nomabr;
odb.CommitTran();
odb.CerrarDB();
}
catch (Exception e)
{
c.nomabr = "NO HAY DATOS...";
}
return View(c);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.Models;
using LibX.X;
using LibX.X.X.cifIO;
namespace MvcApplication1.Controllers
{
public class ClientesController : Controller
{
//
// GET: /FormularioClientes/
public ActionResult Formulario()
{
Parametros p = new Parametros();
ViewBag.doccli = p.comboBCT("TIPDOC");
ViewBag.paises = p.comboBCT("PAIS");
return View();
}
public ActionResult Listado(FormCollection form)
{
SqlDb odb = new SqlDb();
odb.AbrirDB();
odb.BeginTran();
ViewBag.doccli = form["doccli"];
cli.doccli = int.Parse(form["doccli"].ToString());
cli.numcli = long.Parse(form["numcli"].ToString());
cli.digcli = form["digcli"].ToString();
Cliente c = new Cliente();
try
{
cli.LeerCliente(odb);
c.doccli = cli.doccli;
c.numcli = cli.numcli;
c.nomabr = cli.nomabr;
odb.CommitTran();
odb.CerrarDB();
}
catch (Exception e)
{
c.nomabr = "NO HAY DATOS...";
}
return View(c);
}
}
}
Models / Cliente.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace MvcApplication1.Models
{
public class Cliente
{
public int doccli {get; set;}
[StringLength(7)]
public long numcli {get; set;}
public int digcli {get; set;}
public String nomabr { get; set; }
}
}
Models / Parametros.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI.WebControls;
using LibX.X;
using LibX.X.Y.bctIO;
namespace MvcApplication1.Models
{
public class Parametros
{
public int ItemBCT { get; set; }
public List<System.Web.Mvc.SelectListItem> ItemBCTList { get; set; }
public List<System.Web.Mvc.SelectListItem> comboBCT(String tabla)
{
SqlDb odb = new SqlDb();
odb.AbrirDB();
odb.BeginTran();
des.LeerBCTPorTabla(odb, tabla);
List<System.Web.Mvc.SelectListItem> lista = new List<System.Web.Mvc.SelectListItem>();
for (int i = 0; i < odb.dt.Rows.Count; i++)
{
SelectListItem item = new SelectListItem { Value = odb.dt.Rows[i]["coddestab"].ToString(), Text = odb.dt.Rows[i]["coddestab"].ToString() + " - " + odb.dt.Rows[i]["descortab"].ToString() };
lista.Add(item);
/*
ItemBCTList = new List<System.Web.Mvc.SelectListItem>() {
new SelectListItem { Value = "1", Text = "Renault" },
new SelectListItem { Value = "2", Text = "Peugeot" } };
* */
}
odb.CommitTran();
odb.CerrarDB();
return lista;
// return ItemBCTList;
}
}
}
Models / Parametros.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI.WebControls;
using LibX.X;
using LibX.X.Y.bctIO;
namespace MvcApplication1.Models
{
public class Parametros
{
public int ItemBCT { get; set; }
public List<System.Web.Mvc.SelectListItem> ItemBCTList { get; set; }
public List<System.Web.Mvc.SelectListItem> comboBCT(String tabla)
{
SqlDb odb = new SqlDb();
odb.AbrirDB();
odb.BeginTran();
des.LeerBCTPorTabla(odb, tabla);
List<System.Web.Mvc.SelectListItem> lista = new List<System.Web.Mvc.SelectListItem>();
for (int i = 0; i < odb.dt.Rows.Count; i++)
{
SelectListItem item = new SelectListItem { Value = odb.dt.Rows[i]["coddestab"].ToString(), Text = odb.dt.Rows[i]["coddestab"].ToString() + " - " + odb.dt.Rows[i]["descortab"].ToString() };
lista.Add(item);
/*
ItemBCTList = new List<System.Web.Mvc.SelectListItem>() {
new SelectListItem { Value = "1", Text = "Renault" },
new SelectListItem { Value = "2", Text = "Peugeot" } };
* */
}
odb.CommitTran();
odb.CerrarDB();
return lista;
// return ItemBCTList;
}
}
}
Views / Clientes / Formulario.cshtml
<!DOCTYPE html>
@using MvcApplication1.Models
@model Cliente
@{
ViewBag.Title = "Formulario";
}
<link href="../../Content/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="../../Scripts/jquery-1.10.2.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui-1.10.3.js" type="text/javascript"></script>
@using (Html.BeginForm("Listado", "Clientes", FormMethod.Post))
{
@Html.DropDownList("doccli")
@Html.Label("Numcli")
@Html.TextBoxFor(m => m.numcli)
@Html.TextBoxFor(m => m.digcli)
<input id="Submit1" type="submit" value="submit" />
}
Suscribirse a:
Entradas (Atom)
