Accessing HTTP Session and logged in user in GWT

3/17/2011 02:48:00 ÖS

(0) Comments

HttpServletRequest request = this.getThreadLocalRequest();
HttpSession session = request.getSession();
session.invalidate();

HttpServletRequest request = this.getThreadLocalRequest();
String username = request.getUserPrincipal().getName();

more info: http://developerlife.com/tutorials/?p=230

Yasin Hasan Karanfil

Apache Tomcat Realm JDBCRealm with Hibernate

3/17/2011 02:31:00 ÖS

(0) Comments

If you need a restriction to access of your java web project, you can use Apache Tomcat Realm feature. If you need to store users on db, and also access this users as a POJO in jour project, you need to use Hibernate as well, please follow this steps.

In hbm.xml file, define this table
<class name="com.karanfil.shared.Role" table="ROL_ROLES">
<meta attribute="class-description">
JDBC Realm Roles for Tomcat Authentication
</meta>
<id name="RoleName" type="string" length="25" column="ROL_ROLENAME">
</id>
</class>
<class name="com.karanfil.shared.User" table="USR_USERS">
<meta attribute="class-description">
JDBC Realm Users for Tomcat Authentication
</meta>
<id name="UserName" type="string" length="25" column="USR_USERNAME">
</id>
<property name="UserPass" type="string" length="25" column="USR_USERPASSWORD" not-null="true" />
<property name="FirstName" type="string" column="USR_FIRSTNAME" not-null="false" />
<property name="SurName" type="string" column="USR_SURNAME" not-null="false" />
<set name="UserRoles" table="USER_ROLES" cascade="all" lazy="true">
<key column="USR_USERNAME" />
<many-to-many column="ROL_ROLENAME" class="com.karanfil.shared.Role" />

After defining the objects, create POJO objects using Hibernate plug-in.

Now, open ApacheTomcat\conf\server.xml file
Add these lines
<Realm className="org.apache.catalina.realm.JDBCRealm"
driverName="org.gjt.mm.mysql.Driver"
connectionURL="jdbc:mysql://localhost/karanfil"
connectionName="root" connectionPassword="root"
userTable="USR_USERS" userNameCol="USR_USERNAME" userCredCol="USR_USERPASSWORD"
userRoleTable="USER_ROLES" roleNameCol="ROL_ROLENAME" />

Now in your project, WEB-INF\web.xml file
add these lines, and change it to make most suitable for your project.

<security-constraint>
<web-resource-collection>
<web-resource-name>MyFirst</web-resource-name>
<description> accessible by authenticated users of the tomcat role</description>
<url-pattern>*.jsp</url-pattern>
<url-pattern>*.html</url-pattern>
<url-pattern>*.htm</url-pattern>
<url-pattern>/brugwt/greet</url-pattern>
<url-pattern>/upload</url-pattern>
<url-pattern>/Worker</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
<http-method>PUT</http-method>
<http-method>DELETE</http-method>
</web-resource-collection>
<auth-constraint>
<description>These roles are allowed access</description>
<role-name>superuserrole</role-name>
<role-name>datainputrole</role-name>
<role-name>consultantrole</role-name>
</auth-constraint>
</security-constraint>

<login-config>
<auth-method>FORM</auth-method>
<realm-name>MyFirst Protected Area</realm-name>
<form-login-config>
<form-login-page>/login.html</form-login-page>
<form-error-page>/autherr.html</form-error-page>
</form-login-config>
</login-config>

<security-role>
<description>Only 'tomcat' role is allowed to access this web application</description>
<role-name>tomcat</role-name>
</security-role>

<security-role>
<description>Only 'administrator' role is allowed to access this web application</description>
<role-name>administrator</role-name>
</security-role>

Now the last step is creating users and roles on the db, you can do this using SQL or tools like MySql Query browser, Microsoft SQL Server Management Studio

Yasin Hasan Karanfil

Path is not a working copy directory Error

3/17/2011 02:30:00 ÖS

(0) Comments

If Subclipse complains about this error

Path is not a working copy directory
svn: '[original (pre-move) directory path]' is not a working copy

Doing things outside of Eclipse is more likely to create problems than solve
them.

To delete the cache, close Eclipse. The cache is stored in:
[workspace]/.metadata/.plugins/org.eclipse.core.resources/.projects/PROJECTNAME/.syncinfo

So you can just find and delete all files named .syncinfo in
[workspace]/.metadata/.plugins/org.eclipse.core.resources/.projects.

source:http://subclipse.tigris.org/ds/viewMessage.do?dsForumId=1047&dsMessageId=868799

Yasin Hasan Karanfil

Smartgwt File Upload

3/17/2011 02:22:00 ÖS

(0) Comments

Upload Canvas class for interface, and upload servlet for handling upload stream.
-----------------------------------
Upload.java
package edu.iastate.its.thinkspace.gwt.client.util.files;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.google.gwt.user.client.ui.NamedFrame;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.Encoding;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.Button;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.ValuesManager;
import com.smartgwt.client.widgets.form.fields.CheckboxItem;
import com.smartgwt.client.widgets.form.fields.FormItem;
import com.smartgwt.client.widgets.form.fields.HiddenItem;
import com.smartgwt.client.widgets.form.fields.UploadItem;
import com.smartgwt.client.widgets.form.fields.events.ChangedEvent;
import com.smartgwt.client.widgets.form.fields.events.ChangedHandler;
import com.smartgwt.client.widgets.layout.VStack;

public class Upload extends Canvas {
public static enum Mode {SIMPLE, COMPLEX};
public static final String TARGET="uploadTarget";

private DynamicForm uploadForm;
private UploadItem fileItem;
private UploadListener listener;
private List hiddenItems;
/**
*
*/
public Upload() {
this(null,Mode.SIMPLE);
}

/**
* @param args
*/
public Upload(Map args,Mode mode) {
initComplete(this);
List items = new ArrayList();
if (args != null) {
hiddenItems = new ArrayList();
for(String key: args.keySet()) {
HiddenItem item = new HiddenItem(key);
item.setValue(args.get(key));
items.add(item);
hiddenItems.add(item);
};
}
ValuesManager vm = new ValuesManager();
uploadForm = new DynamicForm();
uploadForm.setValuesManager(vm);
uploadForm.setEncoding(Encoding.MULTIPART);
uploadForm.setTarget(TARGET);

fileItem = new UploadItem("file");
fileItem.setTitle("File");
fileItem.setWidth(300);
items.add(fileItem);
fileItem.addChangedHandler(new ChangedHandler() {
public void onChanged(ChangedEvent e) {
System.out.println("change");
}
});
Button uploadButton = new Button("Upload");
uploadButton.addClickHandler(new ClickHandler(){
public void onClick(ClickEvent e) {
Object obj = fileItem.getDisplayValue();
if (obj != null) {
uploadForm.submitForm();
} else
SC.say("Please select a file.");
}
});
VStack stack = new VStack();
stack.setWidth100();
stack.setMembersMargin(10);
stack.setDefaultLayoutAlign(Alignment.CENTER);

NamedFrame frame = new NamedFrame(TARGET);
frame.setWidth("1");
frame.setHeight("1");
frame.setVisible(false);

VStack mainLayout = new VStack();
mainLayout.setWidth(300);
mainLayout.setHeight(200);

if (mode == Mode.COMPLEX) {
CheckboxItem unzip = new CheckboxItem("unzip");
unzip.setDefaultValue(true);
unzip.setTitle("Unzip .zip file");
items.add(unzip);
CheckboxItem overwrite = new CheckboxItem("overwrite");
overwrite.setDefaultValue(false);
overwrite.setTitle("Overwrite existing file");
items.add(overwrite);
CheckboxItem convertpdf = new CheckboxItem("convertpdf");
convertpdf.setDefaultValue(true);
convertpdf.setTitle("Convert Word document to PDF");
items.add(convertpdf);
CheckboxItem streaming = new CheckboxItem("streaming");
streaming.setDefaultValue(true);
streaming.setTitle("Convert video file to streaming format(flv)");
items.add(streaming);
CheckboxItem thumbnail = new CheckboxItem("thumbnail");
thumbnail.setDefaultValue(true);
thumbnail.setTitle("Make thumbnail(48x48) from image");
items.add(thumbnail);
}
FormItem[] fitems = new FormItem[items.size()];
items.toArray(fitems);
uploadForm.setItems(fitems);
stack.addMember(uploadForm);
stack.addMember(uploadButton);
mainLayout.addMember(stack);
mainLayout.addMember(frame);
addChild(mainLayout);
}

public String getFile() {
Object obj = fileItem.getValue();
if (obj == null)
return null;
else
return obj.toString();
}

public void setHiddenItem(String name, String value) {
for (HiddenItem item: hiddenItems)
if (item.getName().equals(name)) {
item.setValue(value);
return;
}
}

public void setAction(String url) {
uploadForm.setAction(url);
}

public void setUploadListener(UploadListener listener) {
this.listener = listener;
}

public void uploadComplete(String fileName) {
if (listener != null)
listener.uploadComplete(fileName);
}


private native void initComplete(Upload upload) /*-{
$wnd.uploadComplete = function (fileName) {
upload.@edu.iastate.its.thinkspace.gwt.client.util.files.Upload::uploadComplete(Ljava/lang/String;)(fileName);
};
}-*/;
}

-------------------------------------------
ProjectServlet.java
package edu.iastate.its.thinkspace.core.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import edu.iastate.its.thinkspace.core.ContextService;
import edu.iastate.its.thinkspace.core.ProjectContext;
import edu.iastate.its.thinkspace.core.ProjectState;
import edu.iastate.its.thinkspace.core.utils.Status;

/**
* @author Pete
*
*/
public class ProjectServlet extends HttpServlet {
private static Log log = LogFactory.getLog(ProjectServlet.class);

public ProjectServlet() {
}

public void doPost(HttpServletRequest request, HttpServletResponse response) {
process(request, response);
}

public void doGet(HttpServletRequest request, HttpServletResponse response) {
process(request, response);
}

private void process(HttpServletRequest request,
HttpServletResponse response) {
try {
if (ServletFileUpload.isMultipartContent(request)) {
processFiles(request, response);
} else {
processQuery(request, response);
}
} catch (Exception e) {
e.printStackTrace();
}
}

private void processQuery(HttpServletRequest request,
HttpServletResponse response) {
try {
String contextName = request.getParameter("context");
if (contextName == null) {
ProjectError.report(response, Status.MISSING_CONTEXT);
return;
}
ProjectContext context = ContextService.get().getContext(
contextName);
assert (context != null);
ProjectState state = (ProjectState) request.getSession()
.getAttribute(contextName);
Request req = new Request(request, response);
if (state != null)
state.request(req);
else {
response.sendRedirect("/thinkspace/logout");
}
} catch (Exception e) {
e.printStackTrace();
log.error(e);
}

}

private void processFiles(HttpServletRequest request,
HttpServletResponse response) {
HashMap args = new HashMap();
boolean isGWT = true;
try {
if (log.isDebugEnabled())
log.debug(request.getParameterMap());
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iter = upload.getItemIterator(request);
// pick up parameters first and note actual FileItem
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
if (item.isFormField()) {
args.put(name, Streams.asString(item.openStream()));
} else {
args.put("contentType", item.getContentType());
String fileName = item.getName();
int slash = fileName.lastIndexOf("/");
if (slash < 0)
slash = fileName.lastIndexOf("\\");
if (slash > 0)
fileName = fileName.substring(slash + 1);
args.put("fileName", fileName);
// upload requests can come from smartGWT (args) or
// FCKEditor (request)
String contextName = args.get("context");
String model = args.get("model");
String path = args.get("path");
if (contextName == null) {
isGWT = false;
contextName = request.getParameter("context");
model = request.getParameter("model");
path = request.getParameter("path");
if (log.isDebugEnabled())
log.debug("query=" + request.getQueryString());
} else if (log.isDebugEnabled())
log.debug(args);
ProjectContext context = ContextService.get().getContext(
contextName);
ProjectState state = (ProjectState) request.getSession()
.getAttribute(contextName);
InputStream in = null;
try {
in = item.openStream();
state.getFileManager().storeFile(
context.getModel(model), path + fileName, in);
} catch (Exception e) {
e.printStackTrace();
log.error("Fail to upload " + fileName + " to " + path);
} finally {
if (in != null)
try {
in.close();
} catch (Exception e) {
}
}
}
}
// TODO: need to handle conversion options and error reporting
response.setContentType("text/html");
response.setHeader("Pragma", "No-cache");
response.setDateHeader("Expires", 0);
response.setHeader("Cache-Control", "no-cache");
PrintWriter out = response.getWriter();
out.println("");
out.println("");
if (isGWT) {
out.println("");
} else
out.println(getEditorResponse());
out.println("");
out.println("");
out.flush();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}

private String getEditorResponse() {
StringBuffer sb = new StringBuffer(400);
sb.append("");
return sb.toString();
}
}

source: http://forums.smartclient.com/showthread.php?t=5477

Yasin Hasan Karanfil

Dozer Mapping Framework

3/17/2011 02:15:00 ÖS

(0) Comments

If you have some serialization problems in a GWT project, or if you need to transfer the data inside a POJO to another POJO, you can use dozer framework to do this.

If you are using Hibernate in your project and you have objects and DTO objects, you don't have to write data transfer code between these objects, you can use dozer framework to do these tasks automatically.

DozerBeanMapperSingletonWrapper.getInstance().map(record, RecordDTO.class));

http://code.google.com/webtoolkit/articles/using_gwt_with_hibernate.html

Yasin Hasan Karanfil

Excel Translate Function

3/17/2011 02:06:00 ÖS

(0) Comments



Using Google Docs, you can translate excel documents to another language using Google Translate service.

To be able to do this use this function

=GoogleTranslate("text", "source language","target language")

instead of "text", you can use the cell number

You can also detect the language of a text
=DetectLanguage("text")

Yasin Hasan Karanfil

Sell your applications on Windows Mobile Marketplace

3/17/2010 11:22:00 ÖÖ

(1) Comments

If you have an Dreamspark account, there is no 99$ fee for selling your applications on Windows Mobile Marketplace. You can get n Dreamspark account by applying your university or getting an ISIC international student card.

https://www.dreamspark.com/

You can download Windows Phone Developers Tools CTP that includes;

Visual Studio 2010 Express for Windows Phone CTP
Windows Phone Emulator CTP
Silverlight for Windows Phone CTP
XNA 4.0 Game Studio CTP

 

Windows Phone Developer Tools CTP

Windows Mobile 6.5 SDK

Yasin Hasan Karanfil

“Could not find resource assembly” error on Windows Mobile

3/05/2010 05:10:00 ÖS

(0) Comments

You should avoid deploying the System_SR cab file; In project properties, select Devices tab uncheck .net framework deployment

If it didn’t work

Copy the System_SR_ENU.CAB file to the emulator and install it. You can check this folders

C:\Program Files (x86)\Microsoft.NET\SDK\CompactFramework\v2.0\WindowsCE\Diagnostics
C:\Program Files\Microsoft Visual Studio 8\SmartDevices\SDK\CompactFramework\2.0\v1.0\WindowsCE\Diagnostics

Yasin Hasan Karanfil

Enable Network Connection on Windows Mobile Emulators

3/05/2010 05:04:00 ÖS

(0) Comments

If you have trouble with connecting to the internet with emulator, and you also tried Active Sync or Windows Mobile Device Center, there is a better way to do it, which worked perfectly for me.

Source: 

http://www.xdevsoftware.com/blog/post/Enable-Network-Connection-Windows-Mobile-6-Emulator.aspx

Steps How I Enabled Internet Connection on the Emulator:

- Downloaded and install Virtual PC 2007 (this is because it has to install some driver for the network card to work for the emulator)
- Open Windows Mobile Device Center and allow DMA connections.
       this can be done by going to Mobile Device Settings ->Connection Settings -> Allow Connections to one of the following -> Select DMA
- Opened Visual Studio and opened my mobile app
- In the toolbar selected Device Options Icon (located next to dropdown with the emulators to select from)
- Under Device Tools -> Devices I selected my Windows Mobile 6 Pro Emulator then clicked on Properties
- Clicked Emulator Options
- Select the Network Tab
- Checked the first box (enabled NE2000 PCMCIA network adapter and bind to:)
- Selected the name of my network card
- Ran the emulator by running the application
- Went to Connection Settings in the Emulator
      Start -> Settings -> Connections Tab -> Connections -> Advanced Tab -> Select Networks -> Choose My Work Network for both drop downs

That should do it to get internet going on your emulator.  Quite a few steps to get on the Internet, but oh well.

Yasin Hasan Karanfil

Creating Windows Mobile CAB Files Programmatically

3/05/2010 04:58:00 ÖS

(0) Comments

There is an easy way to create CAB files programmatically is to create Smart Device Cab Project in Visual Studio. If you check the Debug output you will see there is a command like this

"C:\Program Files (x86)\Microsoft Visual Studio 8\smartdevices\sdk\sdktools\cabwiz.exe" "C:\Users\aradiomy\Documents\Visual Studio 2005\Projects\Program\ProgramKurulum\Release\ProgramKurulum.inf" /dest "C:\Users\aradiomy\Documents\Visual Studio 2005\Projects\Program\ProgramKurulum\Release\" /err CabWiz.log

 

You can edit the *.inf file and call this command from a script or your program.

Yasin Hasan Karanfil

Getting Screen Resolution Programmatically on Windows Mobile

3/05/2010 04:52:00 ÖS

(0) Comments

int screenWidth = Screen.PrimaryScreen.Bounds.Width;
int workingWidth = Screen.PrimaryScreen.WorkingArea.Width;
int screenHeight = Screen.PrimaryScreen.Bounds.Height;
int workingHeight = Screen.PrimaryScreen.WorkingArea.Height;

Yasin Hasan Karanfil

Google App Engine development in NetBeans IDE

6/23/2009 11:42:00 ÖÖ

(1) Comments

You have to install Netbeans 6.7 and follow these steps:

  1. Download the latest NB build from here or use NB 6.7.
  2. Go to Tools - Plugins and select Settings tab.
  3. Click Add button and type 'App Engine' as name of Update center and following URL http://deadlock.netbeans.org/hudson/job/nbappengine/lastSuccessfulBuild/artifact/build/updates/updates.xml.gz into URL text field. Click to OK button.
  4. Switch to Available Plugins tab and choose Google App Engine modules (server, configuration, deployment, editor hints)
  5. Click to Install button

 

and then:

Yasin Hasan Karanfil

Google App Engine Java UTF-8 Character Encoding Problem

5/17/2009 06:44:00 ÖS

(0) Comments

There is a problem about Google App Engine Java Encoding settings. You have to change the Google App Engine's Javac Compiler Encoding.

http://groups.google.com/group/google-appengine-java/browse_thread/thread/1345bf330766d8be/

The easiest way to do it is add an UTF-8 argument to javac.exe. You can use this simple tool.

http://www.karanfil.info/blog/javac.exe

Rename the default javac.exe to javac1.exe, and copy this tool to same folder. (For example : C:\Program Files\Java\jdk1.6.0_12\bin\javac.exe)

Yasin Hasan Karanfil