About jontas

I like to make things that people find useful.

Java org.w3c.dom.Document add attribute to Node(s) (Element(s))

This example will add((or update if exists) a attribute to one or several Element(s).

NodeList nodeList = document.getElementsByTagName("tagToFind");
for (int i = 0; i < nodeList.getLength(); i++){
	( (Element)nodeList.item(i) ).setAttribute("attributeNameToAdd", "attributeStringValueToAdd");
}

And what the manual (jdk6u30) says about setAttribute:

setAttribute

void setAttribute(String name,
String value)
throws DOMException

Adds a new attribute. If an attribute with that name is already present in the element, its value is changed to be that of the value parameter. This value is a simple string; it is not parsed as it is being set. So any markup (such as syntax to be recognized as an entity reference) is treated as literal text, and needs to be appropriately escaped by the implementation when it is written out. In order to assign an attribute value that contains entity references, the user must create an Attr node plus any Text and EntityReference nodes, build the appropriate subtree, and use setAttributeNode to assign it as the value of an attribute.
To set an attribute with a qualified name and namespace URI, use the setAttributeNS method.

Parameters:
name – The name of the attribute to create or alter.
value – Value to set in string form.
Throws:
DOMException – INVALID_CHARACTER_ERR: Raised if the specified name is not an XML name according to the XML version in use specified in the Document.xmlVersion attribute.
NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly.

Java org.w3c.dom.Document getting an attribule as a string from a Node (Element)

This example shows how to get a list of attribute values from all elements with a given name.
Might not fit your needs but it should give a good idea on how to do things that are similar to this (like simply get a attribute from a singe Element).

public static List<String> getAttributesByElementName(String attribute, String element, String xmlString){
	ArrayList<Integer> listToReturn = new ArrayList<Integer>();
 
	Document document = XmlUtils.loadXMLAsDom(xmlString);
	NodeList nodeList = document.getElementsByTagName(element);
	for (int i = 0; i < nodeList.getLength(); i++){
		String currAttribute = ( (Element)nodeList.item(i) ).getAttribute(attribute);
		if ( !currAttribute.isEmpty() ){
			listToReturn.add(currAttribute );
		}
	}
	return listToReturn;
}

Java org.w3c.dom.Document output nicely formatted

This will print a nicely formatted (indented, linebreaks etc) i.e. more human readable xml document.

public static String getNiceLyFormattedXMLDocument(Document doc) throws IOException, TransformerException {
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
 
    Writer stringWriter = new StringWriter();
    StreamResult streamResult = new StreamResult(stringWriter);
    transformer.transform(new DOMSource(doc), streamResult);
    String result = stringWriter.toString();
 
    return result;
}

Java get a XML document (file, string or inputstream) as a org.w3c.dom.Document

This helper function will read a xml string (or any InputStream) and create a Document from this.

public static Document loadXMLAsDom(String xml){
	return loadXMLAsDom(new ByteArrayInputStream(xml.getBytes()));
}
public static Document loadXMLAsDom(InputStream inputStream) {
	DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
	documentBuilderFactory.setNamespaceAware(true);
	DocumentBuilder documentBuilder = null;
	Document document = null;
	try{
		documentBuilder  = documentBuilderFactory.newDocumentBuilder();
		document = documentBuilder.parse(new InputSource(inputStream)); //use InputSource here to get better support for encodings
		inputStream.close();
	}
	catch (ParserConfigurationException e){
		System.out.println("loadXMLAsDom got a ParserConfigurationException! "); e.printStackTrace;
	}
	catch (IOException e){
		System.out.println("loadXMLAsDom got a IOException! "); e.printStackTrace;
	}
	catch (SAXException e){
		System.out.println("loadXMLAsDom got a SAXException! "); e.printStackTrace;
	}		
	return document;
}

Java getting exception.printStackTrace as a string

In cases like when I simply want to make a System.out.println or similar with some details of a exception then the following static helper function is very nice as it takes the exception (uses printStackTrace) and returns a string with the contents of it.

public static String getStackTrace(Exception e){
	StringWriter stringWriter = new StringWriter();
	PrintWriter printWrtier = new PrintWriter(stringWriter);
	e.printStackTrace(printWrtier);
	return stringWriter.toString();
}

Android custom dialog

This will create a custom dialog.

AlertDialog.Builder builder;
AlertDialog alertDialog;
 
Context mContext = this;
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.help_dialog, (ViewGroup) findViewById(R.id.layout_root));
 
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText(getString(R.string.help_string));
 
builder = new AlertDialog.Builder(mContext);
builder.setView(layout);
alertDialog = builder.create();
 
alertDialog.show();

And create a “help_dialog.xml” this name is from the inflater

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout_root"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    >
    <TextView android:id="@+id/text"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:textColor="#FFF"
        />
</LinearLayout>

LayoutInflater at android dev

Android getString(R.string.text) in a static method

Sometimes there is a need to access recourses from static methods.
In order to do this we need to pass along the Context to the method and use getString from that Context.

Example:

package com.f15ijp.android.test;
 
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.WindowManager;
 
public class Help {
	public static AlertDialog helpDialog(Context theContext, String helpMessage){
	AlertDialog alertDialog = new AlertDialog.Builder(theContext).create();            	
    	alertDialog.setTitle("Help");
    	alertDialog.setMessage(helpMessage);
    	alertDialog.setButton(theContext.getString(R.string.close_help_btn), new DialogInterface.OnClickListener() {
	    @Override
	    public void onClick(DialogInterface dialog, int which) {
		return;						
	    }
	});
    	WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        lp.copyFrom(alertDialog.getWindow().getAttributes());
        lp.width = WindowManager.LayoutParams.FILL_PARENT;
        lp.height = WindowManager.LayoutParams.FILL_PARENT;
        /*by calling alertDialog.show() now and then again after setAttributes the background
         * the background activity is replaced by a black box. 
         * If this first alertDialog.show() is removed then the (current) acitivity is used as a background. 
         */
        alertDialog.show();
        alertDialog.getWindow().setAttributes(lp);
        return alertDialog;
    }
}

Java iterating over a Map

In java it is not hard to iterate over a Map. The following example is quick and simple (and if your Map is not of this sort you can change it accordingly easily).

for (Map.Entry<String, Object> entry : map.entrySet()) {
    String key = entry.getKey();
    Object value = entry.getValue();
    // ... do important stuff here!
}

Scala lift list.length() error: Int does not take parameters

When using myList.length() you will get an error message similar to this one

[INFO] Compiling 10 source files to /.../target/classes at 1317721118837
[ERROR] /.../src/main/scala/code/lib/MyLib.scala:216: error: Int does not take parameters
[INFO] 	  var listLength = myList.length()

What the error means is that length is not a function, but simply a property and you should use myList.length and not myList.length()