Ejecutar procedimiento almacenado en JSP.
<%@page language=”java” session=”false” import=”java.sql.*,java.io.*”%>
<%
try {
Class.forName(“com.mysql.jdbc.Driver”).newInstance();
Connection databaseConnection = DriverManager.getConnection(“jdbc:mysql://server/data base name,user,password);
Statement myStatement = databaseConnection.createStatement();
ResultSet myResult = myStatement.executeQuery(“CALL nameofStoreProcedure(‘param1′,’param2′…’)”);
while (myResult.next()) {
out.println(myResult.getString(“Name of column”);
}
databaseConnection.close();
}catch (Exception e){
out.println(“Error: ” + e.getMessage());
}
%>
Conexión a Base de Datos MySql en JSP.
<%@page language=”java” session=”false” import=”java.sql.*,java.io.*”%>
<%
try {
Class.forName(“com.mysql.jdbc.Driver”).newInstance();
Connection databaseConnection = DriverManager.getConnection(“jdbc:mysql://server/database name,user,password);
}catch (Exception e){
out.println(“Error: ” + e.getMessage());
}
%>
Crear conexion HttpsURLConnection
Para poder establecer una conexión https lo primero que tenemos que hacer es definir el código necesario que nos permite aceptar los certificados. Para aceptar todos los certificados debemos hacer los siguiente:
/*Aceptamos todos los certificados*/
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
}
};
try {
SSLContext sc = SSLContext.getInstance(“SSL”);
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
}
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
return true;
}
};
ahora a continuación estableceremos la conexión:
URL _URL = null;
try {
_URL = new URL(“https://……….”);
} catch (MalformedURLException e) {
out.println(“ ERROR: La url de conexión no es correcta.”);
}
HttpsURLConnection.setDefaultHostnameVerifier(hv);
try{
HttpsURLConnection conn = (HttpsURLConnection) _URL.openConnection();
//conn.setMethod(“GET”);
conn.setRequestProperty(“User-Agent”,”Mozilla/5.0 (Windows; U; Windows NT 5.1; es-ES; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2″);
conn.setRequestProperty(“Accept”,”text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8″);
conn.setRequestProperty(“Accept Language”,”es-es,es;q=0.8,en-us;q=0.5,en;q=0.3″);
conn.setRequestProperty(“Accept-Encoding” ,”gzip,deflate”);
conn.setRequestProperty(“Accept-Charset”,”ISO-8859-1,utf-8;q=0.7,*;q=0.7″);
conn.setRequestProperty(“Keep-Alive”,”300″);
conn.setRequestProperty(“Connection”,”keep-alive”);
conn.setRequestProperty(“Content-type”,”text/xml”);
conn.setRequestProperty(“Cache-Control”, “no-cache”);
conn.setDoInput(true);
conn.setRequestMethod(“GET”);
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
while ((line = br.readLine()) != null) {
out.println(line);
}
int status = conn.getResponseCode();
} catch (Exception e) {
out.println(“error:”+ e.getMessage());
}
Enviar Correos en JAVA.
En el siguiente post indicaremos la forma de enviar correos en JAVA, tanto con correo adjunto como si él.
Para el envio de correo a una dirección determinada y con fichero adjunto:
* Enviar correo con documento adjunto a 1 direccion de correo.
* @param smtphost: Servidor de Correo
* @param Address : Direccion del remitente
* @param Passw : Password del usuario remitente
* @param ToAddress : Dirección a la que se dirige el mensage
* @param fichero : fichero adjunto que se desea enviar
* @param Cuerpo : Contiene el cuerpo del mensaje.
* @param debug : Si es true se establace el modo depuración
*/
public static void Enviar(String smtphost,String Address,String Passw,String ToAddress,String fichero, boolean debug, String Cuerpo){
Properties props = new Properties();
props.setProperty(“mail.smtp.host”, smtphost);
props.setProperty(“mail.smtp.starttls.enable”, “true”);
//props.setProperty(“mail.smtp.port”,”8080″);
props.setProperty(“mail.smtp.user”, Address);
props.setProperty(“mail.smtp.auth”, “false”);
Session session = Session.getDefaultInstance(props);
session.setDebug(debug);
BodyPart texto = new MimeBodyPart();
BodyPart adjunto = new MimeBodyPart();
try {
texto.setText(Cuerpo);
adjunto.setDataHandler(new DataHandler(new FileDataSource(fichero)));
adjunto.setFileName(fichero);
MimeMultipart multiParte = new MimeMultipart();
multiParte.addBodyPart(texto);
multiParte.addBodyPart(adjunto);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(Address+”@correo.es”));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(ToAddress));
message.setSubject(“Fichero Log RobotAD”);
message.setContent(multiParte);
Transport t = session.getTransport(“smtp”);
t.connect(Address,Passw);
t.sendMessage(message,message.getAllRecipients());
t.close();
} catch (MessagingException e) {
CargaFicheroDA.log.println(“Error al enviar correo: “+e.getMessage());
}
}
* Envía correos sin archivo adjunto.
* @param smtphost
* @param Address
* @param Passw
* @param ToAddress
* @param debug
* @param Cuerpo
*/
public static void EnviarSA(String smtphost,String Address,String Passw,String ToAddress, boolean debug, String Cuerpo){
Properties props = new Properties();
props.setProperty(“mail.smtp.host”, smtphost);
props.setProperty(“mail.smtp.starttls.enable”, “true”);
//props.setProperty(“mail.smtp.port”,”8080″);
props.setProperty(“mail.smtp.user”, Address);
props.setProperty(“mail.smtp.auth”, “false”);
Session session = Session.getDefaultInstance(props);
session.setDebug(debug);
BodyPart texto = new MimeBodyPart();
//BodyPart adjunto = new MimeBodyPart();
try {
texto.setText(Cuerpo);
// adjunto.setDataHandler(new DataHandler(new FileDataSource(fichero)));
// adjunto.setFileName(fichero);
MimeMultipart multiParte = new MimeMultipart();
multiParte.addBodyPart(texto);
//multiParte.addBodyPart(adjunto);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(Address+”@correo.es”));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(ToAddress));
message.setSubject(“Fichero Log RobotAD”);
message.setContent(multiParte);
Transport t = session.getTransport(“smtp”);
t.connect(Address,Passw);
t.sendMessage(message,message.getAllRecipients());
t.close();
} catch (MessagingException e) {
CargaFicheroDA.log.println(“Error al enviar correo: “+e.getMessage());
}
}
Codificar Fichero en base 64 en Java.
La siguiente función realiza la codificación de un fichero en base 64, recorre todos los fichero de una ruta dada y los pasa a base 64 y deja los ficheros en la ruta especificada por rutaFilesCodec. En la realización de está función se ha utilizada una clases para la transformación a base 64, dichas clases serán descritas el final del post.
public void CodecBase64File(String rutaFiles, String rutaFilesCodec){
Base64FileEncoder codec = new Base64FileEncoder();
String [] files = Lista_ficheros_PDF(rutaFiles);
// String [] files = Lista_ficheros(rutaFiles);
log.write(“ INFO: zip(): — Se van a añadir “+files.length+ ” ficheros.”);
for (int i=0; i<files.length; i++){
try {
log.write(“ INFO: CodecBase64File():— Codificando: “+files[i]);
codec.encodeFile(rutaFiles+files[i], rutaFilesCodec+files[i]);
} catch (IOException e) {
log.write(“ ERROR: CodecBase64File():— Codificando: “+files[i]);
}
}
}
A continuación vamos a especificar las diferentes clases que hemos usado, solo tienes que cortar y pegar.
Base64Coder.java
public class Base64Coder {
// Mapping table from 6-bit nibbles to Base64 characters.
private char[] map1 = new char[64];
{
int i=0;
for (char c=’A'; c<=’Z'; c++)
map1[i++] = c;
for (char c=’a'; c<=’z'; c++)
map1[i++] = c;
for (char c=’0′; c<=’9′; c++)
map1[i++] = c;
map1[i++] = ‘+’; map1[i++] = ‘/’;
}
// Mapping table from Base64 characters to 6-bit nibbles.
private byte[] map2 = new byte[128];
{
for (int i=0; i<map2.length; i++)
map2[i] = -1;
for (int i=0; i<64; i++) map2[map1[i]] =
(byte)i;
}
/**
* Codificando un string a base 64
* @param s String a codificar
* @return String en Base64
*/
public String encodeString (String s) {
return new String(encode(s.getBytes())); }
/**
* array de byte en fomate base64
* @param in array que contine los byte a codificas
* @return array de caracters codificados en base 64
*/
public char[] encode (byte[] in) {
return encode(in,in.length); }
/**
* Codifica un array de byte en base 64
* @param in array de byte a codificar.
* @param iLen numero de byte a codificar en in
* @return Array de caracteres codificados en base 64
*/
public char[] encode (byte[] in, int iLen) {
int oDataLen = (iLen*4+2)/3;
int oLen = ((iLen+2)/3)*4;
char[] out = new char[oLen];
int ip = 0;
int op = 0;
while (ip < iLen) {
int i0 = in[ip++] & 0xff;
int i1 = ip < iLen ? in[ip++] & 0xff : 0;
int i2 = ip < iLen ? in[ip++] & 0xff : 0;
int o0 = i0 >>> 2;
int o1 = ((i0 & 3) << 4) | (i1 >>> 4);
int o2 = ((i1 & 0xf) << 2) | (i2 >>> 6);
int o3 = i2 & 0x3F;
out[op++] = map1[o0];
out[op++] = map1[o1];
out[op] = op < oDataLen ? map1[o2] : ‘=’; op++;
out[op] = op < oDataLen ? map1[o3] : ‘=’; op++;
}
return out;
}
/**
* Decodifica un string en base 64
* @param s String en base 64
* @return A String que contiene los datos decodificados
* @throws IllegalArgumentException if the input is not valid Base64 encoded data.
*/
public String decodeString (String s) {
return new String(decode(s));
}
/**
* Decodifica un array de byte en formato Base64.
* @param s String en base 64 a codificar.
* @return Array de byte decodificado
* @throws IllegalArgumentException if the input is not valid Base64 encoded data.
*/
public byte[] decode (String s) {
return decode(s.toCharArray());
}
/**
* Decodifica un array de byte en formato base 64
* @param in Array de caracteres en base 64
* @return Array de byte con los datos decodificados
* @throws IllegalArgumentException if the input is not valid Base64 encoded data.
*/
public byte[] decode (char[] in) {
int iLen = in.length;
if (iLen%4 != 0)
throw new IllegalArgumentException (“Longitud de cadena codificada en base 64 no es multiple de 4.”);
while (iLen > 0 && in[iLen-1] == ‘=’)
iLen–;
int oLen = (iLen*3) / 4;
byte[] out = new byte[oLen];
int ip = 0;
int op = 0;
while (ip < iLen) {
int i0 = in[ip++];
int i1 = in[ip++];
int i2 = ip < iLen ? in[ip++] : ‘A’;
int i3 = ip < iLen ? in[ip++] : ‘A’;
if (i0 > 127 || i1 > 127 || i2 > 127 || i3 > 127)
throw new IllegalArgumentException (“Caracter ilegal codificado en base 64.”);
int b0 = map2[i0];
int b1 = map2[i1];
int b2 = map2[i2];
int b3 = map2[i3];
if (b0 < 0 || b1 < 0 || b2 < 0 || b3 < 0)
throw new IllegalArgumentException (“Caracte ilegal codificado en base 64.”);
int o0 = ( b0 <<2) | (b1>>>4);
int o1 = ((b1 & 0xf)<<4) | (b2>>>2);
int o2 = ((b2 & 3)<<6) | b3;
out[op++] = (byte)o0;
if (op<oLen)
out[op++] = (byte)o1;
if (op<oLen)
out[op++] = (byte)o2;
}
return out;
}
public Base64Coder() {}
} // end class Base64Coder
Base64FileEncoder.java
public class Base64FileEncoder {
/**
* Codifica un fichero a base 64
* @param inputFileName
* @param outputFileName
* @throws IOException
*/
public void encodeFile (String inputFileName, String outputFileName) throws IOException {
BufferedInputStream in = null;
BufferedWriter out = null;
try {
in = new BufferedInputStream(new FileInputStream(inputFileName));
out = new BufferedWriter(new FileWriter(outputFileName));
encodeStream (in,out);
out.flush(); }
finally {
if (in != null) in.close();
if (out != null) out.close();
}
}
/**
* Codifica un Stream
* @param in
* @param out
* @throws IOException
*/
public void encodeStream (InputStream in, BufferedWriter out) throws IOException {
int lineLength = 72;
Base64Coder cod = new Base64Coder();
byte[] buf = new byte[lineLength/4*3];
while (true) {
int len = in.read(buf);
if (len <= 0) break;
out.write (cod.encode(buf, len));
out.newLine();
}
}
/**
* PAsa un fichero a base 64 y devuelve el resultado en un StringBuffer
* @param inputFileName
* @param out
* @throws IOException
*/
public void encodeStream(String inputFileName, StringBuffer out) throws IOException{
int lineLength = 72;
BufferedInputStream in = new BufferedInputStream(new FileInputStream(inputFileName));
Base64Coder cod = new Base64Coder();
byte[] buf = new byte[lineLength/4*3];
while (true) {
int len = in.read(buf);
if (len <= 0) break;
String nuevo = new String(cod.encode(buf, len));
out.append(nuevo);
}
}
}
Base64FileDecoder.java
public class Base64FileDecoder {
/**
* decodifica un archivos de base 64
* @param inputFileName
* @param outputFileName
* @throws IOException
*/
public void decodeFile (String inputFileName, String outputFileName) throws IOException {
BufferedReader in = null;
BufferedOutputStream out = null;
try {
in = new BufferedReader(new FileReader(inputFileName));
out = new BufferedOutputStream(new FileOutputStream(outputFileName));
decodeStream (in,out);
out.flush(); }
finally {
if (in != null) in.close();
if (out != null) out.close();
}
}
public void decodeStream (BufferedReader in, OutputStream out) throws IOException {
Base64Coder cod = new Base64Coder();
while (true) {
String s = in.readLine();
if (s == null) break;
byte[] buf = cod.decode(s);
out.write (buf);
}
}
}
Ver configuración actual del OWA (in PowerShell) Exchange 2007
Para ver la configuración que en estos momentos tenemos en nuestro OWA lo podemos hacer de la siguiente manera, teniendo en cuanta que donde se indica SERVIDOR debemos indicar nuestro servidor HUB/CAS.
Get-OwaVirtualDirectory -Server SERVIDOR |fl >c:\out.txt
Cambiar Configuración OWA en Exchange 2007
Set-OWAVirtualDirectory -Identity “servexch05\owa (default web site)” -atributo
Para ver más información ayuda
Ver configuracion OWA en Exchange 2007
Get-OwaVirtualDirectory -Identity “SERVIDOR\owa (default web site)”
En el “SERVIDOR”, hay que indicar el servidor que funciona como HUB/CAS
Quitar derechos sobre un buzón a un usuario (in PowerShell) Exchange 2007
Remove-MailboxPermission -Identity ‘CN=buzon,CN=Users,DC=dominio,DC=local’ -User ‘Dominio\usuario’ -InheritanceType ‘All’ -AccessRights ‘FullAccess’
Añadir permiso sobre un buzón a un usuario (in PowerShell) Exchange 2007
Add-MailboxPermission -Identity ‘CN=buzon,CN=Users,DC=dominio,DC=local’ -User ‘Dominio\usuario’ -AccessRights ‘FullAccess’