Thursday, December 13, 2012
Wednesday, November 14, 2012
Monday, October 29, 2012
Unit Testing Runtime Exceptions with JUnit4 and Hamcrest
Junit and Hamcrest make unit testing with Java almost enjoyable. In this post, I show how to unit test Exceptions with JUnit4 and Hamcrest. In this over-simplified example, I'm testing a method that always throws an IllegalArgumentException. In real-life the IllegalArgumentException would only be thrown under special circumstances given certain arguments, and those are the ones you want to test with the unit test.
The basic idea is to surround the method you want to test with a try catch block and pass it an argument that will trigger the IllegalArgumentException to be thrown. The fail method call should never be reached, and if it does the unit test should fail. What should happen is that the IllegalArgumentException is caught, followed by a check for the correct message.
Piece of Cake!!!
The basic idea is to surround the method you want to test with a try catch block and pass it an argument that will trigger the IllegalArgumentException to be thrown. The fail method call should never be reached, and if it does the unit test should fail. What should happen is that the IllegalArgumentException is caught, followed by a check for the correct message.
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.fail;
import org.junit.Test;
/**
* The following example code demonstrates how to unit test Exceptions with JUnit and Hamcrest
*/
public class ExceptionUnitTesting {
@Test
public void test() {
try {
blah("asdf");
fail("Expected exception");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), is(equalTo("Argument foo is not valid!")));
}
}
/**
* @param foo
* @throws IllegalArgumentException - in this test case always
*/
private void blah(String foo) {
throw new IllegalArgumentException("Argument foo is not valid!");
}
}
Piece of Cake!!!
Monday, October 1, 2012
Import a Maven Git Project Into Eclipse
The Easy Way
Prerequisites
Install M2Eclipse
Step 1: Clone or create Git Repo. First, you need to clone a Git repo into an empty folder in your workspace. You need to use a Git client such as SourceTree or TortoiseGit for this. Create you workspace first if it isn't already, and clone the git repo directly into a new folder labeled with the project name.
Step 2: Import Into Eclipse. In the Package Explorer view, right-click and choose Import... In the wizard choose Maven -> "Existing Maven Projects" as the project type. Search for the project home directory and click though the wizard.
The Hard Way
Prerequisites
Install M2Eclipse
Install egit
Step 1: Right-click in the Package Explorer area and select Import..., select Maven -> Check out Maven Projects from SCM, and click Next.
Step 2: Choose "git" as the SCM connector next to "SCM URL:" and type in the Git repo URL. If there are no connectors to choose from you have to first install that Eclipse plugin. To do that, click on the "m2e Marketplace" link in the lower right hand corner of the dialog box.
Step 3: Check m2e-egit and click Finish.
Step 4: Select "git" as the SCM connector and type in the Git repo URL.
Step 5: After asking you for the passphrase for ssh access to the Git repo, it will download and import the Java project as a Maven project into your workspace.
Piece of Cake!!!
Sunday, September 23, 2012
Thursday, September 20, 2012
Wednesday, September 19, 2012
Tuesday, September 11, 2012
Avoiding Name Collisions When Organizing Imports in Eclipse
Is there any way to get Eclipse to automatically give preference to a preferred import when organizing imports? Thankfully, the answer is yes.
For example, I'd like to be able to write:
List myList = new ArrayList();
hit Ctrl + Shift + O and have Eclipse add:
import java.util.List;
And not always ask me which List I want to import:
To tell Eclipse not to ever consider java.awt.List, for example, go to Preferences --> Java --> Appearance --> Type Filters menu. Click add and enter Types you do not want Eclipse to consider for automatic insertion of import statements.
Piece of Cake!!!
For example, I'd like to be able to write:
List
hit Ctrl + Shift + O and have Eclipse add:
import java.util.List;
And not always ask me which List I want to import:
To tell Eclipse not to ever consider java.awt.List, for example, go to Preferences --> Java --> Appearance --> Type Filters menu. Click add and enter Types you do not want Eclipse to consider for automatic insertion of import statements.
Piece of Cake!!!
Tuesday, August 28, 2012
XChange - Open Source Java API for MtGox Bitcoin Exchange
UPDATE March 9, 2013: Version 1.5.0 released. Support for 10 exchanges.
UPDATE Jan 31, 2013: Version 1.4.0 released. Support for Canadian Virtual Exchange. Mostly bug fixes.
UPDATE Jan 16, 2013: Version 1.3.0 released. Support for many more exchanges. See release notes and also XChange Release 1.3.0 Announcement
UPDATE Oct 11, 2012: Version 1.2.0 released. Support for Canadian Virtual Exchange.
Supported Exchanges
Together with other members from the Bitcoin community, I've recently created a new open source Java library called XChange. XChange is a Java library providing a simple and consistent API for interacting with a diverse set of financial security exchanges including Bitcoin. The first exchange implemented is the world's largest Bitcoin exchange - Mt Gox. The plan is to add more Bitcoin exchanges and other traditional financial exchanges offerring trading APIs such as Interactive Brokers.
As of the most recent release 1.1.0, Xchange offers the following functionality:
- Support for MtGox Bitcoin Exchange (public) polling market data (ticker, depth, trades, etc.)
- Support for MtGox Bitcoin Exchange (private) polling trade data (account info, market order, limit order, cancel order open orders, etc.)
- Support for MtGox Bitcoin Exchange (public) streaming market (ticker)
- Support for MtGox Bitcoin Exchange (public) streaming market (depth, trades, etc.)
- Support for MtGox Bitcoin Exchange (private) streaming trade data (account info, market order, limit order, cancel order open orders, etc.)
Relevant Links
Project Home - http://xeiam.com/xchange.jspCode on Github - https://github.com/timmolter/XChange
Example Code - http://xeiam.com/xchange_examplecode.jsp
Examples
The following examples demonstrate getting Ticker data from MtGox, first using the polling API, and second using the streaming API.Ticker via Polling API
package com.xeiam.xchange.examples.mtgox.v1.polling;
import com.xeiam.xchange.Currencies;
import com.xeiam.xchange.Exchange;
import com.xeiam.xchange.ExchangeFactory;
import com.xeiam.xchange.dto.marketdata.Ticker;
import com.xeiam.xchange.service.marketdata.polling.PollingMarketDataService;
/**
* Test requesting polling Ticker at MtGox
*/
public class TickerDemo {
private static PollingMarketDataService marketDataService;
public static void main(String[] args) {
// Use the factory to get the version 1 MtGox exchange API using default settings
Exchange mtGox = ExchangeFactory.INSTANCE.createExchange("com.xeiam.xchange.mtgox.v1.MtGoxExchange");
// Interested in the public polling market data feed (no authentication)
marketDataService = mtGox.getPollingMarketDataService();
// Get the latest ticker data showing BTC to USD
Ticker ticker = marketDataService.getTicker(Currencies.BTC, Currencies.USD);
double value = ticker.getLast().getAmount().doubleValue();
String currency = ticker.getLast().getCurrencyUnit().toString();
System.out.println("Last: " + currency + "-" + value);
System.out.println("Last: " + ticker.getLast().toString());
System.out.println("Bid: " + ticker.getBid().toString());
System.out.println("Ask: " + ticker.getAsk().toString());
// Get the latest ticker data showing BTC to EUR
ticker = marketDataService.getTicker(Currencies.BTC, Currencies.EUR);
System.out.println("Last: " + ticker.getLast().toString());
System.out.println("Bid: " + ticker.getBid().toString());
System.out.println("Ask: " + ticker.getAsk().toString());
// Get the latest ticker data showing BTC to GBP
ticker = marketDataService.getTicker(Currencies.BTC, Currencies.GBP);
System.out.println("Last: " + ticker.getLast().toString());
System.out.println("Bid: " + ticker.getBid().toString());
System.out.println("Ask: " + ticker.getAsk().toString());
}
}
Result:Last: USD-5.14739 Last: USD 5.14739 Bid: USD 5.12011 Ask: USD 5.1299 Last: EUR 4.07 Bid: EUR 4.0527 Ask: EUR 4.07 Last: GBP 3.3452 Bid: GBP 3.3 Ask: GBP 3.34091
Ticker via Streaming API
package com.xeiam.xchange.examples.mtgox.v1.streaming;
import java.util.concurrent.BlockingQueue;
import com.xeiam.xchange.Currencies;
import com.xeiam.xchange.Exchange;
import com.xeiam.xchange.dto.marketdata.Ticker;
import com.xeiam.xchange.mtgox.v1.MtGoxExchange;
import com.xeiam.xchange.service.marketdata.streaming.StreamingMarketDataService;
/**
* Test requesting streaming Ticker at MtGox
*/
public class TickerDemo {
public static void main(String[] args) {
TickerDemo tickerDemo = new TickerDemo();
tickerDemo.start();
}
private void start() {
// Use the default MtGox settings
Exchange mtGox = MtGoxExchange.newInstance();
// Interested in the public streaming market data feed (no authentication)
StreamingMarketDataService streamingMarketDataService = mtGox.getStreamingMarketDataService();
// Get blocking queue that receives streaming ticker data
BlockingQueue tickerQueue = streamingMarketDataService.requestTicker(Currencies.BTC, Currencies.USD);
// take streaming ticker data from the queue and do something with it
while (true) {
try {
// Put your ticker event handling code here
doSomething(tickerQueue.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* Do something fun with the streaming data!
*
* @param ticker
*/
private void doSomething(Ticker ticker) {
System.out.println(ticker.toString());
}
}
Result:Ticker [timestamp=2012-08-26T20:09:13.202Z, last=USD 10.6, bid=USD 10.55248, ask=USD 10.6, tradableIdentifier=BTC, volume=3078691906206] Ticker [timestamp=2012-08-26T20:09:18.651Z, last=USD 10.6, bid=USD 10.55248, ask=USD 10.6, tradableIdentifier=BTC, volume=3068691906206] Ticker [timestamp=2012-08-26T20:09:19.568Z, last=USD 10.6, bid=USD 10.55248, ask=USD 10.6, tradableIdentifier=BTC, volume=3068691906206] Ticker [timestamp=2012-08-26T20:09:23.152Z, last=USD 10.6, bid=USD 10.55248, ask=USD 10.6, tradableIdentifier=BTC, volume=3068691906206] Ticker [timestamp=2012-08-26T20:09:23.975Z, last=USD 10.6, bid=USD 10.55248, ask=USD 10.6, tradableIdentifier=BTC, volume=3068691906206] Ticker [timestamp=2012-08-26T20:09:24.790Z, last=USD 10.6, bid=USD 10.55248, ask=USD 10.6, tradableIdentifier=BTC, volume=3068691906206] Ticker [timestamp=2012-08-26T20:09:25.205Z, last=USD 10.6, bid=USD 10.55248, ask=USD 10.6, tradableIdentifier=BTC, volume=3068691906206] Ticker [timestamp=2012-08-26T20:09:26.018Z, last=USD 10.6, bid=USD 10.55248, ask=USD 10.6, tradableIdentifier=BTC, volume=3068691906206] Ticker [timestamp=2012-08-26T20:09:26.543Z, last=USD 10.6, bid=USD 10.55248, ask=USD 10.6, tradableIdentifier=BTC, volume=3068691906206]Piece of Cake!!!
Subscribe to:
Posts (Atom)






