Posts in java

Download file with GWT

marzo 29th, 2013 Posted by gwt, java, servlet 0 thoughts on “Download file with GWT”

Esta es una manera fácil de enviar desde GWT archivos al navegador para que los usuarios se los puedan descargar.

1. Hay que agregar un frame oculto en el HTML de la hosted page:

<div id="__gwt_downloadFrame" tabIndex='-1'></div>

2. Para iniciar la descarga poner este código en la parte cliente (código GWT):


public static void download(String p_uuid, String p_filename) {
String fileDownloadURL = "/fileDownloadServlet"
+ "?id=" + p_uuid
+ "&filename=" +
URL.encode(p_filename);
Frame fileDownloadFrame = new Frame(fileDownloadURL);
fileDownloadFrame.setSize("0px", "0px");
fileDownloadFrame.setVisible(false);
RootPanel panel = RootPanel.get("__gwt_downloadFrame");
while (panel.getWidgetCount() > 0)
panel.remove(0);
panel.add(fileDownloadFrame);
}

3. Poner esto en el servlet que va a servir el archivo a descargar:


@Override
protected void doGet(HttpServletRequest p_request,
HttpServletResponse p_response)
throws ServletException, IOException {
String filename = p_request.getParameter("filename");
if (filename == null)
{
p_response.sendError(SC_BAD_REQUEST, "Missing filename");
return;
}

File file = /* however you choose to go about resolving
filename */

long length = file.length();
FileInputStream fis = new FileInputStream(file);
p_response.addHeader("Content-Disposition",
"attachment; filename="" + filename +
""");
p_response.setContentType("application/octet-stream");
if (length > 0 && length <= Integer.MAX_VALUE);
p_response.setContentLength((int)length);
ServletOutputStream out = p_response.getOutputStream();
p_response.setBufferSize(32768);
int bufSize = p_response.getBufferSize();
byte[] buffer = new byte[bufSize];
BufferedInputStream bis = new BufferedInputStream(fis,
bufSize);
int bytes;
while ((bytes = bis.read(buffer, 0, bufSize)) >= 0)
out.write(buffer, 0, bytes);
bis.close();
fis.close();
out.flush();
out.close();
}

Cómo solucionar un workspace de Eclipse corrupto

octubre 18th, 2012 Posted by eclipse, java 0 thoughts on “Cómo solucionar un workspace de Eclipse corrupto”

Al intentar abrir Eclipse (corriendo en Mac OS 10.8.2) llegaba hasta el punto en el cual cargaba el plugin de GWT y dejaba de cargar.

Aparentemente el problema era con los editors abiertos.

Lo que hice para solucionarlo fue:

1) Ir por consola hasta el directorio del workspace.

2) Mover el directorio .metadata/.plugins a .metadata/.plugins.failing

3) Arrancar Eclipse (genera un nuevo directorio .plugins)

4) Copiar el directorio org.eclipse.core.resources del backup al nuevo dir .plugins


cp -r .plugins.failing/org.eclipse.core.resources .plugins/org.eclipse.core.resources


5) Copiar los settings desde el backup

cp -r .plugins.failing/org.eclipse.core.runtime/.settings .plugins/org.eclipse.core.runtime/.settings

6) Arrancar Eclipse

7) Importar los proyectos (sin marcar el checkbox para copiar el proyecto al workspace porque ya se encuentran dentro de él).

8) Actualizar las dependencias de Maven.

GWT Hosted mode compilation no es compatible con Java 1.5

agosto 10th, 2012 Posted by gwt, java 0 thoughts on “GWT Hosted mode compilation no es compatible con Java 1.5”

En un proyecto que estamos haciendo con GWT, en el cual tenemos que usar el Hosted Mode de GWT, pero sin Appengine estaba explotando la primera vez que se compilaba una jsp.

La solución la encontramos acá y básicamente hay que crear una clase que extienda de JDTCompiler y agregarla como argumento de la VM en la Run Configuration.

Entonces, primero hay que crear la siguiente clase:


public class JDTCompiler15 extends JDTCompilerAdapter {
@Override
public void setJavac(Javac attributes) {
if (attributes.getTarget() == null) {
attributes.setTarget("1.5");
}
if (attributes.getSource() == null) {
attributes.setSource("1.5");
}
super.setJavac(attributes);
}
}


Y luego hay que hacer click derecho sobre el proyecto > Run As > Run Configurations > seleccionar una de ellas y en VM arguments agregar lo siguiente:

-Dbuild.compiler="com.mypackage.JDTCompiler15"

How to use Apache James in MacOSx

noviembre 18th, 2011 Posted by java, mac 0 thoughts on “How to use Apache James in MacOSx”

1. Download James 2.3.2
2. Unzip it
3. Add this lines to run.sh

export JAVA_HOME=”/Library/Java/Home”
export PHOENIX_JVM_OPTS="-Djava.net.preferIPv4Stack=true"

3. chmod 755 *.sh4. sudo sh run.sh

GWT Celltable ContextMenu in a Column

octubre 4th, 2011 Posted by gwt, java 0 thoughts on “GWT Celltable ContextMenu in a Column”
// create your column class
private class ContextMenuColumn extends Column<UserModel, String>{

public ContextMenuColumn(Cell<String> cell) {
super(cell);
}

@Override
public String getValue(UserModel object) {
return "/img/icons/contextual-menu.jpg";
}

@Override
public void onBrowserEvent(Context context, Element elem, UserModel object, NativeEvent event) {
final UserModel user = object;

int left = elem.getParentElement().getAbsoluteLeft();
int top = elem.getParentElement().getAbsoluteTop();

final DialogBox dialog = new DialogBox();
dialog.setText(constants.Actions());

Anchor lnkEdit = new Anchor(constants.Edit());
lnkEdit.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
placeController.goTo(new ControlPanelUsersEditPlace(user.getUserId()));
dialog.hide();
}
});

Anchor lnkUpdateState = new Anchor(user.getEnable() == false ? constants.Enable() : constants.Disable());
lnkUpdateState.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
presenter.setEnabled(user.getUserId(), !user.getEnable());
dialog.hide();
}
});

Anchor lnkResetPassword = new Anchor(constants.ChangePassword());
lnkResetPassword.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
presenter.resetPassword(user.getUserId());
dialog.hide();
}
});

Anchor lnkDelete = new Anchor(constants.Delete());
lnkDelete.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
presenter.delete(user.getUserId());
dialog.hide();
}
});

VerticalPanel pnl = new VerticalPanel();
pnl.add(lnkEdit);
pnl.add(lnkUpdateState);
pnl.add(lnkResetPassword);
pnl.add(lnkDelete);

dialog.setWidget(pnl);
dialog.setPopupPosition(left - 20, top + 10);
dialog.setAutoHideEnabled(true);
dialog.show();
}
}

// create your column and add it to your table
Column<UserModel, String> contextMenuColumn = new ContextMenuColumn(new MyImageCell());

table.addColumn(contextMenuColumn);

GWT Celltable add a Row Handler

octubre 4th, 2011 Posted by gwt, java 0 thoughts on “GWT Celltable add a Row Handler”
Handler<UserModel> rowHandler = new Handler<UserModel>() {
@Override
public void onCellPreview(CellPreviewEvent<UserModel> event) {
if (event.getColumn() != 0 && event.getNativeEvent().getType().equals("click")) {
placeController.goTo(new CompanyUsersEditPlace(event.getValue().getUserId(), user.getCompanyId()));
}
}
};

table.addCellPreviewHandler(rowHandler);

GWT Celltable and Checkbox Column

octubre 4th, 2011 Posted by gwt, java 0 thoughts on “GWT Celltable and Checkbox Column”
// you need a selection model
private final MultiSelectionModel<usermodel> selectionModel = new MultiSelectionModel<usermodel>(operatorKeyProvider);

// you need a selection manager
private final DefaultSelectionEventManager<usermodel> selectionManager = DefaultSelectionEventManager.createCheckboxManager();

// you need the table ;)
@UiField CellTable<usermodel> table;

// then ...
selectionModel.addSelectionChangeHandler(
new SelectionChangeEvent.Handler() {
public void onSelectionChange(SelectionChangeEvent event) {
StringBuilder sb = new StringBuilder();
boolean first = true;
List&lt;UserModel&gt; selected = new ArrayList&lt;UserModel&gt;(selectionModel.getSelectedSet());

Collections.sort(selected);
for (UserModel value : selected) {
if (first) {
first = false;
} else {
sb.append(&quot;, &quot;);
}
sb.append(value.getFirstName());
}
}
});

table.setSelectionModel(selectionModel, selectionManager);

// create your column
Column<UserModel, Boolean> checkBoxColumn = new Column<UserModel, Boolean>(new CheckboxCell()) {

@Override
public Boolean getValue(UserModel object) {
return selectionModel.isSelected(object);
}

@Override
public FieldUpdater<UserModel, Boolean> getFieldUpdater() {
return null;
}

};

Cómo setear un JDK en eclipse.ini

mayo 19th, 2011 Posted by eclipse, java, maven 0 thoughts on “Cómo setear un JDK en eclipse.ini”

Luego de instalar Maven en Eclipse, aparece un cartel solictando que haya seteado un JDK en eclipse.ini


1. Editar el archivo eclipse.ini (que se encuentra dentro del directorio de Eclipse).
2. Poner en la primer linea del archivo:


-vm
path/to/jdk/bin/javaw.exe

Cómo agregar una JDK en Eclipse

mayo 18th, 2011 Posted by eclipse, java 0 thoughts on “Cómo agregar una JDK en Eclipse”

1. Window -> Preferences -> Java -> Installed JREs
2. Add -> Standard VM -> path/al/jdk (por ejemplo: “C:Archivos de programaJavajdk1.6.0_25”)

Cómo instalar JDK de Java en Windows XP

mayo 18th, 2011 Posted by java, windows 0 thoughts on “Cómo instalar JDK de Java en Windows XP”

1. Bajar el SDK de Java http://java.sun.com/javase/downloads/index.jsp
2. Correr el instalador.
3. Click derecho sobre “Mi PC” -> Opciones de Entorno -> Variables de Entorno
4. Buscar la variable “Path”, editar, y agregar al final la ubicación del compilador de Java, por ejemplo: ;C:Javajdk1.6.0_02bin
5. Crear una variable llamada “Classpath” y poner como valor: “C:Javajdk1.6.0_02src.zip”
6. Para testear si salió todo ok abrir una consola (Inicio -> Programas -> Accesorios -> Símbolo del Sistema) y tipear “java” y luego “javac”.

Copyright © 2018 programadorfreelanceargentina.com

Programador Freelance Argentina