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