Git snippets

These are a view things that i had looked up to solve some problems and i plan to update this post regularly…

To push a new branch to remote

git push origin new_branch

To delete a remote branch

git push origin :new_branch

To push new tags

git push --tags origin

To delete a remote tag

git tag -d 12345
git push origin :refs/tags/12345

To reset a local branch to exactly match a remote branch

git fetch origin
git reset --hard origin/master

To abort a rebase

git rebase --abort

Changing the origin of your git repository (relocate the repository)

git config remote.origin.url [new origin url]

How do I make git ignore mode changes (chmod)?

git config core.filemode false

Delete the last commit if it is not pushed yet:

git reset --soft HEAD~1

Remove file from repository but not from filesystem (in case you’ve ignored a file but don’t want to delete it)

git rm --cached Foobar.java

Short log (oneline), including sha and date

git log --pretty=format:"%h %ad%x09%an%x09%s" --date=short

Count commits by author:

git shortlog -s -n

Display the first n commits:

git log --pretty=format:"%h %ad%x09%an%x09%s" --date=short  --reverse | head -20

Merge a branch but don’t commit the merge yet (and avoid fast-forwards):

git merge --no-commit --no-ff theAwesomeFeatureBranch

List all files changed since commit:

git git diff --name-only  COMMIT_ID_OR_WHATEVER_COMMITISH

This one is useful, if you did a lot of amending to an old commit and want to restore it’s date order for your inner monk:

Do an interactive rebase, edit the commit in question with “e” or “edit”, so that you can amend it again and then continue rebase:

git rebase -i <ref>
git commit --amend --reset-author --no-edit
git rebase --continue

Or you could move around the commit during your rebase as well, if it isn’t your last commit.

Group commits by author:

git shortlog -s -n

Reduce the repositories database size:

git reflog expire --all --expire=now
git gc --prune=now --aggressive

(See this answer)

Pushes a subtree onto a different branch (“dist” being the subtree here):

git subtree push --prefix dist origin gh-pages

Create a new branch with all the content from the parent but without commits:

git checkout --orphan public

Last update: 2019/01/06

| Comments (0) »

22-Dec-11


oEmbedding twitter updates with Java and WordPress

I’m really a big fan of oEmbed. My project Daily Fratze acts as oEmbed provider and consumer for example.

Now I’m really happy that twitter announced that it now acts as an oembed provider:

(I’d even be happier if twitter would autodiscover providers 😉 )

To use this in a Java based application you can use my java-oembed lib with the following configuration:

Oembed oembed = new OembedBuilder(this.httpClient)
	.withCacheManager(cacheManager)
	.withBaseUri("http://yourproject")
	.withConsumer("yourproject")
	.withProviders(					
			new OembedProviderBuilder()
				.withName("twitter")
				.withFormat("json")
				.withMaxWidth(480)
				.withEndpoint("https://api.twitter.com/1/statuses/oembed.%{format}")
				.withUrlSchemes("https?://twitter.com/#!/[a-z0-9_]{1,20}/status/\\d+")
				.build()
	 )
	.withHandlers(new CommonHandler("twitter"))
	.build();

The handler looks like this:

import org.apache.commons.lang.StringEscapeUtils;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
 
import ac.simons.oembed.OembedResponse;
import ac.simons.oembed.OembedResponseHandler;
 
 
public class CommonHandler implements OembedResponseHandler {
	private String handlerFor;
 
	public CommonHandler(String handlerFor) {
		this.handlerFor = handlerFor;
	}
 
	@Override
	public String getFor() {
		return handlerFor;
	}
 
	@Override
	public void handle(Document document, Element a, OembedResponse response) {
		final StringBuilder hlp = new StringBuilder();
 
		final String title = StringEscapeUtils.escapeHtml(response.getTitle());
		if(response.getType().equalsIgnoreCase("video") || response.getType().equalsIgnoreCase("rich")) {
			hlp.append("<span style=\"display:block; text-align:center;\">");
			hlp.append(response.getHtml());
			hlp.append("</span>");
		} else if(response.getType().equalsIgnoreCase("photo")) {			
			hlp.append("<span style=\"display:block; text-align:center;\">");			
			hlp.append(String.format("<img src=\"%s\" alt=\"%s\" title=\"%s\" style=\"width: %d; height: %d;\" />", response.getUrl(), title, title, response.getWidth(), response.getHeight()));			
			hlp.append("</span>");
		}
 
		a.before(hlp.toString());
		a.remove();		
	}
}

Be careful to get the latest release, twitter has some real large values for cache ages and i needed to update a member from int to long.

To have WordPress automatically embed statusupdates, add the following line to the “functions.php” of your current theme. Create the file if it isn’t available in the root folder of your theme:

wp_oembed_add_provider('#https?://twitter.com/\#!/[a-z0-9_]{1,20}/status/\d+#i', 'https://api.twitter.com/1/statuses/oembed.json', true);

Whenever you add the plain link (whithout an anchor tag) to a statusupdate on a single line in a post, it will be embedded like the example above.

Update

If you are more into plugins, just download my Enable Twitter oEmbed WordPress plugin, install it and you’re good to go.

An alternative to oEmbed for Twitter was the Twitter Blackbird Pie Plugin for WordPress, but why adding more stuff if everything else is already there? My plugin is much more lightweight.

Embedding me looks like this, by the way:

michael | DailyFratze.de ...täglich frisch!

the picture will always show my latest update on daily fratze.

As this is probably the last post here for this year, i wish every visitor some nice christmas holidays!

| Comments (0) »

20-Dec-11


Scripted network mounts with Windows

I have some services and scheduled tasks that call a Batch file under windows. The scheduled tasks cannot access network drives that the assigned user has defined, but luckily there is a “mount” pendant within Windows as well.

To mount a network share within the Batch script use:

net use t: \\server\share /persistent:no

The authentication is taken from the user that is assigned to the task.

If this not enough use

net use t: \\server\share /persistent:no /user:user@domain password

To unmount the share use

net use t: /delete

| Comments (0) »

12-Dec-11


Java stuff

Here is some Java stuff I’ve written over the last year for Daily Fratze. All of the stuff is in use on Daily Fratze since June 2011.

java-akismet
java-akismet is a simple client for Akismet based on the latest version of Apache HttpComponents.
java-oembed
I really like the idea of oEmbed: A mechanism for auto embedding stuff from other sites so that users don’t have to paste some html code into a textbox but just plain links. This is my version of a configurable Java client that can autodetect oEmbed endpoints as well as statically configured endpoints.
java-autolinker
This is my idea of an autolinker based on jsoup. If you want to get autolinking right, you have to parse the text. Just scanning for regex that matches urls or email addresses is not enough. This autolinker first parses the text into a DOM tree and passes all text nodes to the configured linkers. At the moment it supports URLs, email addresses and twitter handles.

I’d be happy if someone can actually use this stuff too or even contribute to it 🙂

| Comments (1) »

28-Nov-11


Fixing hibernate “Cannot release connection” exception using DBCP and MySQL.

Every 8 hours i got a Hibernate exception “Cannot release connection” within a Java application using Hibernate, Apache DBCP on Tomcat:

org.hibernate.exception.GenericJDBCException: Cannot release connection
    at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:103)
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:91)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:29)
    ..
    ..
Caused by: java.sql.SQLException: Already closed.

Not only that the messages polluted my inbox, the exception was visible to the enduser, resulting in a HTTP 500 error. An older blog post i found suggested dismissing DBCP and using c3p0, a solution that i’m not quite found of. At least, the post helped to reproduce the problem within my development setup. The underlying problem was indeed the MySQL wait_timeout.

There’s quite a long documentation on the Tomcat JDBC Connection Pool. Although the Tomcat team recommends their own solution since Tomcat 7, i still wanted to go with DBCP.

The relevant keywords are “testOnBorrow”, “testOnReturn”, “testWhileIdle”, “validationQuery” and “timeBetweenEvictionRunsMillis”. The first 3 are boolean values. If set to true, the query given as validationQuery is executed on borrowing a connection from the pool, on returning or when idling. The first option is not an option on production use as the query is executed before each call. Although “Select 1” is probably very fast, i just don’t want to have. Also: The problem is an invalidated, idle connection so i set testWhileIdle to true. And what happened? Nothing! The problem stayed. So there is the last option timeBetweenEvictionRunsMillis which should, according to the docs, default to 5 seconds but it doesn’t. The documentation is wrong. It’s under zero, so the eviction thread that tests idle connections never run. I’ve tweeted the tomcat team, but there was no reaction.

So the correct configuration for a DBCP pool database source is:

<Resource
	type="javax.sql.DataSource"
	driverClassName="com.mysql.jdbc.Driver"
	maxActive="100"
	maxIdle="30"
	maxWait="10000"
	testOnBorrow="false"
	testOnReturn="false"
	testWhileIdle="true"
	validationQuery="Select 1"
	timeBetweenEvictionRunsMillis="1800000"
/>

This way the eviction thread runs every 30 minutes, testing idle connections with the query “Select 1” and removing them from the pool. The timeBetweenEvictionRunsMillis should not be to low. It should be adapted to the configured MySQL wait_timeout.

| Comments (2) »

21-Nov-11