class Program
{
static void Main(string[] args){
Resolver resolver = new Resolver();
resolver.Register<Shopper, Shopper>();
resolver.Register<ICreditCard, MasterCard>();
var shoper = resolver.Resolve<Shopper>();
shopper.Charge();
Console.Read();
}
}
public class Resolver
{
private Dictionary<Type, Type> dependencyMap = new Dictionary<Type, Type>();
public T Resolve<T>()
{
return (T)Resolve(typeof(T));
private object Resolve(Type typeToResolve)
{
Type resolvedType = null;
try{
resolvedType = dependencyMap[typeToResolve];
}
catch
{
throw new Exception(string.Format("Could not resolve type {0}", typeToResolve.FullName));
}
var firstConstructor = resolvedType.GetConstructors().First();
var constructorParameters = firstConstructor.GetParameters();
if(constructorParameters.Count() == 0)
return Activator.CreateInstance(resolvedType);
IList<object> parameters = new List<object>();
foreach(var parameterToResolve in constructorParameters)
{
parameters.Add(Resolve(parameterToResolve.ParameterType);
}
return firstConstructor.Invoke(parameters.ToArray());
}
public void Register<TFrom, TTo>()
{
dependencyMap.Add(typeof(TFrom), typeof(TTo));
}
}
public class Visa : ICreditCard
{
public string Charge()
{
return "Charging with the Visa!";
}
}
public class MasterCard : ICreditCard
{
public string Charge()
{
return "Charging with the MasterCard!";
}
}
public interface ICreditCard
{
string Charge();
}
}
Reference: Pluralsight course on Inversion of Control by John Sonmez
Monday, March 11, 2013
Saturday, March 9, 2013
Wednesday, March 6, 2013
List Cycler with jQuery
<ul id="posts">
<li><label>Title 1</label>Description</li>
<li><label>Title 2</label>Description</li>
<li><label>Title 3</label>Description</li>
</ul>
Javascript function method
var cycler = function(){
var firstPost;
removeFirst = function(){
firstPost = $("#posts li:first");
firstPost.fadeOut(appendToEnd);
};
appendToEnd = function(post){
firstPost.remove();
$("#posts").append(firstPost);
};
return{
removeFirst : removeFirst,
appendToEnd : appendToEnd
}
}();
$(function(){
$("#cycler").click(function(){
cycler.removeFirst();
});
});
Javascript class method
var ListCycler = function(parentContainer){
var listContainer = $(parentContainer);var firstPost = $(parentContainer + " li:first");
cycle = function(){
firstPost.fadeOut(appendToEnd);
};
appendToEnd = function(post){
firstPost.remove();
listContainer.append(firstPost);
firstPost.fadeIn();
};
return{
cycle : cycle
}
};
$(function(){
$("#cycle").click(function(){
var cycler = new ListCycler("#posts");
cycler.cycle();
});
});
Reference: http://vimeo.com/47483575
Tuesday, March 5, 2013
Create Bootable Disk with ImgBurn
http://www.imgburn.com/index.php?act=download
http://www.allbootdisks.com/ (Choose .img for bootable disk)
Friday, March 1, 2013
Enable NetFX3 in Windows Server 2012
C:\Users\Administrator>dism.exe /online /enable-feature /featurename:NetFX3Serve
rFeatures /Source:e:\sources\sxs /LimitAccess
Deployment Image Servicing and Management tool
Version: 6.2.9200.16384
Image Version: 6.2.9200.16384
Enabling feature(s)
[==========================100.0%==========================]
The operation completed successfully.
C:\Users\Administrator>dism.exe /online /enable-feature /featurename:NetFX3 /Sou
rce:e:\sources\sxs /LimitAccess
Deployment Image Servicing and Management tool
Version: 6.2.9200.16384
Image Version: 6.2.9200.16384
Enabling feature(s)
[==========================100.0%==========================]
The operation completed successfully.
rFeatures /Source:e:\sources\sxs /LimitAccess
Deployment Image Servicing and Management tool
Version: 6.2.9200.16384
Image Version: 6.2.9200.16384
Enabling feature(s)
[==========================100.0%==========================]
The operation completed successfully.
C:\Users\Administrator>dism.exe /online /enable-feature /featurename:NetFX3 /Sou
rce:e:\sources\sxs /LimitAccess
Deployment Image Servicing and Management tool
Version: 6.2.9200.16384
Image Version: 6.2.9200.16384
Enabling feature(s)
[==========================100.0%==========================]
The operation completed successfully.
Thursday, February 28, 2013
Issue arises after fresh install of Windows Server 2012 and SQL Server 2012
What could possibly have caused this error?
Server Error in '/' Application.
Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies. Access is denied.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.IO.FileLoadException: Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies. Access is denied.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Assembly Load Trace: The following information can be helpful to determine why the assembly 'AjaxControlToolkit' could not be loaded.
WRN: Assembly binding logging is turned OFF. To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1. Note: There is some performance penalty associated with assembly bind failure logging. To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].
Stack Trace:
[FileLoadException: Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies. Access is denied.] System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +0 System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +210 System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean forIntrospection) +242 System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +17 System.Reflection.Assembly.Load(String assemblyString) +35 System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +122 [ConfigurationErrorsException: Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies. Access is denied.] System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +12759734 System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory() +503 System.Web.Configuration.AssemblyInfo.get_AssemblyInternal() +142 System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +334 System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath) +203 System.Web.Compilation.BuildManager.ExecutePreAppStart() +152 System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +1151 [HttpException (0x80004005): Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies. Access is denied.] System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +12880068 System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +159 System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +12721257
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18033
Server Error in '/' Application.
Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies. Access is denied.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.IO.FileLoadException: Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies. Access is denied.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Assembly Load Trace: The following information can be helpful to determine why the assembly 'AjaxControlToolkit' could not be loaded.
WRN: Assembly binding logging is turned OFF. To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1. Note: There is some performance penalty associated with assembly bind failure logging. To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].
Stack Trace:
[FileLoadException: Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies. Access is denied.] System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +0 System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +210 System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean forIntrospection) +242 System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +17 System.Reflection.Assembly.Load(String assemblyString) +35 System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +122 [ConfigurationErrorsException: Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies. Access is denied.] System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +12759734 System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory() +503 System.Web.Configuration.AssemblyInfo.get_AssemblyInternal() +142 System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +334 System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath) +203 System.Web.Compilation.BuildManager.ExecutePreAppStart() +152 System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +1151 [HttpException (0x80004005): Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies. Access is denied.] System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +12880068 System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +159 System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +12721257
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18033
Wednesday, January 30, 2013
MCSD: Web Applications Solutions Developer
Exam 70-480: Programming in HTML5 with JavaScript and CSS3 (Publication Date: April 22, 2013)
Exam 70-486: Developing ASP.NET MVC 4 Web Applications (Publication Date: May 22, 2013)
Exam Ref 70-487: Developing Windows Azure and Web Services (Publication Date: June 22, 2013)
Exam 70-486: Developing ASP.NET MVC 4 Web Applications (Publication Date: May 22, 2013)
Exam Ref 70-487: Developing Windows Azure and Web Services (Publication Date: June 22, 2013)
Saturday, January 5, 2013
EF Unit of Work and Repository Pattern
GenericRepository.cs
namespace SCNData
{
public class GenericRepository<TEntity> where TEntity : class
{
internal NhacContext context;
internal DbSet<TEntity> dbSet;
public GenericRepository(NhacContext context)
{
this.context = context;
this.dbSet = context.Set<TEntity>();
}
public virtual IEnumerable<TEntity> Get(
Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string includeProperties = "")
{
IQueryable<TEntity> query = dbSet;
if (filter != null)
{
query = query.Where(filter);
}
foreach (var includeProperty in includeProperties.Split
(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
if (orderBy != null)
{
return orderBy(query).ToList();
}
else
{
return query.ToList();
}
}
public virtual TEntity GetByID(object id)
{
return dbSet.Find(id);
}
public virtual void Insert(TEntity entity)
{
dbSet.Add(entity);
}
public virtual void Delete(object id)
{
TEntity entityToDelete = dbSet.Find(id);
Delete(entityToDelete);
}
public virtual void Delete(TEntity entityToDelete)
{
if (context.Entry(entityToDelete).State == EntityState.Detached)
{
dbSet.Attach(entityToDelete);
}
dbSet.Remove(entityToDelete);
}
public virtual void Update(TEntity entityToUpdate)
{
dbSet.Attach(entityToUpdate);
context.Entry(entityToUpdate).State = EntityState.Modified;
}
}
}
UnitOfWork.cs
namespace SCNData
{
public class UnitOfWork : IDisposable
{
private NhacContext context = new NhacContext();
private GenericRepository<Performer> performerRepository;
public GenericRepository<Performer> PerformerRepository
{
get
{
if (this.performerRepository == null)
{
this.performerRepository = new GenericRepository<Performer>(context);
}
return performerRepository;
}
}
public void Save()
{
context.SaveChanges();
}
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
context.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
namespace SCNData
{
public class GenericRepository<TEntity> where TEntity : class
{
internal NhacContext context;
internal DbSet<TEntity> dbSet;
public GenericRepository(NhacContext context)
{
this.context = context;
this.dbSet = context.Set<TEntity>();
}
public virtual IEnumerable<TEntity> Get(
Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string includeProperties = "")
{
IQueryable<TEntity> query = dbSet;
if (filter != null)
{
query = query.Where(filter);
}
foreach (var includeProperty in includeProperties.Split
(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
if (orderBy != null)
{
return orderBy(query).ToList();
}
else
{
return query.ToList();
}
}
public virtual TEntity GetByID(object id)
{
return dbSet.Find(id);
}
public virtual void Insert(TEntity entity)
{
dbSet.Add(entity);
}
public virtual void Delete(object id)
{
TEntity entityToDelete = dbSet.Find(id);
Delete(entityToDelete);
}
public virtual void Delete(TEntity entityToDelete)
{
if (context.Entry(entityToDelete).State == EntityState.Detached)
{
dbSet.Attach(entityToDelete);
}
dbSet.Remove(entityToDelete);
}
public virtual void Update(TEntity entityToUpdate)
{
dbSet.Attach(entityToUpdate);
context.Entry(entityToUpdate).State = EntityState.Modified;
}
}
}
UnitOfWork.cs
namespace SCNData
{
public class UnitOfWork : IDisposable
{
private NhacContext context = new NhacContext();
private GenericRepository<Performer> performerRepository;
public GenericRepository<Performer> PerformerRepository
{
get
{
if (this.performerRepository == null)
{
this.performerRepository = new GenericRepository<Performer>(context);
}
return performerRepository;
}
}
public void Save()
{
context.SaveChanges();
}
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
context.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
EF Repository Pattern
IPerformerRepository.cs
namespace SCNData
{
public interface IPerformerRepository : IDisposable
{
IEnumerable<Performer> GetPerformers();
Performer GetPerformerByID(int performerId);
void InsertPerformer(Performer performer);
void DeletePerformer(int performerID);
void UpdatePerformer(Performer performer);
void Save();
}
}
PerformerRepository.cs
namespace SCNData
{
public class PerformerRepository : IPerformerRepository, IDisposable
{
private NhacContext context;
public PerformerRepository(NhacContext context)
{
this.context = context;
}
public IEnumerable<Performer> GetPerformers()
{
return context.Performers.ToList();
}
public Performer GetPerformerByID(int id)
{
return context.Performers.Find(id);
}
public void InsertPerformer(Performer performer)
{
context.Performers.Add(performer);
}
public void DeletePerformer(int performerId)
{
Performer performer = context.Performers.Find(performerId);
context.Performers.Remove(performer);
}
public void UpdatePerformer(Performer performer)
{
context.Entry(performer).State = EntityState.Modified;
}
public void Save()
{
context.SaveChanges();
}
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
context.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
namespace SCNData
{
public interface IPerformerRepository : IDisposable
{
IEnumerable<Performer> GetPerformers();
Performer GetPerformerByID(int performerId);
void InsertPerformer(Performer performer);
void DeletePerformer(int performerID);
void UpdatePerformer(Performer performer);
void Save();
}
}
PerformerRepository.cs
namespace SCNData
{
public class PerformerRepository : IPerformerRepository, IDisposable
{
private NhacContext context;
public PerformerRepository(NhacContext context)
{
this.context = context;
}
public IEnumerable<Performer> GetPerformers()
{
return context.Performers.ToList();
}
public Performer GetPerformerByID(int id)
{
return context.Performers.Find(id);
}
public void InsertPerformer(Performer performer)
{
context.Performers.Add(performer);
}
public void DeletePerformer(int performerId)
{
Performer performer = context.Performers.Find(performerId);
context.Performers.Remove(performer);
}
public void UpdatePerformer(Performer performer)
{
context.Entry(performer).State = EntityState.Modified;
}
public void Save()
{
context.SaveChanges();
}
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
context.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
Friday, December 28, 2012
Java JDBC
ILookup.java
import java.util.List;
public interface ILookup {
void SaveStudentSurveyFormData(StudentBean postData);
StudentBean GetStudentSurveyData(String studentId);
Surveys GetSurveys();
List<String> GetSurveyIds();
}
StudentDbDAO.java
package gmu.swe642.hw6;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class StudentDbDAO implements ILookup {
private Connection con;
public StudentDbDAO(){
try {
Class.forName ("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection ( "jdbc:oracle:thin:@",
dbusername, dbpassword);
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public void SaveStudentSurveyFormData(StudentBean postData){
try {
PreparedStatement pstat = con.prepareStatement("insert into survey values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
pstat.setString(1, postData.getStudentId());
pstat.setString(2, postData.getFirstName());
pstat.setString(3, postData.getLastName());
pstat.setString(4, postData.getStreet());
pstat.setString(5, postData.getZip());
pstat.setString(6, postData.getCity());
pstat.setString(7, postData.getState());
pstat.setString(8, postData.getTelephone());
pstat.setString(9, postData.getEmail());
pstat.setString(10, postData.getUrl());
pstat.setString(11, postData.getDateOfSurvey());
pstat.setString(12, postData.getGraduationMonth());
pstat.setString(13, postData.getGraduationYear());
pstat.setString(14, postData.getLikes());
pstat.setString(15, postData.getInterests());
pstat.setString(16, postData.getRecommendation());
pstat.setString(17, postData.getComments());
pstat.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public StudentBean GetStudentSurveyData(String studentId){
Surveys surveys = GetSurveys();
for(StudentBean survey : surveys.data){
if(survey.getStudentId().equalsIgnoreCase(studentId)){
return survey;
}
}
return null;
}
public Surveys GetSurveys(){
Surveys surveys = new Surveys();
surveys.data = new ArrayList<StudentBean>();
Statement stmt;
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from survey");
while (rs.next())
{
String studentId = rs.getString(Consts.STUDENTID);
String firstName = rs.getString(Consts.FIRSTNAME);
String lastName = rs.getString(Consts.LASTNAME);
String street = rs.getString(Consts.STREET);
String zip = rs.getString(Consts.ZIP);
String city = rs.getString(Consts.CITY);
String state = rs.getString(Consts.STATE);
String telephone = rs.getString(Consts.TELEPHONE);
String email = rs.getString(Consts.EMAIL);
String url = rs.getString(Consts.URL);
String dateOfSurvey = rs.getString(Consts.DATEOFSURVEY);
String graduationMonth = rs.getString(Consts.GRADUATIONMONTH);
String graduationYear = rs.getString(Consts.GRADUATIONYEAR);
String likes = rs.getString(Consts.LIKES);
String interests = rs.getString(Consts.INTERESTS);
String recommendation = rs.getString(Consts.RECOMMENDATION);
String comments = rs.getString(Consts.COMMENTS);
StudentBean s = new StudentBean(studentId, firstName, lastName, street, zip, city, state,
telephone, email, url, dateOfSurvey, graduationMonth,
graduationYear, likes, interests, recommendation, comments);
surveys.data.add(s);
}
} catch (SQLException e) {
e.printStackTrace();
}
return surveys;
}
public List<String> GetSurveyIds(){
List<String> surveyIds = new ArrayList<String>();
Surveys surveys = GetSurveys();
for(StudentBean survey : surveys.data){
surveyIds.add(survey.getStudentId());
}
return surveyIds;
}
}
import java.util.List;
public interface ILookup {
void SaveStudentSurveyFormData(StudentBean postData);
StudentBean GetStudentSurveyData(String studentId);
Surveys GetSurveys();
List<String> GetSurveyIds();
}
StudentDbDAO.java
package gmu.swe642.hw6;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class StudentDbDAO implements ILookup {
private Connection con;
public StudentDbDAO(){
try {
Class.forName ("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection ( "jdbc:oracle:thin:@",
dbusername, dbpassword);
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public void SaveStudentSurveyFormData(StudentBean postData){
try {
PreparedStatement pstat = con.prepareStatement("insert into survey values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
pstat.setString(1, postData.getStudentId());
pstat.setString(2, postData.getFirstName());
pstat.setString(3, postData.getLastName());
pstat.setString(4, postData.getStreet());
pstat.setString(5, postData.getZip());
pstat.setString(6, postData.getCity());
pstat.setString(7, postData.getState());
pstat.setString(8, postData.getTelephone());
pstat.setString(9, postData.getEmail());
pstat.setString(10, postData.getUrl());
pstat.setString(11, postData.getDateOfSurvey());
pstat.setString(12, postData.getGraduationMonth());
pstat.setString(13, postData.getGraduationYear());
pstat.setString(14, postData.getLikes());
pstat.setString(15, postData.getInterests());
pstat.setString(16, postData.getRecommendation());
pstat.setString(17, postData.getComments());
pstat.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public StudentBean GetStudentSurveyData(String studentId){
Surveys surveys = GetSurveys();
for(StudentBean survey : surveys.data){
if(survey.getStudentId().equalsIgnoreCase(studentId)){
return survey;
}
}
return null;
}
public Surveys GetSurveys(){
Surveys surveys = new Surveys();
surveys.data = new ArrayList<StudentBean>();
Statement stmt;
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from survey");
while (rs.next())
{
String studentId = rs.getString(Consts.STUDENTID);
String firstName = rs.getString(Consts.FIRSTNAME);
String lastName = rs.getString(Consts.LASTNAME);
String street = rs.getString(Consts.STREET);
String zip = rs.getString(Consts.ZIP);
String city = rs.getString(Consts.CITY);
String state = rs.getString(Consts.STATE);
String telephone = rs.getString(Consts.TELEPHONE);
String email = rs.getString(Consts.EMAIL);
String url = rs.getString(Consts.URL);
String dateOfSurvey = rs.getString(Consts.DATEOFSURVEY);
String graduationMonth = rs.getString(Consts.GRADUATIONMONTH);
String graduationYear = rs.getString(Consts.GRADUATIONYEAR);
String likes = rs.getString(Consts.LIKES);
String interests = rs.getString(Consts.INTERESTS);
String recommendation = rs.getString(Consts.RECOMMENDATION);
String comments = rs.getString(Consts.COMMENTS);
StudentBean s = new StudentBean(studentId, firstName, lastName, street, zip, city, state,
telephone, email, url, dateOfSurvey, graduationMonth,
graduationYear, likes, interests, recommendation, comments);
surveys.data.add(s);
}
} catch (SQLException e) {
e.printStackTrace();
}
return surveys;
}
public List<String> GetSurveyIds(){
List<String> surveyIds = new ArrayList<String>();
Surveys surveys = GetSurveys();
for(StudentBean survey : surveys.data){
surveyIds.add(survey.getStudentId());
}
return surveyIds;
}
}
Apache Struts with Actions and Form Beans
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>swe642hw5khuc</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
struts-config.xml
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
"http://struts.apache.org/dtds/struts-config_1_3.dtd">
<struts-config>
<form-beans>
<form-bean name="surveyFormBean" type="package.SurveyFormBean"/>
<form-bean name="surveyLookupFormBean" type="package.SurveyLookupFormBean"/>
</form-beans>
<action-mappings>
<action path="/submitSurvey" type="package.SubmitSurveyAction" name="surveyFormBean" scope="session">
<forward name="simple-ack" path="/jsp/SimpleAcknowledgementJSP.jsp" />
<forward name="winner-ack" path="/jsp/WinnerAcknowledgementJSP.jsp" />
</action>
<action path="/displaySurvey" type="package.DisplaySurveyAction" scope="session">
<forward name="survey-found" path="/jsp/StudentJSP.jsp" />
<forward name="survey-not-found" path="/jsp/NoSuchStudentJSP.jsp" />
</action>
</action-mappings>
</struts-config>
SubmitSurveyAction.java
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class SubmitSurveyAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception{
SurveyFormBean formBean = (SurveyFormBean)form;
StudentBean studentBean = new StudentBean(formBean.getStudentId(),formBean.getFirstName(), formBean.getLastName(),
formBean.getStreet(), formBean.getZip(), formBean.getCity(), formBean.getState(),
formBean.getTelephone(), formBean.getEmail(), formBean.getUrl(), formBean.getDateOfSurvey(),
formBean.getGraduationMonth(), formBean.getGraduationYear(), formBean.getLikes(),
formBean.getInterests(), formBean.getRecommendation(), formBean.getComments());
StudentDAO.SaveStudentSurveyFormData(studentBean);
DataBean dataBean = DataProcessor.ComputeMeanAndStandardDeviation(formBean.getData());
List<String> surveyIdsBean = StudentDAO.GetSurveyIds();
HttpSession session = request.getSession();
session.setAttribute("student", studentBean);
session.setAttribute("data", dataBean);
session.setAttribute("surveys", surveyIdsBean);
if(dataBean.getMean() > 90){
return mapping.findForward("winner-ack");
}
return mapping.findForward("simple-ack");
}
}
DisplaySurveyAction.java
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class DisplaySurveyAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception{
String studentId = request.getParameter("studentId");
StudentBean studentBean = null;
if(studentId != null){
studentBean = StudentDAO.GetStudentSurveyData(studentId);
}
HttpSession session = request.getSession();
if(studentBean == null){
session.setAttribute("badId", studentId);
return mapping.findForward("survey-not-found");
}
else{
session.setAttribute("student", studentBean);
return mapping.findForward("survey-found");
}
}
}
SurveyFormBean.java
import org.apache.struts.action.ActionForm;
@SuppressWarnings("serial")
public class SurveyFormBean extends ActionForm {
private String studentId;
private String firstName;
private String lastName;
private String street;
private String zip;
private String city;
private String state;
private String telephone;
private String email;
private String url;
private String dateOfSurvey;
private String graduationMonth;
private String graduationYear;
private String[] likes;
private String interests;
private String recommendation;
private String comments;
private String data;
public String getStudentId(){
return this.studentId;
}
public void setStudentId(String studentId){
this.studentId = studentId;
}
public String getFirstName(){
return this.firstName;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public String getLastName(){
return this.lastName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
public String getStreet(){
return this.street;
}
public void setStreet(String street){
this.street = street;
}
public String getZip(){
return this.zip;
}
public void setZip(String zip){
this.zip = zip;
}
public String getCity(){
return this.city;
}
public void setCity(String city){
this.city = city;
}
public String getState(){
return this.state;
}
public void setState(String state){
this.state = state;
}
public String getTelephone(){
return this.telephone;
}
public void setTelephone(String telephone){
this.telephone = telephone;
}
public String getEmail(){
return this.email;
}
public void setEmail(String email){
this.email = email;
}
public String getUrl(){
return this.url;
}
public void setUrl(String url){
this.url = url;
}
public String getDateOfSurvey(){
return this.dateOfSurvey;
}
public void setDateOfSurvey(String dateOfSurvey){
this.dateOfSurvey = dateOfSurvey;
}
public String getGraduationMonth(){
return this.graduationMonth;
}
public void setGraduationMonth(String graduationMonth){
this.graduationMonth = graduationMonth;
}
public String getGraduationYear(){
return this.graduationYear;
}
public void setGraduationYear(String graduationYear){
this.graduationYear = graduationYear;
}
public String[] getLikes(){
return this.likes;
}
public void setLikes(String[] likes){
this.likes = likes;
}
public String getInterests(){
return this.interests;
}
public void setInterests(String interests){
this.interests = interests;
}
public String getRecommendation(){
return this.recommendation;
}
public void setRecommendation(String recommendation){
this.recommendation = recommendation;
}
public String getComments(){
return this.comments;
}
public void setComments(String comments){
this.comments = comments;
}
public String getData(){
return this.data;
}
public void setData(String data){
this.data = data;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>swe642hw5khuc</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
struts-config.xml
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
"http://struts.apache.org/dtds/struts-config_1_3.dtd">
<struts-config>
<form-beans>
<form-bean name="surveyFormBean" type="package.SurveyFormBean"/>
<form-bean name="surveyLookupFormBean" type="package.SurveyLookupFormBean"/>
</form-beans>
<action-mappings>
<action path="/submitSurvey" type="package.SubmitSurveyAction" name="surveyFormBean" scope="session">
<forward name="simple-ack" path="/jsp/SimpleAcknowledgementJSP.jsp" />
<forward name="winner-ack" path="/jsp/WinnerAcknowledgementJSP.jsp" />
</action>
<action path="/displaySurvey" type="package.DisplaySurveyAction" scope="session">
<forward name="survey-found" path="/jsp/StudentJSP.jsp" />
<forward name="survey-not-found" path="/jsp/NoSuchStudentJSP.jsp" />
</action>
</action-mappings>
</struts-config>
SubmitSurveyAction.java
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class SubmitSurveyAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception{
SurveyFormBean formBean = (SurveyFormBean)form;
StudentBean studentBean = new StudentBean(formBean.getStudentId(),formBean.getFirstName(), formBean.getLastName(),
formBean.getStreet(), formBean.getZip(), formBean.getCity(), formBean.getState(),
formBean.getTelephone(), formBean.getEmail(), formBean.getUrl(), formBean.getDateOfSurvey(),
formBean.getGraduationMonth(), formBean.getGraduationYear(), formBean.getLikes(),
formBean.getInterests(), formBean.getRecommendation(), formBean.getComments());
StudentDAO.SaveStudentSurveyFormData(studentBean);
DataBean dataBean = DataProcessor.ComputeMeanAndStandardDeviation(formBean.getData());
List<String> surveyIdsBean = StudentDAO.GetSurveyIds();
HttpSession session = request.getSession();
session.setAttribute("student", studentBean);
session.setAttribute("data", dataBean);
session.setAttribute("surveys", surveyIdsBean);
if(dataBean.getMean() > 90){
return mapping.findForward("winner-ack");
}
return mapping.findForward("simple-ack");
}
}
DisplaySurveyAction.java
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class DisplaySurveyAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception{
String studentId = request.getParameter("studentId");
StudentBean studentBean = null;
if(studentId != null){
studentBean = StudentDAO.GetStudentSurveyData(studentId);
}
HttpSession session = request.getSession();
if(studentBean == null){
session.setAttribute("badId", studentId);
return mapping.findForward("survey-not-found");
}
else{
session.setAttribute("student", studentBean);
return mapping.findForward("survey-found");
}
}
}
SurveyFormBean.java
import org.apache.struts.action.ActionForm;
@SuppressWarnings("serial")
public class SurveyFormBean extends ActionForm {
private String studentId;
private String firstName;
private String lastName;
private String street;
private String zip;
private String city;
private String state;
private String telephone;
private String email;
private String url;
private String dateOfSurvey;
private String graduationMonth;
private String graduationYear;
private String[] likes;
private String interests;
private String recommendation;
private String comments;
private String data;
public String getStudentId(){
return this.studentId;
}
public void setStudentId(String studentId){
this.studentId = studentId;
}
public String getFirstName(){
return this.firstName;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public String getLastName(){
return this.lastName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
public String getStreet(){
return this.street;
}
public void setStreet(String street){
this.street = street;
}
public String getZip(){
return this.zip;
}
public void setZip(String zip){
this.zip = zip;
}
public String getCity(){
return this.city;
}
public void setCity(String city){
this.city = city;
}
public String getState(){
return this.state;
}
public void setState(String state){
this.state = state;
}
public String getTelephone(){
return this.telephone;
}
public void setTelephone(String telephone){
this.telephone = telephone;
}
public String getEmail(){
return this.email;
}
public void setEmail(String email){
this.email = email;
}
public String getUrl(){
return this.url;
}
public void setUrl(String url){
this.url = url;
}
public String getDateOfSurvey(){
return this.dateOfSurvey;
}
public void setDateOfSurvey(String dateOfSurvey){
this.dateOfSurvey = dateOfSurvey;
}
public String getGraduationMonth(){
return this.graduationMonth;
}
public void setGraduationMonth(String graduationMonth){
this.graduationMonth = graduationMonth;
}
public String getGraduationYear(){
return this.graduationYear;
}
public void setGraduationYear(String graduationYear){
this.graduationYear = graduationYear;
}
public String[] getLikes(){
return this.likes;
}
public void setLikes(String[] likes){
this.likes = likes;
}
public String getInterests(){
return this.interests;
}
public void setInterests(String interests){
this.interests = interests;
}
public String getRecommendation(){
return this.recommendation;
}
public void setRecommendation(String recommendation){
this.recommendation = recommendation;
}
public String getComments(){
return this.comments;
}
public void setComments(String comments){
this.comments = comments;
}
public String getData(){
return this.data;
}
public void setData(String data){
this.data = data;
}
}
StudentDAO with FileReader and FilerWriter
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.*;
public class StudentDAO {
public static String fileName = "//data//temp//SurveyData.txt";
public static void SaveStudentSurveyFormData(StudentBean postData) throws IOException{
Surveys surveys = GetSurveys();
surveys.data.add(postData);
SaveFile(new Gson().toJson(surveys));
}
public static StudentBean GetStudentSurveyData(String studentId) throws IOException{
Surveys surveys = GetSurveys();
for(StudentBean survey : surveys.data){
if(survey.getStudentId().equalsIgnoreCase(studentId)){
return survey;
}
}
return null;
}
public static Surveys GetSurveys() throws IOException{
Surveys surveys = null;
String fileText = ReadFile();
if(fileText.length() > 0){
surveys = new Gson().fromJson(fileText, Surveys.class);
}
else{
surveys = new Surveys();
surveys.data = new ArrayList<StudentBean>();
}
return surveys;
}
public static List<String> GetSurveyIds() throws IOException{
List<String> surveyIds = new ArrayList<String>();
Surveys surveys = GetSurveys();
for(StudentBean survey : surveys.data){
surveyIds.add(survey.getStudentId());
}
return surveyIds;
}
public static String ReadFile() throws IOException{
BufferedReader file = new BufferedReader(new FileReader(fileName));
String line;
StringBuffer fileText = new StringBuffer();
while((line=file.readLine()) != null){
fileText.append(line);
}
file.close();
return fileText.toString();
}
public static void SaveFile(String fileText) throws IOException{
FileWriter fWriter = new FileWriter(fileName,false);
BufferedWriter writer = new BufferedWriter(fWriter);
fWriter.append(fileText);
writer.flush();
writer.close();
}
}
import java.util.ArrayList;
public class Surveys {
public ArrayList<StudentBean> data;
}
public class StudentBean {
private String studentId;
private String firstName;
private String lastName;
private String street;
private String zip;
private String city;
private String state;
private String telephone;
private String email;
private String url;
private String dateOfSurvey;
private String graduationMonth;
private String graduationYear;
private String likes;
private String interests;
private String recommendation;
private String comments;
public StudentBean(String studentId, String firstName, String lastName, String street, String zip,
String city, String state, String telephone, String email, String url, String dateOfSurvey,
String graduationMonth, String graduationYear, String likes, String interests,
String recommendation, String comments){
this.studentId = studentId;
this.firstName = firstName;
this.lastName = lastName;
this.street = street;
this.zip = zip;
this.city = city;
this.state = state;
this.telephone = telephone;
this.email = email;
this.url = url;
this.dateOfSurvey = dateOfSurvey;
this.graduationMonth = graduationMonth;
this.graduationYear = graduationYear;
this.likes = likes;
this.interests = interests;
this.recommendation = recommendation;
this.comments = comments;
}
public String getStudentId(){
return this.studentId;
}
public String getFirstName(){
return this.firstName;
}
public String getLastName(){
return this.lastName;
}
public String getStreet(){
return this.street;
}
public String getZip(){
return this.zip;
}
public String getCity(){
return this.city;
}
public String getState(){
return this.state;
}
public String getTelephone(){
return this.telephone;
}
public String getEmail(){
return this.email;
}
public String getUrl(){
return this.url;
}
public String getDateOfSurvey(){
return this.dateOfSurvey;
}
public String getGraduationMonth(){
return this.graduationMonth;
}
public String getGraduationYear(){
return this.graduationYear;
}
public String getLikes(){
return this.likes;
}
public String getInterests(){
return this.interests;
}
public String getRecommendation(){
return this.recommendation;
}
public String getComments(){
return this.comments;
}
}
Java Servlet with RequestDispatcher
import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/Display")
public class Display extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String studentId = request.getParameter("studentid");
String address = "jsp/StudentJSP.jsp";
StudentBean studentBean = null;
if(studentId != null){
studentBean = StudentDAO.GetStudentSurveyData(studentId);
}
HttpSession session = request.getSession();
if(studentBean == null){
address = "jsp/NoSuchStudentJSP.jsp";
session.setAttribute("badId", studentId);
}
else{
session.setAttribute("student", studentBean);
}
RequestDispatcher dispatcher = request.getRequestDispatcher(address);
dispatcher.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String studentId = request.getParameter("studentId");
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String street = request.getParameter("street");
String zip = request.getParameter("zip");
String city = request.getParameter("city");
String state = request.getParameter("state");
String telephone = request.getParameter("telephone");
String email = request.getParameter("email");
String url = request.getParameter("url");
String dateOfSurvey = request.getParameter("dateOfSurvey");
String graduationMonth = request.getParameter("graduationMonth");
String graduationYear = request.getParameter("graduationYear");
String[] likes = request.getParameterValues("likes");
String interests = request.getParameter("interests");
String recommendation = request.getParameter("recommendation");
String comments = request.getParameter("comments");
String data = request.getParameter("data");
String likesString = "";
for(int i=0; i< likes.length; i++){
likesString += likes[i] + ", ";
}
likesString = likesString.substring(0, likesString.length() - 2);
StudentBean studentBean = new StudentBean(studentId, firstName, lastName, street, zip, city, state,
telephone, email, url, dateOfSurvey, graduationMonth,
graduationYear, likesString, interests, recommendation, comments);
StudentDAO.SaveStudentSurveyFormData(studentBean);
DataBean dataBean = DataProcessor.ComputeMeanAndStandardDeviation(data);
List<String> surveyIdsBean = StudentDAO.GetSurveyIds();
HttpSession session = request.getSession();
session.setAttribute("student", studentBean);
session.setAttribute("data", dataBean);
session.setAttribute("surveys", surveyIdsBean);
String address = "jsp/SimpleAcknowledgementJSP.jsp";
if(dataBean.getMean() > 90){
address = "jsp/WinnerAcknowledgementJSP.jsp";
}
RequestDispatcher dispatcher = request.getRequestDispatcher(address);
dispatcher.forward(request, response);
}
}
Wednesday, November 21, 2012
Java RMI
1) Compute.java
package compute;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface Compute extends Remote {
<T> T executeTask(Task<T> t) throws RemoteException;
}
2) Task.java
package compute;
public interface Task<T> {
T execute();
}
cd c:\home\waldo\src
javac compute\Compute.java compute\Task.java
jar cvf compute.jar compute\*.class
3) ComputeEngine.java
package engine;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import compute.Compute;
import compute.Task;
public class ComputeEngine implements Compute{
public ComputeEngine(){
super();
}
public<T> T executeTask(Task<T> t){
return t.execute();
}
public static void main(String[] args){
if(System.getSecurityManager() == null){
System.setSecurityManager(new SecurityManager());
}
try{
String name = "Compute";
Compute engine = new ComputeEngine();
Compute stub = (Compute) UnicastRemoteObject.exportObject(engine, 0);
Registry registry = LocateRegistry.getRegistry();
registry.rebind(name, stub);
} catch(Exception e){
System.err.println("ComputeEngine exception: ");
e.printStackTrace();
}
}
}
cd c:\home\ann\src
javac -cp c:\home\ann\public_html\classes\compute.jar
engine\ComputeEngine.java
Pi.java
package client;
import compute.Task;
import java.io.Serializable;
import java.math.BigDecimal;
public class Pi implements Task<BigDecimal>, Serializable{
private final int digits;
public Pi(int digits){
this.digits = digits;
}
public BigDecimal execute(){
return computePi(digits);
}
public static BigDecimal computePi(int digits){
return result;
}
}
ComputPi.java
package client;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.math.BigDecimal;
import compute.Compute;
public class ComputePi{
public static void main(String args[]){
if(System.getSecurityManager() == null){
System.setSecurityManager(new SecurityManager());
}
try{
String name = "Compute";
Registry registry = LocateRegistry.getRegistry(args[0]);
Compute comp = (Compute) registry.lookup(name);
Pi task = new Pi(Integer.parseInt(args[1]);
BigDecimal pi = comp.executeTask(task);
System.out.println(pi);
} catch(Exception e){
System.err.println("ComputerPi exception:");
e.printStackTrace();
}
}
}
cd c:\home\jones\src
javac -cp c:\home\jones\public_html\classes\compute.jar
client\ComputePi.java client\Pi.java
mkdir c:\home\jones\public_html\classes\client
cp client\Pi.class
c:\home\jones\public_html\classes\client
server.policy
grant codeBase "file:/home/ann/src/" {
permission java.security.AllPermission;
};
client.policy
grant codeBase "file:/home/jones/src/" {
permission java.security.AllPermission;
};
start rmiregistry (or javaw if start is not available)
java -cp c:\home\ann\src;c:\home\ann\public_html\classes\compute.jar
-Djava.rmi.server.codebase=file:/c:/home/ann/public_html/classes/compute.jar
-Djava.rmi.server.hostname=mycomputer.example.com
-Djava.security.policy=server.policy
engine.ComputeEngine
java -cp c:\home\jones\src;c:\home\jones\public_html\classes\compute.jar
-Djava.rmi.server.codebase=file:/c:/home/jones/public_html/classes/
-Djava.security.policy=client.policy
client.ComputePi mycomputer.example.com 45
package compute;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface Compute extends Remote {
<T> T executeTask(Task<T> t) throws RemoteException;
}
2) Task.java
package compute;
public interface Task<T> {
T execute();
}
cd c:\home\waldo\src
javac compute\Compute.java compute\Task.java
jar cvf compute.jar compute\*.class
3) ComputeEngine.java
package engine;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import compute.Compute;
import compute.Task;
public class ComputeEngine implements Compute{
public ComputeEngine(){
super();
}
public<T> T executeTask(Task<T> t){
return t.execute();
}
public static void main(String[] args){
if(System.getSecurityManager() == null){
System.setSecurityManager(new SecurityManager());
}
try{
String name = "Compute";
Compute engine = new ComputeEngine();
Compute stub = (Compute) UnicastRemoteObject.exportObject(engine, 0);
Registry registry = LocateRegistry.getRegistry();
registry.rebind(name, stub);
} catch(Exception e){
System.err.println("ComputeEngine exception: ");
e.printStackTrace();
}
}
}
cd c:\home\ann\src
javac -cp c:\home\ann\public_html\classes\compute.jar
engine\ComputeEngine.java
Pi.java
package client;
import compute.Task;
import java.io.Serializable;
import java.math.BigDecimal;
public class Pi implements Task<BigDecimal>, Serializable{
private final int digits;
public Pi(int digits){
this.digits = digits;
}
public BigDecimal execute(){
return computePi(digits);
}
public static BigDecimal computePi(int digits){
return result;
}
}
ComputPi.java
package client;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.math.BigDecimal;
import compute.Compute;
public class ComputePi{
public static void main(String args[]){
if(System.getSecurityManager() == null){
System.setSecurityManager(new SecurityManager());
}
try{
String name = "Compute";
Registry registry = LocateRegistry.getRegistry(args[0]);
Compute comp = (Compute) registry.lookup(name);
Pi task = new Pi(Integer.parseInt(args[1]);
BigDecimal pi = comp.executeTask(task);
System.out.println(pi);
} catch(Exception e){
System.err.println("ComputerPi exception:");
e.printStackTrace();
}
}
}
cd c:\home\jones\src
javac -cp c:\home\jones\public_html\classes\compute.jar
client\ComputePi.java client\Pi.java
mkdir c:\home\jones\public_html\classes\client
cp client\Pi.class
c:\home\jones\public_html\classes\client
server.policy
grant codeBase "file:/home/ann/src/" {
permission java.security.AllPermission;
};
client.policy
grant codeBase "file:/home/jones/src/" {
permission java.security.AllPermission;
};
start rmiregistry (or javaw if start is not available)
java -cp c:\home\ann\src;c:\home\ann\public_html\classes\compute.jar
-Djava.rmi.server.codebase=file:/c:/home/ann/public_html/classes/compute.jar
-Djava.rmi.server.hostname=mycomputer.example.com
-Djava.security.policy=server.policy
engine.ComputeEngine
java -cp c:\home\jones\src;c:\home\jones\public_html\classes\compute.jar
-Djava.rmi.server.codebase=file:/c:/home/jones/public_html/classes/
-Djava.security.policy=client.policy
client.ComputePi mycomputer.example.com 45
Thursday, November 8, 2012
Objective-C Header and Class Implementation
Person.h
#import <Foundation/Foundation.h>
@interface Person:NSObject{
NSString *name;
int age;
}
- (NSString *)name;
- (void) setName: (NSString *) newName;
- (int)age;
- (void) setAge: (int) newAge;
//actions
- (BOOL) isAllowedToVote;
- (void castBallot;
@end
Person.m
#import "Person.h"
@implementation Person
- (int) age{
return age;
}
- (void) setAge: (int) value{
age = value;
}
//... and other methods
@end
Using a class
id anObject = [[SomeClass alloc] init];
- (id) init
{
self = [super init];
if(self){
//initializations
}
return self;
}
- (Person *) createPersonWithName: (NSString *) aName{
Person *aPerson = [[Person alloc] init];
[aPerson setName:aName];
[aPerson setAge:21];
return aPerson;
}
Class Inheritance
@interface Student : Person {
NSString *major;
}
@end
@implementation Student
// Constructor for a student
- (id) init
{
self = [super init];
if(self != nil){
//set attributes
[self setMajor:@"Undefined"];
}
return self;
}
@end
Objective-C Selector
id object;
SEL anAction = @selector(action:);
if([object respondsToSelector:anAction]){
[object performSelector:anAction withObject:self];
}
SEL anAction = @selector(action:);
if([object respondsToSelector:anAction]){
[object performSelector:anAction withObject:self];
}
Objective-C Object Messaging
[receiver message]
[receiver message:argument]
[receiver message:arg1 argument2:arg2]
int status = [receiver message];
[receiver makeGroup:group, memberOne, memberTwo, memberThree];
[rectangle draw]
[rectangle setColor:blue]
[rectangle setStrokeColor:blue andThickness:2.0]
double length = [rectangle circumference];
[NSArray arrayWithObjects:one, two, three, nil];
[receiver message:argument]
[receiver message:arg1 argument2:arg2]
int status = [receiver message];
[receiver makeGroup:group, memberOne, memberTwo, memberThree];
[rectangle draw]
[rectangle setColor:blue]
[rectangle setStrokeColor:blue andThickness:2.0]
double length = [rectangle circumference];
[NSArray arrayWithObjects:one, two, three, nil];
Java vs. Objective-C
Java
Rectangle rect = Rectangle(someWidth, someHeight);
println(rect.getHeight());
boolean inside = rect.contains(x,y);
Objective-C
Rectangle *rect = [[Rectangle alloc] initWithWidth:someWidth andHeight:someHeight];
NSLog(@"%f", [rect height]);
BOOL inside = [rect containsPointWithX:x andY:y]
Rectangle rect = Rectangle(someWidth, someHeight);
println(rect.getHeight());
boolean inside = rect.contains(x,y);
Objective-C
Rectangle *rect = [[Rectangle alloc] initWithWidth:someWidth andHeight:someHeight];
NSLog(@"%f", [rect height]);
BOOL inside = [rect containsPointWithX:x andY:y]
Objective-C Identiy vs. Equality
// test for object identity:
BOOL identical = @"Peter" == @"Peter"; //YES
identical = @"Peter" == @" Peter "; //NO
// test for string equality: will return YES
NSString *aName = @"Peter";
NSMutableString *anotherName = [NSMutableString stringWithString:@"P"];
[anotherName appendString:@"eter"];
BOOL same = [aName isEqualToString:anotherName]; //YES
BOOL equal = (aName == anotherName); //NO
// test for existence
BOOL exists = (object != nil);
BOOL identical = @"Peter" == @"Peter"; //YES
identical = @"Peter" == @" Peter "; //NO
// test for string equality: will return YES
NSString *aName = @"Peter";
NSMutableString *anotherName = [NSMutableString stringWithString:@"P"];
[anotherName appendString:@"eter"];
BOOL same = [aName isEqualToString:anotherName]; //YES
BOOL equal = (aName == anotherName); //NO
// test for existence
BOOL exists = (object != nil);
Saturday, October 20, 2012
Javascript Namespace with Require.js
index.html
<script src="scripts/require.js" data-main="scripts/lib/main.js"></script>
main.js
require(["Order"], function(Order){
var o = new Order(1, "A Customer");
alert(o.id);
alert(o.customer.name);
});
Order.js
define('"Customer"], // Required scripts (Customer)
function(Customer){ // Get Required objects
function Order(id, custName){
this.id = id;
this.customer = new Customer(custName);
}
return Order;
}
);
Customer.js
define([],
function(){
function Customer(name){
this.name = name;
}
return Customer;
}
);
<script src="scripts/require.js" data-main="scripts/lib/main.js"></script>
main.js
require(["Order"], function(Order){
var o = new Order(1, "A Customer");
alert(o.id);
alert(o.customer.name);
});
Order.js
define('"Customer"], // Required scripts (Customer)
function(Customer){ // Get Required objects
function Order(id, custName){
this.id = id;
this.customer = new Customer(custName);
}
return Order;
}
);
Customer.js
define([],
function(){
function Customer(name){
this.name = name;
}
return Customer;
}
);
Javascript Namespace
main.js
$(function(){
var o = new ProjectNS.Order(1, "A Customer");
alert(o.id);
alert(o.customer.name);
});
order.js
(function(ns){
ns.Order = function(id, custName){
this.id = id,
this.customer = new ns.Customer(custName)
};
}(window.ProjectNS = window.ProjectNS || {}));
Customer.js
(function(ns){
ns.Customer = function(name){
this.name = name
};
}(window.ProjectNS = window.ProjectNS || {}));
$(function(){
var o = new ProjectNS.Order(1, "A Customer");
alert(o.id);
alert(o.customer.name);
});
order.js
(function(ns){
ns.Order = function(id, custName){
this.id = id,
this.customer = new ns.Customer(custName)
};
}(window.ProjectNS = window.ProjectNS || {}));
Customer.js
(function(ns){
ns.Customer = function(name){
this.name = name
};
}(window.ProjectNS = window.ProjectNS || {}));
Subscribe to:
Posts (Atom)

