JavaFX – Adding and placing imageView

Version JavaFX 2.0, JDK 1.7.0_10

Use a Pane or a Pane subclass.

Panes are Regions to which you can add children using the getChildren() api. Pane is very similar to a Group; e.g. has a simple api for adding children and does not explicitly layout the location of the children. It also has the aspects of a Region; e.g. css styleable, resize capable, etc. Region’s only have an unmodifiable list of children via their public API, meaning that the only way to add children to them is to subclass them (as Pane does for you already). The Region class itself is really just a building block class for control creators and not something you would instantiate during normal development.

Here is an example of adding ImageView nodes to a Pane.

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.*;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;

public class RegionSample extends Application {
  public static void main(String[] args) throws Exception { launch(args); }
  public void start(Stage stage) throws Exception {
    Pane pane = new Pane();
    pane.setStyle("-fx-background-color: linear-gradient(to bottom right, derive(goldenrod, 20%), derive(goldenrod, -40%));");
    ImageView iv1 = new ImageView(new Image("http://icons.iconarchive.com/icons/kidaubis-design/cool-heroes/128/Ironman-icon.png"));  // Creative commons with attribution license for icons: No commercial usage without authorization. All rights reserved. Design (c) 2008 - Kidaubis Design http://kidaubis.deviantart.com/  http://www.kidcomic.net/ All Rights of depicted characters belong to their respective owners.
    ImageView iv2 = new ImageView(new Image("http://icons.iconarchive.com/icons/kidaubis-design/cool-heroes/128/Starwars-Stormtrooper-icon.png"));
    iv1.relocate(10, 10);
    iv2.relocate(80, 60);
    pane.getChildren().addAll(iv1, iv2);
    stage.setScene(new Scene(pane));
    stage.show();
  }
}

Source: http://stackoverflow.com/questions/11181080/how-to-add-imageview-to-javafx-region-element

Gradle – Build JavaFX Project

Gradle version: 1.2
JDK version: 1.7.0_10 (OSX)

1. Install git (http://git-scm.com/downloads)
2. Download, build and install JavaFX gradle plugin:
First of all you need to get the code for the javafx gradle plugin from bitbucket:
https://bitbucket.org/shemnon/javafx-gradle

For this you create a directory where you want to store the code and type in the following command:

git clone https://bitbucket.org/shemnon/javafx-gradle.git

Then you have to build and install the plugin:
cd into you project and type the following command:

gradle install

This will install the plugin with the version 0.0.0-SNAPSHOT, if you want it to change go to the plugin/build directory and change the version in the file build.gradle.

3. Gradle assemble
So far, so good. Now add the following build.gradle file into the root of your project:

apply plugin: 'javafx'
buildscript {
    repositories {
        mavenLocal()
    }
    dependencies {
        classpath 'com.bitbucket.shemnon.javafxplugin:plugin:0.0.0-SNAPSHOT'
    }
}
repositories {
    mavenLocal()
    mavenCentral()
}
dependencies {
}
javafx {
    def javafxMainClass = 'ch.prait.slimbudget.fx.SlimBudget'
}

Make sure that the version is the same in the buildscript dependencies section and execute the command:

gradle assemble

If everything is running o.k. the script will build your executable (osx: dmg and windows: exe)

4. Signing
For the key, you have two options, in the build script or via properties.
Properties looks like this (in a gradle.properties or via command line -D switches)…

javafx.releaseKey.alias = selfsigned
javafx.releaseKey.keypass = password
javafx.releaseKey.keystore = /path/to/keystore.jks
javafx.releaseKey.storepass = password
javafx.signingMode = release

In the build.gradle it looks like this:

javafx {
releaseKey {
alias = 'selfsigned'
keypass = 'password'
keystore = file('/path/to/keystore.jks')
storepass = 'password'
}
signingMode = 'release'
}

Note that there is a releaseKey section and a debugKey section, toggled by signingMode (which defaults to debug). A self-signed debug key is created for you if you don’t set one. For the release key, I recommend at least the passwords go in the properties. And properties override what is in the build.gradle for signing.

Ubuntu – Search Text in Files

Search in all files recursively:

grep -r "TEXT" *

Search case insensitive:

grep -i -r "TEXT" *

Tomcat 7 Security – How to define your own DB Realm in the War

What you need to have is a META-INF/context.xml in the root of your war file.
Here you can define everything that you can define in the tomcat context elements.

Just put the following content into the file if you had an oracle db realm:

<?xml version="1.0" encoding="UTF-8"?>
<Context path="/yourwebappContextRoot">
      <Realm className="ch.prait.security.TomcatRealm"
                  name="yourwebappContextRoot"
                  databaseUrl="jdbc:oracle:thin:@myhost.prait.ch:1526:schema"
                  autoReconnect="true"
                  driverClass="oracle.jdbc.driver.OracleDriver"/>
</Context>

Here is a small example of the db realm without db code:

package ch.prait.security;

import java.security.Principal;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.catalina.LifecycleException;
import org.apache.catalina.realm.GenericPrincipal;
import org.apache.catalina.realm.RealmBase;
import org.apache.log4j.Logger;

public class TomcatRealm extends RealmBase {

	Logger logger = Logger.getLogger(TomcatRealm.class);

	/**
	 * Instance of the JDBC Driver class we use as a connection factory.
	 */
	protected Driver driver = null;

	private Connection conn;

	private Map<String, GenericPrincipal> realm;

	private String databaseUrl;

	private String autoReconnect = "true";

	private String driverClass;

	private String name = "Spnego Realm";

	public void setAutoReconnect(String autoReconn) {
		autoReconnect = autoReconn;
	}

	public String getAutoReconnect() {
		return this.autoReconnect;
	}

	public void setDatabaseUrl(String databaseUrl) {
		this.databaseUrl = databaseUrl;
	}

	public String getDatabseUrl() {
		return this.databaseUrl;
	}

	public void setDriverClass(String driverClass) {
		this.driverClass = driverClass;
	}

	public String getDriverClass() {
		return this.driverClass;
	}

	/**
	 * Initialise le realm
	 */
	public TomcatRealm() {
		realm = new HashMap<String, GenericPrincipal>();
	}

	public String getInfo() {
		return "ch.prait.security.TomcatRealm/1.1";
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	protected String getPassword(String princ) {
		return null;
	}

	protected Principal getPrincipal(String princ) {
		logger.debug("getPrincipal: " + princ);
		GenericPrincipal principal = (GenericPrincipal) realm.get(princ);
		if (principal == null) {
			principal = createPrincipalAndAddRole(princ);
			realm.put(princ, principal);
		}
		return principal;
	}

	public GenericPrincipal createPrincipalAndAddRole(String princ) {

		// load the roles from the db per application and principal name (princ)
		// and add them into the List
		String application = getName();
		List<String> roles = new ArrayList<String>();

		.......
		.......
		// set the roles for the principal name on the Principal
		GenericPrincipal principal = new GenericPrincipal(princ, "NO_PW", roles);
		return principal;

	}

	public boolean hasRole(Principal princ, String role) {

		if (!(princ instanceof GenericPrincipal)) {
			return false;
		}
		GenericPrincipal principal = (GenericPrincipal) princ;

		realm.put(principal.getName(), principal);

		// get the roles from db and add em to the List
		List<String> roles = new ArrayList<String>();

		.........
		.........

		return roles.contains(role);
	}

}

WordPress – Adding a special frontpage

Ever wondered how to have a front page and a second one for posts?
Here is the official guide:
http://codex.wordpress.org/Creating_a_Static_Front_Page

Latex – Lass es doch Latex rechnen (ohne calc)

A really useful guide for calculating with Latex ….not the material used for tight dresses ;-)
It’s written in german and its done without using the calc package.

Lass doch Latex rechnen.pdf
pdf is created by Bernd Kosubek

Lucene – Horatio says ’tis but our fantasy

Useful links to start with Lucene:
http://www.lucenetutorial.com/lucene-in-5-minutes.html
http://stackoverflow.com/questions/468405/how-to-incorporate-multiple-fields-in-queryparser
Here an example how to index and search text:

package ch.prait.lucene;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.lucene.analysis.KeywordAnalyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopScoreDocCollector;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.SimpleFSDirectory;
import org.apache.lucene.util.Version;

public class PrettyLucene {

	public void index(Directory index, List<String> stringsToIndex, String teller) throws Exception {
		// create an analyzer
		StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_36);

		// Create the index writer
		IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_36, analyzer);
		IndexWriter w = new IndexWriter(index, config);

		int idCounter = 0;
		for (String stringToIndex : stringsToIndex) {

			// create a document and add three fields to it whereas 2 are analyzed and one is just
			// information stored
			Document myDocument = new Document();
			myDocument.add(new Field("myString", stringToIndex, Field.Store.YES, Field.Index.ANALYZED));
			myDocument.add(new Field("id", String.valueOf(idCounter), Field.Store.YES, Field.Index.ANALYZED));
			myDocument.add(new Field("teller", teller, Field.Store.YES, Field.Index.NO));
			w.addDocument(myDocument);
		}
		// close all handles
		w.close();
	}

	public void searchIndex(Directory index, String searchTerm) throws Exception {
		// create an analyzer
		KeywordAnalyzer analyzer = new KeywordAnalyzer();

		// create a topScore Collection and display the results
		int hitsPerPage = 10;
		IndexReader reader = IndexReader.open(index);

		IndexSearcher searcher = new IndexSearcher(reader);
		TopScoreDocCollector collector = TopScoreDocCollector.create(hitsPerPage, true);
		QueryParser parser = new QueryParser(Version.LUCENE_36, "myString", analyzer);
		Query q = parser.parse(searchTerm);
		searcher.search(q, collector);
		ScoreDoc[] hits = collector.topDocs().scoreDocs;

		System.out.println("Found " + hits.length + " hits.");
		for (int i = 0; i < hits.length; ++i) {
			int docId = hits[i].doc;
			Document d = searcher.doc(docId);
			System.out.println((i + 1) + ". " + "Line " + d.get("id") + " told by " + d.get("teller") + ": "
					+ d.get("myString"));
		}
		reader.close();
	}

	public static void main(String[] args) {

		PrettyLucene prettyLucene = new PrettyLucene();
		try {
			// makes a directory luceneIndex where you start the program. In this folder
			// lucene will put the index files
			Directory index = new SimpleFSDirectory(new File("luceneIndex"));

			List<String> marcellus = new ArrayList<String>();
			marcellus.add("Horatio says 'tis but our fantasy,");
			marcellus.add("And will not let belief take hold of him");
			marcellus.add("Touching this dreaded sight, twice seen of us:");
			marcellus.add("Therefore I have entreated him along");
			marcellus.add("With us to watch the minutes of this night;");
			marcellus.add("That if again this apparition come,");
			marcellus.add("He may approve our eyes and speak to it.");
			prettyLucene.index(index, marcellus, "Marcellus");

			List<String> horatio = new ArrayList<String>();
			horatio.add("What art thou that usurp'st this time of night,");
			horatio.add("Together with that fair and warlike form");
			horatio.add("In which the majesty of buried Denmark");
			horatio.add("Did sometimes march? by heaven I charge thee, speak!");
			prettyLucene.index(index, horatio, "Horatio");

			prettyLucene.searchIndex(index, "speak*");

			index.close();

		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}

Gradle – 0.9 Breaking Changes

Do you have problems migrating from 0.8 to 0.9 ? This will help you a looot:

http://wiki.gradle.org/display/GRADLE/Gradle+0.9+Breaking+Changes

Git – Making bare repo from working copy

Suppose “repo” is your working copy and you just wanted to make a bare repo out of it.

cd repos
mv .git repos.git
cd repos.git
git config --bool core.bare true # from another answer
cd ../
mv repos.git ../
cd ../
rm -rf repos/ # or delete using a file manager if you like

If you just want to create a bare repo on the server from your local repo, Ralph posted a nice way to do this:
http://rwehner.wordpress.com/2010/03/01/a-simple-way-to-create-git-repository-on-a-server-machine-connecting-via-ssh/

Separating Application Logs

You can segment logging output by assigning log4j categories to specific appenders in
the conf/log4j.xml configuration. For example, the following

<appender name="App1Log" class="org.apache.log4j.FileAppender">
      <errorHandler class="org.jboss.logging.util.OnlyOnceErrorHandler"></errorHandler>
      <param name="Append" value="false"/>
      <param name="File" value="${jboss.server.home.dir}/log/app1.log"/>
      <layout class="org.apache.log4j.PatternLayout">
         <param name="ConversionPattern" value="%d{ABSOLUTE} %-5p [%c{1}] %m%n"/>
      </layout>
   </appender>

...

   <category name="com.app1">
     <appender-ref ref="App1Log"></appender-ref>
   </category>
   <category name="com.util">
     <appender-ref ref="App1Log"></appender-ref>
   </category>

If you have multiple apps with shared classes/categories, and/or want the JBoss categories to show up in your app log then this approach will not work. There is a new appender filter called TCLFilter (attached) that will be in the 3.2.4 release that can help with this. You add the filter to the appender and specify what deployment url should logging be restricted to. For example, if your app1 deployment was app1.ear, you would use the following additions to the conf/log4j.xml:

<appender name="App1Log" class="org.apache.log4j.FileAppender">
      <errorHandler class="org.jboss.logging.util.OnlyOnceErrorHandler"></errorHandler>
      <param name="Append" value="false"/>
      <param name="File" value="${jboss.server.home.dir}/log/app1.log"/>
      <layout class="org.apache.log4j.PatternLayout">
         <param name="ConversionPattern" value="%d{ABSOLUTE} %-5p [%c{1}] %m%n"/>
      </layout>
      <filter class="org.jboss.logging.filter.TCLFilter">
         <param name="AcceptOnMatch" value="true"/>
         <param name="DeployURL" value="app1.ear"/>
      </filter>
   </appender>

...

   <root>
      <appender-ref ref="CONSOLE"></appender-ref>
      <appender-ref ref="FILE"></appender-ref>
      <appender-ref ref="App1Log"></appender-ref>
   </root>

article has been copied from: https://community.jboss.org/wiki/SeparatingApplicationLogs