Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 11-20 of 24 total

testing new bean scopes with spring 2.0 - example

// scoped bean definition
	<bean id="scopedBean"
		class="org.bla.ScopedBeanImpl"
		scope="session">
		<aop:scoped-proxy />
	</bean>

// an example test case
public class ScopedBeanTest extends AbstractRequestContextFilterTestBase {

	protected String[] getConfigLocations() {
		return new String[] { "classpath:applicationContext-with-scopedBean.xml" };
	}


	@Test
	public void testScopedBean() throws Exception {

		new FilterTest(new FilterChain() {

			public void doFilter(ServletRequest arg0, ServletResponse arg1)
					throws IOException, ServletException {
				ScopedBean scopedBean = (ScopedBean) applicationContext
						.getBean("scopedBean");
				...
				/* 
				 * let the classses under test do something with your scopedBean
				 * and check if modifications are done correctly 
				 */
				...
			}

		}).run();

	}

Set a Field Equal to Something

A basic code sample for tcm_write_macros. It sets a custom field to a value
/* also - custom-1, custom-2, custom-3, custom-4, custom-5, etc for custom fields. */
var obj = document.getElementById('custom-3');
obj.value = "VALUE";

C - Example Buffer OverFlow

/*
*
* Esempio di Buffer Overflow ...
*/

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
	char *buffer1 = (char *)calloc(5, sizeof(char));
	char *buffer2 = (char *)calloc(15, sizeof(char));
	char *tmp;
	
	strcpy(buffer2, "ls -a --color");
	strcpy(buffer1, argv[1]);

	// Indirizzi di memoria...
	printf("%p <-- buffer1\n", buffer1);
	printf("%p <-- buffer2\n", buffer2);
	printf("\n\n");

	// Stampa indirizzi...
	printf("Start code....\n");
	tmp=buffer1;
	while(tmp<buffer2+15)
	{
		printf("%p: %c (0x%x)\n", tmp, *tmp, *(unsigned int *)tmp);
		tmp++;
	}

	printf("\n");
	system(buffer2);
	return 0;
}

Odd numbers up to 1..100 in Ruby

// 10 different ways to display odd numbers 1 through 100 in Ruby

100.times do |i|
  next if i % 2 == 0
  puts i
end

50.times { |i| p i*2+1 }
(1..100).step(2) { |i| puts i}
1.upto(100) { |i| puts i unless i[0].zero? }
puts Array.new(50) { |i| i * 2 + 1 }
# a self referential recursive lambda :-)
lambda { me = lambda { |x| p x; me.call(x+2) if x < 99 } ; me.call(1) }.call

# same thing, but passing the lambda around
rec = lambda { |v,l| p v; l.call(v+2,l) if v < 99 }
rec.call(-1,rec)

# same recursive algorithm, but in method form
def odds(x=1)
  p x
  odds(x+2) if x < 99
end
odds

class Integer
  def odd?
    self[0].nonzero?
  end
end
100.times { |i| puts i if i.odd? }


require 'delegate'
class OddNum < DelegateClass(Fixnum)
  def initialize(value)
    value |= 1  # force it odd
    super(value)
  end
  
  def succ
    # note that the delegated succ gets called when we call super
    # and the constructor forces it (up) to the next odd number
    OddNum.new(super)
    
    # or
    # OddNum.new(self + 1)  # still using the constructor's force to odd
    # or 
    # OddNum.new(self + 2)  # being odd all on our own
  end
end
(OddNum.new(1)..100).each { |i| puts i }

general javascript code example

// description of your code here
sample code.
to test online bookmarklet builders.

alert('too       much'); //comment1
alert/*comment2*/('another     much');    var   a   =   1;
if(a == 1)
   a = 2
else
   a = 1

TableEditor in SWT

This code shows some table cell editors for SWT
it's not complete, but you can get a hint

import java.util.HashMap;
import java.util.Random;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.TableEditor;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.ColorDialog;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;

public class TableTester {
	
	private Display display;
	private Shell shell;
	private HashMap<String, Image> hashImages;
	private Table table;
	
	private Color GRAY;
	private Color WHITE;
	private int EDITABLECOLUMN;
	
	public TableTester() {
		display = new Display();
		shell = new Shell(display);
		
		init();
		createGUI();
		
		shell.open();
		
		while(!shell.isDisposed()) {
			if(!display.readAndDispatch()) {
				display.sleep();
			}
		}
	}
	
	private void init() {
		hashImages = new HashMap<String, Image>();
		hashImages.put("help", new Image(display, "C:\\Programme\\eclipse\\workspace\\TestSwt\\src\\icons\\help.png"));
		hashImages.put("about", new Image(display, "C:\\Programme\\eclipse\\workspace\\TestSwt\\src\\icons\\about_kde.png"));
		
		GRAY = new Color(display, 220, 220, 220);
		WHITE = new Color(display, 255, 255, 255);
	}
	
	private void createGUI() {
		shell.setLayout(new FillLayout());
		shell.setText("TableTester");
		
		shell.setImage(hashImages.get("about"));
		
		table = new Table(shell, SWT.SINGLE | SWT.FULL_SELECTION | SWT.V_SCROLL | SWT.H_SCROLL | SWT.VIRTUAL);
		table.setHeaderVisible(true);
		table.setLinesVisible(true);
		
		table.addListener (SWT.MouseDown, new Listener () {
			public void handleEvent (Event event) {
				Rectangle clientArea = table.getClientArea ();
				Point selectedPoint = new Point (event.x, event.y);
				int index = table.getTopIndex ();
				while (index < table.getItemCount ()) {
					boolean visible = false;
					TableItem item = table.getItem (index);
					for (int i=0; i < table.getColumnCount(); i++) {
						Rectangle rect = item.getBounds (i);
						if (rect.contains (selectedPoint)) {
//							System.out.println ("Item " + index + "-" + i);
							EDITABLECOLUMN = i;
						}
						if (!visible && rect.intersects (clientArea)) {
							visible = true;
						}
					}
					if (!visible) return;
					index++;
				}
			}
		});
		
		final TableEditor editor = new TableEditor(table);
		//The editor must have the same size as the cell and must
		//not be any smaller than 50 pixels.
		editor.horizontalAlignment = SWT.LEFT;
		editor.grabHorizontal = true;
		editor.minimumWidth = 50;
		
		table.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				// Clean up any previous editor control
				Control oldEditor = editor.getEditor();
				if (oldEditor != null) oldEditor.dispose();
		
				// Identify the selected row
				TableItem item = (TableItem)e.item;
				if (item == null) {
					return;
				}

				// The control that will be the editor must be a child of the Table
				if(EDITABLECOLUMN == 0) { // boolean
					if("true".equalsIgnoreCase(item.getText())) {
						final Button newEditor = new Button(table, SWT.CHECK);
						newEditor.setText("Click to change");
						newEditor.setSelection(true);
						newEditor.addSelectionListener(new SelectionAdapter() {
							public void widgetSelected(SelectionEvent e) {
								editor.getItem().setText("" + newEditor.getSelection());
							}
						});
						newEditor.setFocus();
						editor.setEditor(newEditor, item, EDITABLECOLUMN);
					} else {
						final Button newEditor = new Button(table, SWT.CHECK);
						newEditor.setText("Click to change");
						newEditor.setSelection(false);
						newEditor.addSelectionListener(new SelectionAdapter() {
							public void widgetSelected(SelectionEvent e) {
								editor.getItem().setText("" + newEditor.getSelection());
							}
						});
						newEditor.setFocus();
						editor.setEditor(newEditor, item, EDITABLECOLUMN);
					}
				} else if(EDITABLECOLUMN == 3) { // password string
					Button newEditor = new Button(table, SWT.NONE);
					newEditor.setText("Generate");
					newEditor.addSelectionListener(new SelectionAdapter() {
						public void widgetSelected(SelectionEvent e) {
							String s = Utilities.getRandomString(12, true, true, true, true);
							editor.getItem().setText(EDITABLECOLUMN, s);
						}
					});
					newEditor.setFocus();
					editor.setEditor(newEditor, item, EDITABLECOLUMN);
				} else if(EDITABLECOLUMN == 4) { // color
					ColorDialog newEditor = new ColorDialog(shell, SWT.NONE);
					String[] data = item.getText(EDITABLECOLUMN).split(",");
					newEditor.setRGB(new RGB(Integer.parseInt(data[0].trim()),
							Integer.parseInt(data[1].trim()),
							Integer.parseInt(data[2].trim())));
					RGB rgb = newEditor.open();
					item.setText(EDITABLECOLUMN, rgb.red + "," + rgb.green + "," + rgb.blue);
				} else {
					Text newEditor = new Text(table, SWT.NONE);
					newEditor.setText(item.getText(EDITABLECOLUMN));
					newEditor.addModifyListener(new ModifyListener() {
						public void modifyText(ModifyEvent me) {
							Text text = (Text)editor.getEditor();
							editor.getItem().setText(EDITABLECOLUMN, text.getText());
						}
					});
					newEditor.selectAll();
					newEditor.setFocus();
					editor.setEditor(newEditor, item, EDITABLECOLUMN);
				}
			}
		});
		
		fillWithData();
	}
	
	private void fillWithData() {
		TableColumn col = new TableColumn(table, SWT.NONE);
		col.setText("boolean");
		col.setWidth(100);
		
		col = new TableColumn(table, SWT.NONE);
		col.setText("Integer");
		col.setWidth(100);
		
		col = new TableColumn(table, SWT.NONE);
		col.setText("Float");
		col.setWidth(100);
		
		col = new TableColumn(table, SWT.NONE);
		col.setText("Password");
		col.setWidth(100);

		col = new TableColumn(table, SWT.NONE);
		col.setText("Color");
		col.setWidth(100);
		
		TableItem row;
		Random r = new Random(System.nanoTime());
		for (int i = 0; i < 1000; i++) {
			row = new TableItem(table, SWT.NONE);
			row.setText(new String[] {
					"" + r.nextBoolean(),
					"" + r.nextInt(),
					"" + r.nextFloat(),
					"" + Utilities.getRandomString(12, true, true, true, true),
					"" + r.nextInt(255) + "," + r.nextInt(255) + "," + r.nextInt(255)});
			row.setBackground((i % 2 == 0) ? WHITE : GRAY);
		}
	}

	public static void main(String[] args) {
		new TableTester();
	}
}

Simple Wizard in SWT

// This code is an example for StackLayout

import java.util.Vector;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StackLayout;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

public class Wizard {

private Display display;
private Shell shell;
private int index;
private Button prev;
private Button next;
private Vector<Control> PAGES;
private Composite wizardPanel;
private StackLayout wizardLayout;
private Vector<String> TITLES;

public Wizard() {
display = new Display();
shell = new Shell(display);

shell.setText("Wizard");

init();
createGUI();

fillPages();
setSize(500, 400);

shell.open();

while(!shell.isDisposed()) {
if(!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}

private void fillPages() {
Button label = new Button(shell, SWT.BORDER);
label.setText("Hello, World 0!");
addPage(label, "Page 1");

label = new Button(shell, SWT.BORDER);
label.setText("Hello, World 1!");
addPage(label, "This is page #2!");

Group group = new Group(shell, SWT.NONE);
group.setLayout(new GridLayout(2, false));

Label imgLabel = new Label(group, SWT.BORDER);
GridData gd = new GridData(GridData.FILL_VERTICAL);
gd.verticalSpan = 2;
imgLabel.setLayoutData(gd);
imgLabel.setImage(new Image(display, "C:\\Programme\\eclipse\\workspace\\TestSwt\\src\\icons\\simwizard.jpg"));

Text text = new Text(group, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL);
text.setText("Hier steht ein Hinweis.\nAuch über mehrere\n\tZeilen, mit Sonderzeichen!");
text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

Group ng = new Group(group, SWT.NONE);
ng.setLayout(new GridLayout(2, false));
ng.setLayoutData(new GridData(GridData.FILL_BOTH | GridData.GRAB_VERTICAL | GridData.GRAB_HORIZONTAL));

Label l = new Label(ng, SWT.NONE);
l.setLayoutData(new GridData());
l.setText("Combo:");
Combo combo = new Combo(ng, SWT.BORDER);
combo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
combo.setItems(new String[] {"foo", "bar", "baz"});

l = new Label(ng, SWT.NONE);
l.setLayoutData(new GridData());
l.setText("Text:");
Text t = new Text(ng, SWT.BORDER);
t.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
t.setText("foo");

l = new Label(ng, SWT.NONE);
l.setLayoutData(new GridData());
l.setText("Radio:");

Group g = new Group(ng, SWT.NONE);
g.setLayout(new FillLayout());
Button r = new Button(g, SWT.RADIO);
r.setText("Radio #1");
r = new Button(g, SWT.RADIO);
r.setText("Radio #2");
r = new Button(g, SWT.RADIO);
r.setText("Radio #3");

l = new Label(ng, SWT.NONE);
l.setLayoutData(new GridData());
l.setText("Check:");

g = new Group(ng, SWT.NONE);
g.setLayout(new FillLayout());
r = new Button(g, SWT.CHECK);
r.setText("Check #1");
r = new Button(g, SWT.CHECK);
r.setText("Check #2");
r = new Button(g, SWT.CHECK);
r.setText("Check #3");

addPage(group, "This is filled with controls.");
}

private void init() {
index = 0; // index for current page
PAGES = new Vector<Control>();
TITLES = new Vector<String>();
}

private void createGUI() {
shell.setLayout(new GridLayout(2, false));

wizardPanel = new Composite(shell, SWT.NONE);
GridData gd = new GridData(GridData.FILL_BOTH);
gd.horizontalSpan = 2;
wizardPanel.setLayoutData(gd);

wizardLayout = new StackLayout();
wizardPanel.setLayout(wizardLayout);

prev = new Button(shell, SWT.PUSH);
next = new Button(shell, SWT.PUSH);
next.setText("Next >");
next.setLayoutData(new GridData());
next.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
next();
}
});
next.setEnabled(false);

prev.setText("< Previous");
prev.setLayoutData(new GridData());
prev.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
previous();
}
});
prev.setEnabled(false);
}

private void next() {
if(index == PAGES.size()-1 && "finish".equalsIgnoreCase(next.getText())) {
System.out.println("finished!");
shell.close();
display.dispose();
return;
}

if(index < PAGES.size()-1) {
index += 1;
wizardLayout.topControl = PAGES.get(index);
shell.setText("Wizard - " + TITLES.get(index));
wizardPanel.layout();
}

if(index-1 >= 0) {
prev.setEnabled(true);
}
if(index+1 >= PAGES.size()) {
// next.setEnabled(false);
next.setText("Finish");
}
}

private void previous() {
if(index > 0) {
index -= 1;
wizardLayout.topControl = PAGES.get(index);
shell.setText("Wizard - " + TITLES.get(index));
wizardPanel.layout();
}

if(index+1 < PAGES.size()) {
// next.setEnabled(true);
next.setText("Next >");
}
if(index-1 < 0) {
prev.setEnabled(false);
}
}

public void addPage(Control c) {
addPage(c, "Page");
}

public void addPage(Control c, String title) {
// auf Wizardpanel umsetzen
c.setParent(wizardPanel);

PAGES.addElement(c);
TITLES.addElement(title);
wizardLayout.topControl = PAGES.get(0);
shell.setText("Wizard - " + TITLES.get(0));
if(PAGES.size() > 0) {
next.setEnabled(true);
}
}

public int getPageCount() {
return PAGES.size();
}

public void setSize(int width, int height) {
shell.setSize(width, height);
}

public static void main(String[] args) {
new Wizard();
}

}

DragAndDrop SWT example

// This code implements a very basic Drag'n'Drop
// you can drag the labels from the top into the canvas
// and the text will be drawn there. The positioning isn't exact
// but who cares...

import java.util.HashMap;

import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.DragSourceEvent;
import org.eclipse.swt.dnd.DragSourceListener;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.DropTargetListener;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;

public class DragAndDropTool {

private Display display;
private Shell shell;
private HashMap<String, Image> hashImages;
private Label drag1;
private Label drag2;
private Label drag3;
private Canvas text;

public DragAndDropTool() {
// Display & Shell holen
display = new Display();
shell = new Shell(display);

shell.setText("DnD Toolbar");
shell.setSize(500, 300);

init();
createGUI();

// Shell öffnen
shell.open();

// Event-Schleife starten
while(!shell.isDisposed()) {
if(!display.readAndDispatch()) {
display.sleep();
}
}
}

private void init() {
hashImages = new HashMap<String, Image>();
hashImages.put("action", new Image(display, "C:\\Programme\\eclipse\\workspace\\TestSwt\\src\\icons\\aktion.png"));
hashImages.put("help", new Image(display, "C:\\Programme\\eclipse\\workspace\\TestSwt\\src\\icons\\help.png"));
hashImages.put("about", new Image(display, "C:\\Programme\\eclipse\\workspace\\TestSwt\\src\\icons\\about_kde.png"));
}

private void createGUI() {
shell.setLayout(new GridLayout(3, false));

drag1 = new Label(shell, SWT.BORDER);
drag1.setText("drag source #1");
drag1.setLayoutData(new GridData());
DragSource dragSource1 = new DragSource(drag1, DND.DROP_COPY);
Transfer[] transfers1 = new Transfer[] {TextTransfer.getInstance()};
dragSource1.setTransfer(transfers1);
dragSource1.addDragListener(new DragSourceListener() {
public void dragStart(DragSourceEvent event) {
if(drag1.getText().length() == 0) {
event.doit = false;
}
}

public void dragSetData(DragSourceEvent event) {
if (TextTransfer.getInstance().isSupportedType(event.dataType)) {
event.data = drag1.getText();
}
}

public void dragFinished(DragSourceEvent event) {}
});

drag2 = new Label(shell, SWT.BORDER);
drag2.setText("drag source #2");
drag2.setLayoutData(new GridData());
DragSource dragSource2 = new DragSource(drag2, DND.DROP_COPY);
Transfer[] transfers2 = new Transfer[] {TextTransfer.getInstance()};
dragSource2.setTransfer(transfers2);
dragSource2.addDragListener(new DragSourceListener() {
public void dragStart(DragSourceEvent event) {
if(drag2.getText().length() == 0) {
event.doit = false;
}
}

public void dragSetData(DragSourceEvent event) {
if (TextTransfer.getInstance().isSupportedType(event.dataType)) {
event.data = drag2.getText();
}
}

public void dragFinished(DragSourceEvent event) {}
});

drag3 = new Label(shell, SWT.BORDER);
drag3.setText("drag source #3");
drag3.setLayoutData(new GridData());
DragSource dragSource3 = new DragSource(drag3, DND.DROP_COPY | DND.DROP_DEFAULT);
Transfer[] transfers3 = new Transfer[] {TextTransfer.getInstance()};
dragSource3.setTransfer(transfers3);
dragSource3.addDragListener(new DragSourceListener() {
public void dragStart(DragSourceEvent event) {
if(drag3.getText().length() == 0) {
event.doit = false;
}
}

public void dragSetData(DragSourceEvent event) {
if (TextTransfer.getInstance().isSupportedType(event.dataType)) {
event.data = drag3.getText();
}
}

public void dragFinished(DragSourceEvent event) {}
});


// text = new Text(shell, SWT.BORDER | SWT.MULTI);
text = new Canvas(shell, SWT.BORDER);
GridData gd = new GridData(GridData.FILL_BOTH);
gd.horizontalSpan = 3;
text.setLayoutData(gd);
DropTarget dropTarget = new DropTarget(text, DND.DROP_COPY | DND.DROP_DEFAULT);
Transfer[] types = new Transfer[] {TextTransfer.getInstance()};
dropTarget.setTransfer(types);
dropTarget.addDropListener(new DropTargetListener() {
public void dragEnter(DropTargetEvent event) {
if(event.detail == DND.DROP_DEFAULT) {
if((event.operations & DND.DROP_COPY) != 0) {
event.detail = DND.DROP_COPY;
} else {
event.detail = DND.DROP_NONE;
}
}
}

public void dragLeave(DropTargetEvent event) {}

public void dragOperationChanged(DropTargetEvent event) {}

public void dragOver(DropTargetEvent event) {
}

public void drop(DropTargetEvent event) {}

public void dropAccept(DropTargetEvent event) {
if (TextTransfer.getInstance().isSupportedType(event.currentDataType)) {
String d = (String)TextTransfer.getInstance().nativeToJava(event.currentDataType);
// text.append(d + '\n');
GC gc = new GC(text);
int x = event.x - shell.getBounds().x - text.getBounds().x;
int y = event.y - shell.getBounds().y - text.getBounds().y;
// System.err.println("drop x=" + (event.x - shell.getBounds().x - text.getBounds().x) + ",y=" + (event.y - shell.getBounds().y - text.getBounds().y));
gc.drawString(d, x, y);
gc.dispose();
}
}
});
}

public static void main(String[] args) {
new DragAndDropTool();
}

}

FileToImageGenerator

// creates a simple colored image out of a text file

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Random;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

public class FileToImageGenerator {

private Display display;
private Shell shell;
private File imgFile;
private Text textFile;
private Canvas canvas;
private Color clearColor;

public FileToImageGenerator() {
display = new Display();
shell = new Shell(display);

// shell.setSize(500, 300);
shell.setText("FileToImageGenerator");

createGUI();

shell.open();

while(!shell.isDisposed()) {
if(!display.readAndDispatch()) {
display.sleep();
}
}
}

private void createGUI() {
shell.setLayout(new GridLayout(3, false));

Label label = new Label(shell, SWT.NONE);
label.setText("File:");
label.setLayoutData(new GridData());

textFile = new Text(shell, SWT.BORDER | SWT.READ_ONLY);
textFile.setText("");
textFile.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

Button b = new Button(shell, SWT.BORDER);
b.setText("Open...");
b.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
FileDialog dlg = new FileDialog(shell);
dlg.open();

imgFile = new File(dlg.getFilterPath() + File.separator + dlg.getFileName());

if(imgFile.isDirectory()) {
imgFile = null;
} else {
generateImageFromFile(imgFile);
}
}
});
b.setLayoutData(new GridData());
b.setFocus();

canvas = new Canvas(shell, SWT.BORDER);
GridData gd = new GridData(GridData.FILL_BOTH | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL);
gd.horizontalSpan = 3;
canvas.setLayoutData(gd);
clearColor = canvas.getBackground();
}

private void generateImageFromFile(File i) {
textFile.setText(i.getAbsolutePath());

Rectangle bounds = canvas.getBounds();
GC gc = new GC(canvas);
canvas.setBackground(clearColor);
gc.fillRectangle(0, 0, bounds.width, bounds.height);

Random r = new Random(System.nanoTime());

try {
BufferedReader fr = new BufferedReader(new FileReader(i.getAbsoluteFile()));
int b = -1;
int x = 0;
int y = 0;
while((b = fr.read()) != -1) {
// System.err.print((char)b);
// gc.drawString("" + (char)b, x, y);
gc.setBackground(new Color(display, r.nextInt(255), r.nextInt(255), r.nextInt(255)));
gc.fillRectangle(x, y, 10, 15);

x += 10;
// if(b == '\n') {
if(x >= bounds.width) {
x = 0;
y += 15;
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

public static void main(String[] args) {
new FileToImageGenerator();
}

}

OpenURL in SWT

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

import sun.net.www.protocol.http.HttpURLConnection;

public class OpenUrl {

private Display display;
private Shell shell;
private GridLayout layout;
// private Text textArea;
private Browser browser;

public OpenUrl() {
// Display & Shell holen
display = new Display();
shell = new Shell(display);

shell.setText("OpenURL - WWW demo application");
shell.setSize(500, 300);

createGUI();

// Shell öffnen
shell.open();

// Event-Schleife starten
while(!shell.isDisposed()) {
if(!display.readAndDispatch()) {
display.sleep();
}
}
}

private void createGUI() {
layout = new GridLayout();
layout.numColumns = 2;

layout.marginLeft = 5;
layout.marginTop = 5;
layout.marginRight = 5;
layout.marginBottom = 5;

shell.setLayout(layout);

Label l = new Label(shell, SWT.NONE);
l.setText("URL:");
l.setLayoutData(new GridData(SWT.LEFT));

final Text t = new Text(shell, SWT.BORDER);
t.setText("http://www.google.de/");
t.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL));

// textArea = new Text(shell, SWT.BORDER | SWT.MULTI | SWT.WRAP | SWT.V_SCROLL | SWT.READ_ONLY);
// textArea.setText("Press \"Open\" to load the URL contents...");
// GridData gd = new GridData(GridData.FILL_BOTH | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL);
// gd.horizontalSpan = 2;
// textArea.setLayoutData(gd);

browser = new Browser(shell, SWT.BORDER);
GridData gd = new GridData(GridData.FILL_BOTH | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL);
gd.horizontalSpan = 2;
browser.setLayoutData(gd);

Button b = new Button(shell, SWT.NONE);
b.setText("Open");
b.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
open(t.getText());
}
});
b.setFocus();
b.setLayoutData(new GridData(SWT.BEGINNING));
}

private void open(String u) {
System.err.println(OpenUrl.this + " open URL '" + u + "'");

try {
StringBuffer urlText = new StringBuffer();
URL url = new URL(u);
HttpURLConnection con = new HttpURLConnection(url, "webgate.de.emea.csc.com", 8080);
InputStream in = con.getInputStream();
int i = -1;
while(((i = in.read()) != -1)) {
urlText.append((char)i);
}

// textArea.setText(urlText.toString());
browser.setText(urlText.toString());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public static void main(String[] args) {
new OpenUrl();
}
}
« Newer Snippets
Older Snippets »
Showing 11-20 of 24 total