Initial import.

This commit is contained in:
Ziver Koc 2012-06-13 17:59:22 +00:00
parent bce93523ca
commit d3b4793113
308 changed files with 23679 additions and 0 deletions

97
src/zall/util/Email.java Normal file
View file

@ -0,0 +1,97 @@
package zall.util;
import java.io.IOException;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import sun.net.smtp.SmtpClient;
/**
* Simplifies sending of a email
*
* @author Ziver
*/
public class Email {
public static enum ContentType{
PLAIN, HTML
}
private static final SimpleDateFormat dateFormatter =
new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
private static String host = "localhost";
private String from;
private String niceFrom = null;
private String to;
private String replyTo = null;
private ContentType type = ContentType.PLAIN;
private String subject;
private String message;
public Email(String from, String to){
this.from = from;
this.to = to;
}
public void setFrom(String f){
from = f;
}
public void setNiceFrom(String nf){
niceFrom = nf;
}
public void setReplyTo(String rpt){
replyTo = rpt;
}
public void setTo(String t){
to = t;
}
public void setContentType(ContentType t){
type = t;
}
public void setSubject(String s){
subject = s;
}
public void setMessage(String msg){
message = msg;
}
public static void setServer(String host){
Email.host = host;
}
public void send() throws IOException{
if(from == null)
throw new IllegalArgumentException("From value missing!");
if(to == null)
throw new IllegalArgumentException("To value missing!");
SmtpClient smtp = new SmtpClient( host );
smtp.from(from);
smtp.to(to);
PrintStream msg = smtp.startMessage();
//************ Headers
msg.println("From: "+(niceFrom!=null ? "\""+niceFrom+"\"" : "")+" <"+from+">");
msg.println("Reply-To: <"+replyTo+">");
if( replyTo != null )
msg.println("Reply-To: <"+replyTo+">");
msg.println("To: " + to); // so mailers will display the To: address
msg.println("Subject: "+subject);
// Date
msg.println("Date: "+dateFormatter.format(new Date(System.currentTimeMillis())));
// Content type
switch( type ){
case HTML:
msg.println("Content-Type: text/html;"); break;
default:
msg.println("Content-Type: text/plain;"); break;
}
msg.println();
//*********** Mesasge
msg.println( message );
smtp.closeServer();
}
}

View file

@ -0,0 +1,121 @@
package zall.util.facebook;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Logger;
import zutil.io.IOUtil;
import zutil.log.LogUtil;
import zutil.parser.DataNode;
import zutil.parser.json.JSONParser;
/**
* This class represent a Facebook user
*
* @author Ziver
*/
public class FBUser {
private static Logger logger = LogUtil.getLogger();
/** This is the connection to Facebook **/
private FacebookConnect fbc;
/** the user id of this user */
private String uid;
/* User data */
private String name;
private String email;
private String birthday;
private String gender;
private String relationship_status;
private String website;
private int timezone;
private String locale;
public FBUser( FacebookConnect fbc, String uid ){
this.fbc = fbc;
this.uid = uid;
load();
}
/**
* Updates the data of the user in this object
*/
public void load(){
try {
InputStream stream = fbc.getServiceURL( uid ).openStream();
String data = IOUtil.getContent( stream );
JSONParser jp = new JSONParser();
DataNode node = jp.read( data );
logger.finer("User("+uid+") data from Facebook: "+data);
if( node.get("name") != null )
name = node.get("name").getString();
if( node.get("email") != null )
email = node.get("email").getString();
if( node.get("birthday") != null )
birthday = node.get("birthday").getString();
if( node.get("gender") != null )
gender = node.get("gender").getString();
if( node.get("relationship_status") != null )
relationship_status = node.get("relationship_status").getString();
if( node.get("website") != null )
website = node.get("website").getString();
if( node.get("timezone") != null )
timezone = node.get("timezone").getInt();
if( node.get("locale") != null )
locale = node.get("locale").getString();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @return The unique user id on Facebook
*/
public String getUID(){
return uid;
}
public String getName(){
return name;
}
public String getEmail(){
return email;
}
public String getBirthday(){
return birthday;
}
public String getGender(){
return gender;
}
public String getRelationshipStatus(){
return relationship_status;
}
public String getWebsite(){
return website;
}
public int getTimezone(){
return timezone;
}
public String getLocale(){
return locale;
}
/**
* Returns an instance of the given UID user class
*
* @param uid is the id of the user
* @return a cached FBUser object or a new one if its not cached
*/
public static FBUser get( FacebookConnect fbc, String uid ){
if( uid == null )
return null;
return new FBUser( fbc, uid );
}
}

View file

@ -0,0 +1,206 @@
package zall.util.facebook;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Logger;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import zutil.Hasher;
import zutil.log.LogUtil;
import zutil.parser.Base64Decoder;
import zutil.parser.DataNode;
import zutil.parser.json.JSONParser;
/**
* This class connects to Facebook and
* retrieves information about the user
*
* @author Ziver
*/
public class FacebookConnect {
private static Logger logger = LogUtil.getLogger();
/** The URL to the Facebook OpenGraph service. (must end with a '/') **/
public static final String SERVICE_URL = "https://graph.facebook.com/";
/** The application id for this application generated by Facebook **/
protected static String application_id = null;
/** The application secret for this application generated by Facebook **/
protected static String application_secret = null;
protected String access_token;
protected FBUser user;
private FacebookConnect( String access_token, String uid ){
this.access_token = access_token;
user = FBUser.get( this, uid );
}
/**
* @return the main user
*/
public FBUser getUser(){
return user;
}
/**
* Returns the given user by UID
*
* @param uid is the user id of the user
* @return a FBUser object or null if there is no such user
*/
public FBUser getUser(String uid){
return FBUser.get( this, uid );
}
/**
* @return The access token for this session
*/
protected String getAccessToken(){
return access_token;
}
/**
* Generates a url for calling the Facebook OpenGraph API
*
* @param page is the page ex. a UID
* @return A URL to the service
* @throws MalformedURLException
*/
protected URL getServiceURL(String page) throws MalformedURLException{
return getServiceURL(page, null);
}
/**
* Generates a url for calling the Facebook OpenGraph API
*
* @param page is the page ex. a UID
* @param params is URL parameters ex. "?name=lol" or "&name=lol&lol=name" or "name=lol" etc...
* @return A URL to the service
* @throws MalformedURLException
*/
protected URL getServiceURL(String page, String params) throws MalformedURLException{
StringBuilder url = new StringBuilder( SERVICE_URL );
url.append( page );
url.append( '?' );
url.append( "access_token=" );
url.append( access_token );
if( params != null && !params.isEmpty() ){
if( params.charAt(0) == '?' )
params = params.substring( 1 );
if( params.charAt(0) != '&' )
url.append( '&' );
url.append( params );
}
return new URL( url.toString() );
}
/**
* Sets the static values for this application
* @param id is the application id for this application generated by Facebook
* @param secret is the application secret for this application generated by Facebook
*/
public static void setApplicationID(String id, String secret){
application_id = id;
application_secret = secret;
}
public static String getAplicationId() {
return application_id;
}
/**
* Creates a new instance of the FacebookConnect for the logged in user
* or null if the creation was unsuccessful.
*
* @param cookies is the cookies from the client
* @return A new FacebookConnect object or null if the creation was unsuccessful
*/
public static FacebookConnect getConnection( Cookie[] cookies ){
if( cookies == null ){
logger.severe("Cookie is not set!");
return null;
}
String cookie_name = "fbsr_" + application_id;
// Find the cookie
for(Cookie cookie : cookies) {
if ( cookie_name.equals(cookie.getName()) ){
// remove the trailing "
String value = cookie.getValue();
return getConnection( value );
}
}
System.out.println("Facebook Nothing here!");
return null;
}
/**
* Creates a new instance of the FacebookConnect for the logged in user
* or null if the creation was unsuccessful.
*
* @param value is the string value from facebook
* @return A new FacebookConnect object or null if the creation was unsuccessful
*/
public static FacebookConnect getConnection( String value ){
if( application_id == null ){
logger.severe("Application_id is not set!");
return null;
}
if( application_secret == null ){
logger.severe("Application_secret is not set!");
return null;
}
value = value.trim();
if( value.isEmpty() )
return null;
value = value.replaceAll("-", "+");
value = value.replaceAll("_", "/");
// Parse the attributes
String[] attrib = value.split("\\.", 2);
String signature = Base64Decoder.decodeToHex( attrib[0] );
System.out.println( signature );
attrib[1] = Base64Decoder.addPadding( attrib[1] );
String data = Base64Decoder.decode( attrib[1] );
JSONParser json = new JSONParser();
DataNode map = json.read( data );
System.out.println(map);
if ( !map.getString("algorithm").equalsIgnoreCase("HMAC-SHA256") ) {
logger.severe("Unknown algorithm: '"+map.getString("algorithm")+"' Expected 'HMAC-SHA256'");
return null;
}
// Check hash signature
String local_sig = Hasher.HMAC_SHA256( attrib[1], application_secret );
System.out.println(local_sig);
if ( !signature.equals( local_sig )) {
logger.severe("Bad Signed JSON signature: '"+signature+"' Expected '"+local_sig+"'");
return null;
}
//if( map.containsKey( "access_token" ) )
// return new FacebookConnect( map.get( "access_token" ), map.get( "uid" ) );
//return null;
return null;
}
/**
* This method remove the cookie from the user by setting the MaxAge to -1
*
* @param response is the response that the cookie will be added to
*/
public void logout(HttpServletResponse response) {
Cookie cookie = new Cookie( "fbsr_" + application_id, null);
cookie.setMaxAge( 0 );
cookie.setPath("/");
response.addCookie( cookie );
}
}

View file

@ -0,0 +1,24 @@
package zall.util.msg;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* This class reads a get request and returns all messages
* to that user as JSON.
*
* @author Ziver
*/
public class AjaxUserMessageServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
/**
* Ajax request
*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException{
}
}

View file

@ -0,0 +1,147 @@
package zall.util.msg;
import java.util.LinkedList;
import java.util.Queue;
import java.util.logging.Logger;
import javax.servlet.http.HttpSession;
import zutil.log.LogUtil;
/**
* This class represents all the messages to a single user.
* The class is implemented as an Iterator.
*
* <XMP>
* Example HTML:
*
<SCRIPT type="text/javascript">
jQuery(document).ready(function(){
jQuery(".message").click(function(){
jQuery(this).animate({
opacity: 0
}, 300).animate({
height: 0,
border: 0
}, 300, function(){
jQuery(this).css("display","none");
});
});
});
</SCRIPT>
<div class="menu">
<div class="message" style="border: 2px solid #E6E600; padding: 0px; margin: 5px; background: #FFFF99 none repeat scroll 0%; font-size: 11px; color: black; border-radius: 7px;">
<center><b>Warning:</b></center>
</div>
<div class="message" style="border: 2px solid #FF0000; padding: 0px; margin: 5px; background: #FFDDCC none repeat scroll 0%; font-size: 11px; color: black; border-radius: 7px;">
<center><b>Error:</b></center>
</div>
<div class="message" style="border: 2px solid #039C00; padding: 0px; margin: 5px; background: #9BFB66 none repeat scroll 0%; font-size: 11px; color: black; border-radius: 7px;">
<center><b>Info:</b></center>
</div>
</div>
*
* </XMP>
*
* @author Ziver
*/
public class UserMessage{
public static final Logger logger = LogUtil.getLogger();
public static final String SESSION_USERMESSAGE_KEY = "AJAX_USER_MESSAGES";
/**
* Is the different types of messages
*/
public enum MessageType{
ERROR, WARNING, INFO
}
/**
* This class represents a single message to a user
*/
protected class Message{
MessageType type;
String msg;
}
/** is the queue that contains the messages **/
private Queue<Message> msg_queue;
/** is the current message **/
private Message current;
public UserMessage(){
msg_queue = new LinkedList<Message>();
}
//******** Queue methods
/**
* Adds a new message to the queue
*
* @param type is the type of the message
* @param msg is the message itself
*/
public void add(MessageType type, String msg){
Message m = new Message();
m.type = type;
m.msg = msg;
msg_queue.add( m );
logger.finer("Queueing(Size: "+msg_queue.size()+") user message: "+type+"= \""+msg+"\"");
}
/**
* @return if there is more messages in the queue
*/
public boolean hasNext(){
return msg_queue.size() != 0;
}
/**
* Polls a new message from the Queue
*
* @return if the poll was successful
*/
public boolean next(){
boolean tmp = hasNext();
current = msg_queue.poll();
return tmp;
}
public int size(){
return msg_queue.size();
}
public void clear(){
msg_queue.clear();
}
//******** Message Methods
/**
* @return the type of the current message
*/
public MessageType getType(){
return current.type;
}
/**
* @return the message of the current one
*/
public String getMessage(){
return current.msg;
}
//******** Static methods
public static UserMessage getUserMessage(HttpSession session){
if( session.getAttribute(SESSION_USERMESSAGE_KEY) == null ){
UserMessage msg = new UserMessage();
msg.setSession( session );
return msg;
}
return (UserMessage) session.getAttribute(SESSION_USERMESSAGE_KEY);
}
public void setSession(HttpSession session) {
session.setAttribute(SESSION_USERMESSAGE_KEY, this);
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,10 @@
package zall.util.test;
import zall.util.facebook.FacebookConnect;
public class FacebookTester {
public static void main(String[] args){
FacebookConnect.setApplicationID("110543555676926", "5b2dd75314a2fd58b080b06a19b55713");
FacebookConnect.getConnection("rZtSPvnBVqNi8hnjJuIffghIvQdq56yaLh1FiP-KybQ.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImNvZGUiOiJBUUJnR3ZtNzVfLXIyVU9iSU4wdnJ4N2pMYVRicVpLdVprdE1xQXVWMHBxUjZMcGkzTDJXVEtYV3BxQmJ5MjByX1pnSFo1dDJLX3lGTENFRTJ3Sko1ek8tbHU2Z3Eyb2xfaDB4WGNneW9OTHNRODBsR2tpMG1hVFdSV083a2VfOUlPb0puYkVqajVSdnhyYW03UW9DOHRkRUEtS2NRZE1DUmptd1kzeHNSNFVsUDBuOE9fblFLa1RUbldYNjY0XzR5UEUiLCJpc3N1ZWRfYXQiOjEzMzU3OTQ4MDcsInVzZXJfaWQiOiIxMTg3MDk1NTIyIn0");
}
}

View file

@ -0,0 +1,174 @@
package zall.util.test;
import java.io.File;
import com.xuggle.mediatool.IMediaReader;
import com.xuggle.mediatool.IMediaWriter;
import com.xuggle.mediatool.MediaListenerAdapter;
import com.xuggle.mediatool.MediaToolAdapter;
import com.xuggle.mediatool.ToolFactory;
import com.xuggle.mediatool.event.IAddStreamEvent;
import com.xuggle.mediatool.event.IVideoPictureEvent;
import com.xuggle.mediatool.event.VideoPictureEvent;
import com.xuggle.xuggler.Configuration;
import com.xuggle.xuggler.ICodec;
import com.xuggle.xuggler.IContainer;
import com.xuggle.xuggler.IStream;
import com.xuggle.xuggler.IStreamCoder;
import com.xuggle.xuggler.IVideoPicture;
import com.xuggle.xuggler.IVideoResampler;
public class Transcoder {
public static void main(String[] args){
File originalFile = new File( "C:\\Users\\Ziver\\Desktop\\Downloads\\test2.mp4" );
File mediumFile = new File( "C:\\Users\\Ziver\\Desktop\\Downloads\\temp\\test2_medium.mp4" );
File smallFile = new File( "C:\\Users\\Ziver\\Desktop\\Downloads\\temp\\test2_small.png" );
///////////// Start Transcoding
// create a media reader
IMediaReader reader = ToolFactory.makeReader( originalFile.getPath() );
reader.open();
// create a media writer
IMediaWriter mediaWriter = ToolFactory.makeWriter(mediumFile.getPath(), reader);
// add a writer to the reader, to create the output file
reader.addListener(mediaWriter);
mediaWriter.addListener(new Resizer(450, 295));
mediaWriter.addListener(new CodecChanger());
mediaWriter.addListener(new ProgressListener(reader.getContainer()));
// create a media viewer with stats enabled for debugging
//IMediaViewer mediaViewer = ToolFactory.makeViewer(true);
// add a viewer to the reader, to see the decoded media
//reader.addListener(mediaViewer);
// read and decode packets from the source file and
// and dispatch decoded audio and video to the writer
while (reader.readPacket() == null);
// Incomplete transcoding
if( reader.isOpen() ){
System.out.println("Transcoding incomplete, removing incomplete files!");
reader.close();
mediumFile.delete();
smallFile.delete();
}
System.out.println("Done!");
}
}
class Resizer extends MediaToolAdapter {
private Integer width;
private Integer height;
private IVideoResampler videoResampler = null;
public Resizer(Integer aWidth, Integer aHeight) {
this.width = aWidth;
this.height = aHeight;
}
@Override
public void onVideoPicture(IVideoPictureEvent event) {
IVideoPicture pic = event.getPicture();
if (videoResampler == null) {
videoResampler = IVideoResampler.make(width, height, pic.getPixelType(), pic.getWidth(), pic
.getHeight(), pic.getPixelType());
}
IVideoPicture out = IVideoPicture.make(pic.getPixelType(), width, height);
videoResampler.resample(out, pic);
IVideoPictureEvent asc = new VideoPictureEvent(event.getSource(), out, event.getStreamIndex());
super.onVideoPicture(asc);
out.delete();
}
}
class ProgressListener extends MediaToolAdapter {
private long currentLength;
private long totalLength;
public ProgressListener(IContainer c) {
this.totalLength = c.getDuration();
}
@Override
public void onVideoPicture(IVideoPictureEvent event) {
currentLength = event.getTimeStamp();
System.out.println(currentLength+" / "+totalLength+" - "+getProgress());
}
public long getProcessedLength(){
return currentLength;
}
public long getTotalLength(){
return totalLength;
}
public int getProgress(){
return (int)(((double)currentLength/totalLength)*100);
}
}
class CodecChanger extends MediaListenerAdapter {
/*
* HTML5
* video codec - avc1.42E01E i.e. H.264/MPEG-4 AVC
* audio codec - mp4a.40.2 i.e. MPEG-4 AAC LC
*/
public void onAddStream(IAddStreamEvent event) {
// put your stream specific configuration code here
// you can get the container from the writer and
// get the specific stream from the container using
// the stream index in the event
int streamIndex = event.getStreamIndex();
IStream stream = event.getSource().getContainer().getStream(streamIndex);
ICodec.Type codecType = stream.getStreamCoder().getCodecType();
if(codecType == ICodec.Type.CODEC_TYPE_AUDIO){
applyAudioSettings(stream);
} else {
applyVideoSettings(stream);
}
}
private void applyVideoSettings(IStream stream) {
IStreamCoder coder = stream.getStreamCoder();
coder.setCodec(ICodec.ID.CODEC_ID_H264);
coder.setBitRate( 500000 );
//IVideoResampler.make(outWidth, outHeight, outContainer.getPixelType(), inContainer.getWidth(), inContainer.getHeight(), inContainer.getPixelType());
}
private void applyAudioSettings(IStream stream) {
IStreamCoder coder = stream.getStreamCoder();
// ICodec.ID.CODEC_ID_MP3
coder.setCodec( ICodec.ID.CODEC_ID_AAC );
//coder.setSampleRate( 44000 );
coder.setBitRate( 128 );
//IAudioResampler.make(out.getChannels(), in.getChannels(), out.getSampleRate(), in.getSampleRate());
}
}
class SetVideoTranscodeListener extends MediaToolAdapter {
@Override
public void onAddStream(IAddStreamEvent event) {
int streamIndex = event.getStreamIndex();
IStreamCoder streamCoder = event.getSource().getContainer().getStream(streamIndex).getStreamCoder();
if (streamCoder.getCodecType() == ICodec.Type.CODEC_TYPE_VIDEO) {
streamCoder.setCodec(ICodec.findEncodingCodec(ICodec.ID.CODEC_ID_H264));
int retval = Configuration.configure("/usr/local/xuggler/share/ffmpeg/libx264-superfast.ffpreset", streamCoder);
if (retval<0)
throw new RuntimeException("cound not cofigure coder from preset file");
}
super.onAddStream(event);
}
}