Subversion Repositories bacoAlunos

Compare Revisions

Ignore whitespace Rev 2027 → Rev 2028

/es2018/jmachado/src/java/pt/estgp/es/exemplos/hibernate/utils/StreamsUtils.java
New file
0,0 → 1,140
package pt.estgp.es.exemplos.hibernate.utils;
 
import java.io.*;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
 
/**
* @author Jorge Machado
* @date 27/Mai/2008
* @see jomm.utils
*/
public class StreamsUtils
{
public static byte[] readBytes(InputStream stream) throws IOException
{
ByteArrayOutputStream b = new ByteArrayOutputStream();
int readedBytes;
byte[] buf = new byte[1024];
while ((readedBytes = stream.read(buf)) > 0)
{
b.write(buf, 0, readedBytes);
}
b.close();
return b.toByteArray();
}
 
public static String readString(InputStream stream) throws IOException
{
ByteArrayOutputStream b = new ByteArrayOutputStream();
int readedBytes;
byte[] buf = new byte[1024];
while ((readedBytes = stream.read(buf)) > 0)
{
b.write(buf, 0, readedBytes);
}
b.close();
return b.toString();
}
 
public static void inputStream2File(InputStream stream, File f) throws IOException
{
f.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(f);
inputStream2OutputStream(stream,out);
}
 
/**
* ATENTION this method does not close the given stream
* @param stream
* @param f
* @return
* @throws IOException
*/
public static String inputStream2FileGetMd5(InputStream stream, File f) throws IOException
{
f.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(f);
return inputStream2OutputStreamGetMd5(stream, out);
}
 
public static void inputStream2OutputStream(InputStream stream, OutputStream out) throws IOException
{
inputStream2OutputStream(stream,out,true,true);
}
 
public static void inputStream2OutputStream(InputStream stream, OutputStream out,boolean closeOut,boolean closeIn) throws IOException
{
int readedBytes;
byte[] buf = new byte[1024];
while ((readedBytes = stream.read(buf)) > 0)
{
out.write(buf, 0, readedBytes);
}
if(closeIn)
stream.close();
if(closeOut)
out.close();
}
 
/**
* Return digest Md5 from consumed bytes
* * ATENTION this method does not close the given stream
* @param stream
* @param out
* @return Md5 HEX
* @throws IOException
*/
public static String inputStream2OutputStreamGetMd5(InputStream stream, OutputStream out) throws IOException
{
MessageDigest messageDigest = null;
try {
messageDigest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
 
DigestInputStream digestInputStream = new DigestInputStream(stream, messageDigest);
int readedBytes;
byte[] buf = new byte[1024];
while ((readedBytes = digestInputStream.read(buf)) > 0)
{
out.write(buf, 0, readedBytes);
}
messageDigest = digestInputStream.getMessageDigest();
String md5 = BytesUtils.toHex(messageDigest.digest());
out.close();
return md5;
}
 
/**
* Return digest Md5 from consumed bytes
* * ATENTION this method does not close the given stream
* @param stream
* @param out
* @return Md5 HEX
* @throws IOException
*/
public static String getFileMd5(File f) throws IOException
{
MessageDigest messageDigest = null;
try {
messageDigest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
 
DigestInputStream digestInputStream = new DigestInputStream(new FileInputStream(f), messageDigest);
int readedBytes;
byte[] buf = new byte[1024];
while ((readedBytes = digestInputStream.read(buf)) > 0)
{
//nottinhg to do only calculate nd5
}
messageDigest = digestInputStream.getMessageDigest();
String md5 = BytesUtils.toHex(messageDigest.digest());
digestInputStream.close();
return md5;
}
}
/es2018/jmachado/src/java/pt/estgp/es/exemplos/hibernate/utils/BytesUtils.java
New file
0,0 → 1,268
package pt.estgp.es.exemplos.hibernate.utils;
 
 
import org.apache.commons.lang.RandomStringUtils;
import org.apache.log4j.Logger;
 
import java.io.*;
import java.math.BigInteger;
import java.rmi.dgc.VMID;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
 
/**
*
* @author Jorge Machado
*/
 
public class BytesUtils {
private static int counter = 0;
private static Random random = new Random();
private static VMID vmid = new VMID();
private static Logger logger = Logger.getLogger(BytesUtils.class);
 
/** Private Constructor */
 
private BytesUtils () {}
 
 
public static String getMd5FromFile(String filepath)
{
return getMD5(getBytes(filepath));
}
 
public static byte[] getBytes(String fileName)
{
 
byte[] data = null;
try{
 
FileInputStream r = new FileInputStream(fileName);
 
File f = new File(fileName);
 
//this value is never bigger than a integer
int len =(int) f.length();
 
data = new byte[len];
 
int bytesRead = 0;
 
bytesRead = r.read(data);
 
r.close();
 
if(bytesRead == -1)
return null;
 
 
}
catch(FileNotFoundException e)
{
logger.error("Files getBytes()",e);
return null;
}
catch(IOException e)
{
logger.error("Files getData()",e);
return null;
}
return data;
}
 
public static String getMD5(String data)
{
return getMD5(data.getBytes());
}
 
public static String getMD5(byte[] data)
{
return toHex(getMD5Bytes(data));
}
 
public static String getDigestMD5Hex(String str){
byte[] digest = getDigestMD5(str.getBytes());
if(digest != null)
return toHex(digest);
 
return null;
}
public static byte[] getDigestMD5(byte[] data)
{
byte[] result = null;
try{
MessageDigest md5 = MessageDigest.getInstance("MD5");
 
md5.update(data);
 
result = md5.digest();
 
}
catch(NoSuchAlgorithmException e)
{
//this never hapens beacause MD5 is a correct algoritm
logger.fatal("MD5 function does not exists",e);
}
 
return result;
}
/*********************************************************
*Returns true if the two digests are equal
*
*******************************************************/
public static boolean isDigestEqual(byte[] b1,byte[] b2)
{
 
try{
MessageDigest md5 = MessageDigest.getInstance("MD5");
 
return md5.isEqual(b1,b2);
 
}
catch(NoSuchAlgorithmException e)
{
//this never hapens beacause MD5 is a correct algoritm
logger.fatal("MD5 function does not exists",e);
}
 
return false;
 
}
 
public static byte[] getMD5Bytes(byte[] data)
{
try
{
MessageDigest digest = MessageDigest.getInstance("MD5");
 
return digest.digest(data);
}
catch (NoSuchAlgorithmException e)
{
logger.fatal("MD5 function does not exists",e);
}
return null;
}
 
/**
* Return a hex representation of the byte array
*
* @param data The data to transform.
* @return A hex representation of the data.
*/
public static String toHex(byte[] data)
{
if ((data == null) || (data.length == 0))
return null;
 
StringBuffer result = new StringBuffer();
 
// This is far from the most efficient way to do things...
for (int i = 0; i < data.length; i++)
{
int low = (int) (data[i] & 0x0F);
int high = (int) (data[i] & 0xF0);
 
result.append(Integer.toHexString(high).substring(0, 1));
result.append(Integer.toHexString(low));
}
 
return result.toString();
}
 
/**
* Generate a unique key.
* The key is a long (length 38 to 40) sequence of digits.
*
* @return A unique key as a long sequence of base-10 digits.
*/
public static String generateKey()
{
return new BigInteger(generateBytesKey()).abs().toString();
}
 
/**
* Generate a unique key.
* The key is a 32-character long sequence of hex digits.
*
* @return A unique key as a long sequence of hex digits.
*/
public static String generateHexKey()
{
return toHex(generateBytesKey());
}
 
/**
* Generate a unique key as a byte array.
*
* @return A unique key as a byte array.
*/
public static synchronized byte[] generateBytesKey()
{
byte[] junk = new byte[16];
 
random.nextBytes(junk);
 
String input = new StringBuffer().append(vmid).append(new java.util.Date()).append(junk).append(counter++).toString();
 
return getMD5Bytes(input.getBytes());
}
 
// The following two methods are taken from the Jakarta IOUtil class.
 
/**
* Copy stream-data from source to destination. This method does not
* buffer, flush or close the streams, as to do so would require making
* non-portable assumptions about the streams' origin and further use. If
* you wish to perform a buffered copy, use {@link #bufferedCopy}.
*
* @param input The InputStream to obtain data from.
* @param output The OutputStream to copy data to.
*/
public static void copy( final InputStream input, final OutputStream output )
throws IOException
{
final int BUFFER_SIZE = 1024 * 4;
final byte[] buffer = new byte[ BUFFER_SIZE ];
 
while( true )
{
final int count = input.read( buffer, 0, BUFFER_SIZE );
if( -1 == count ) break;
 
// write out those same bytes
output.write( buffer, 0, count );
}
 
//needed to flush cache
//output.flush();
}
 
 
public static void bufferedCopy( final InputStream source, final OutputStream destination )
throws IOException
{
final BufferedInputStream input = new BufferedInputStream( source );
final BufferedOutputStream output = new BufferedOutputStream( destination );
copy( input, output );
output.flush();
}
 
public static int gen5DigitsKey() {
Random r = new Random( System.currentTimeMillis() );
return 10000 + r.nextInt(20000);
}
 
public static String genCharsDigitsKey(int number) {
String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789~`!@#$%^&*()-_=+[{]},<.>?";
return RandomStringUtils.random(number, characters);
}
 
public static void main(String[] args)
{
System.out.println(gen5DigitsKey());
}
 
 
}
/es2018/jmachado/src/java/pt/estgp/es/exemplos/hibernate/web/login/LoginRest.java
New file
0,0 → 1,25
package pt.estgp.es.exemplos.hibernate.web.login;
 
import org.json.JSONException;
import org.json.JSONObject;
import pt.estgp.es.exemplos.hibernate.web.rest.AbstractRestServlet;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public class LoginRest extends AbstractRestServlet
{
public JSONObject login(JSONObject data, HttpServletRequest req, HttpServletResponse resp) throws JSONException
{
String username = data.getString("username");
String password = data.getString("password");
 
System.out.println(username);
System.out.println(password);
 
JSONObject js = new JSONObject();
js.put("result","ok");
 
return js;
}
}
/es2018/jmachado/src/java/pt/estgp/es/exemplos/hibernate/web/rest/AbstractRestServlet.java
1,12 → 1,21
package pt.estgp.es.exemplos.hibernate.web.rest;
 
import org.json.JSONException;
import org.json.JSONObject;
import pt.estgp.es.exemplos.hibernate.utils.StreamsUtils;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
 
public class AbstractRestServlet extends HttpServlet
public abstract class AbstractRestServlet extends HttpServlet
{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
20,13 → 29,54
 
protected void process(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
if(req.getContentType().equals("application/json"))
JSONObject requestObj;
 
if(req.getContentType().equalsIgnoreCase("application/json"))
{
InputStream content = req.getInputStream();
if(content != null)
{
String json = StreamsUtils.readString(content);
try {
requestObj = new JSONObject(json);
System.out.println("REQUEST JSON:");
System.out.println(requestObj.toString());
 
String service = requestObj.getString("service");
String data = requestObj.has("data") ? requestObj.getString("data") : null;
 
Method innerMethod = this.getClass().getMethod(service,new Class[]{
JSONObject.class,
HttpServletRequest.class,
HttpServletResponse.class});
JSONObject obj = (JSONObject) innerMethod.invoke(this,new Object[]{data,req,resp});
 
JSONObject response = new JSONObject();
response.put("service","ok");
response.put("response",obj);
 
resp.setContentType("application/json");
PrintWriter pw = resp.getWriter();
pw.write(obj.toString());
 
} catch (Throwable e) {
e.printStackTrace();
JSONObject response = new JSONObject();
try {
response.put("service","error");
response.put("cause",e.toString());
resp.setContentType("application/json");
PrintWriter pw = resp.getWriter();
pw.write(response.toString());
} catch (JSONException e1) {
e1.printStackTrace();
}
 
 
}
}
}
else
{
 
}
 
}
}
/es2018/jmachado/src/web/js/rest-layer.js
New file
0,0 → 1,47
function rest(restAction,serviceName,data,webMessagesContainer,handlerOk,handlerFail)
{
var request =
{
data : data,
service : serviceName
}
 
$.ajax({
url: restAction,
type: "POST",
contentType: "application/json",
data: request,
dataType: "json",
 
success: function(resposta)
{
 
$(webMessagesContainer).find(".web-messages").html("");
if(resposta.service == "error")
{
$(webMessagesContainer).find(".web-messages").html('<div class="alert alert-danger">' + resposta.exception + '</div>');
if(handlerFail != undefined)
{
handlerFail(resposta.exception);
}
 
}
else if(resposta.service == "ok")
{
for(var msg in resposta.messages)
{
$(webMessagesContainer).find(".web-messages").append('<div class="alert alert-success">' + resposta.messages[msg] + '</div>');
}
if(handlerOk != undefined)
handlerOk(resposta.response);
}
},
error: function(resposta) {
$(webMessagesContainer).find(".web-messages").html('<div class="alert alert-danger">Erro de comunicação, por favor tente novamente</div>');
if(handlerFail != undefined)
{
handlerFail(resposta.exception);
}
}
});
}