Sunday, 4 January 2015
Java 8 Examples dedicated blog
Tuesday, 23 December 2014
How to create Interstitial Ad for AdMob in Ionic Cordova app?
You might have encountered an error like, when requesting an ad from AdMob using Cordova AdMob Plugin: interstitialAd is null, call createInterstitialView first
Chances are you are doing it wrong. To create an Interstitial Ad you need to take of three things:
- Use interstitialAdId as the key to pass you ad unit id in your options object
- First create a Interstitial view using createInterstitialView
- In success callback from createInterstitialView use requestInterstitialAd to request an ad
if (window.plugins && window.plugins.AdMob) {
var admob_key = device.platform == "Android" ? "XXXXX" : "YYYYYYYYY";
var admob = window.plugins.AdMob;
var options = {
interstitialAdId: admob_key,
autoShow: true
};
admob.createInterstitialView(options, function() {
admob.requestInterstitialAd({
'isTesting': false
},
function() {
admob.showAd(true);
},
function(error) {
console.log('failed to request ad ' + error);
}
);
},
function() {
console.log('failed to create Interstitial view');
});
} else {
console.log("Admob plugin not available");
}
Thursday, 11 December 2014
Using AmCharts in Play Framework 2 with Java
In this post, I am going to show you how you can use AmCharts in Play Framework 2 using Java.
First create a new Play Framework 2 Java project and download the Javascript libraries for AmCharts. download. After you uncompress the file, you see that there are a lot of files in that folder. You really don't need all of it. To start with, I just chose some of them and put them in the public folder in my Play Framework 2 project:
Make things easier you can also download jQuery.
<script src="@routes.Assets.at("javascripts/jquery-1.11.1.min.js")" type="text/javascript"></script>
<script src="@routes.Assets.at("javascripts/amcharts/amcharts.js")" type="text/javascript"></script>
<script src="@routes.Assets.at("javascripts/amcharts/themes/dark.js")" type="text/javascript"></script>
<script src="@routes.Assets.at("javascripts/amcharts/serial.js")" type="text/javascript"></script>
<script src="@routes.Assets.at("javascripts/amcharts/pie.js")" type="text/javascript"></script>
Now let's create a template file called graph.scala.html and add two empty divs. One for the graph itself and the other for the legend. Also, for the ease of presentation, we put the javascript to handle the graph drawing in this template, but outside the main:
@main("Graphs"){
<div id="test-chart"></div>
<div id="test-legend"></div>
}
<script type="text/javascript">
// code to handle the graph drawing goes here
</script>
Make sure that the tag ids match. Meaning the first section of the id on both tags should be the same: xxxx-chart, xxxx-legend.
AmCharts.ready(function(){
// code goes here
}
Please not that you might see other variations of initialization above across other websites.
Now, let's put the actual code inside the initialization function, for now we use some fake data to show the graph:
var chart = AmCharts.makeChart("test-chart", {
"type": "pie", // type of the graph
"theme": "dark", // the theme
"legend": { // settings for legend
"markerType": "circle",
"position": "right",
"marginRight": 80,
"autoMargins": false
},
"dataProvider": [{
"country": "Czech Republic",
"litres": 256.9
}, {
"country": "Ireland",
"litres": 131.1
}, {
"country": "Germany",
"litres": 115.8
},
"valueField": "litres", // field name to get the value from
"titleField": "country" // field name to get the title from
});
Put the route in the 'routes' file, and Implement an action in a controller to show the page:
public class Application extends Controller {
public static Result showGraph() {
return ok(graph.render(""));
}
}
The final and a very important step is to give an initial width size to your div. Create a css file called main.css in public/stylesheets folder and put the following in it:
#test-chart {
width : 100%;
height : 500px;
font-size : 11px;
}
Make sure you add it to your header in the main.scala.html file:
<link rel="stylesheet" media="screen" href="@routes.Assets.at("stylesheets/main.css")">
Now, run the project and go to the url that you defined in the routes file. You should see something like:
Friday, 5 December 2014
Switching between multiple JDKs on Mac OSX
First. make sure that you download your required JDKs: JDK 8 and JDK 7. gm
Second, look for .bash_profile in your home directory ~. If you can't find it, create it as follows:
touch ~/.bash_profile
Next, use a text editor such as vim to open this file as follows:
vim ~/.bash_profile
Now let's add some aliases that will allow us to easily switch between JDKs:
alias setJdk6='export JAVA_HOME=$(/usr/libexec/java_home -v 1.6)'
alias setJdk7='export JAVA_HOME=$(/usr/libexec/java_home -v 1.7)'
alias setJdk8='export JAVA_HOME=$(/usr/libexec/java_home -v 1.8)'
/usr/libexec/java_home is just a command (symlink) that gives you the path for the active JDK, and using -v xx shows the path to the JDK with version xx.
After you added the above aliases to the .bash_profile file, save and close the file and run:
source ~/.bash_profile
This will set the aliases for you.
Now to switch between the JDKs, just type setJdkX (replace X with the version number). Example:
setJdk8
Thursday, 27 November 2014
How to test file upload action in Play Framework 2 in Java?
public static F.Promise uploadProfileImage() {
final Http.MultipartFormData body = request().body().asMultipartFormData();
final Http.MultipartFormData.FilePart picture = body.getFile("picture");
User user = // get the user from db
final File imgFile = picture.getFile();
final String imgPathToSave = "images/" + "some unique name";
//save on disk
final boolean success = new File("images").mkdirs();
final byte[] bytes = IOUtils.toByteArray(new FileInputStream(imgFile));
FileUtils.writeByteArrayToFile(new File(imgPathToSave),bytes);
user.profileImageUrl = imgPathToSave;
user.save();
}
AS you can see, the body of the request is a MultipartFormData. This makes a bit tricky to write functional tests in Play Framework 2 for Java actually. But, let's see the solution.
@Test
public void uploadProfileImageOK() throws Exception {
MultipartFormData.FilePart part = new MultipartFormData.FilePart<>("picture","test-image.jpg",Scala.Option("image/jpeg"),new File("test-image.jpg"));
MultipartFormData formData = new MultipartFormData(Scala.>emptyMap(),Scala.toSeq(Arrays.asList(part)),Scala.emptySeq(),Scala. emptySeq());
AnyContent anyContent = new AnyContentAsMultipartFormData(formData);
Result uploadImageResult = callAction(controllers.routes.ref.UserController.uploadProfileImage(), fakeRequest().withHeader("Csrf-Token", "nocheck").withCookies(fakeCookie).withAnyContent(anyContent,"multipart/form-data", "POST"));
assertEquals(OK, status(uploadImageResult));
}
To see more about functional testing in Play Framework 2 using Java see:
How to test an action secure by SecureSocial in Play Framework 2 in Java
How to test an action secure by SecureSocial in Play Framework 2 in Java?
public class Application extends Controller {
@SecureSocial.SecuredAction
public static Result index() {
Identity user = (Identity) ctx().args.get(SecureSocial.USER_KEY);
return ok(index.render(user));
}
}
At the time of writing this blog post, SecureSocial only uses cookies for authentication.
If you want to write a functional test for this action without taking care of a fake cookie you will get an unauthorized message. To do this we need to some provisioning before our test. Best is to use the @Befor.
Below is the steps:
- Lets assume that you save your user authentication data in the User model. Here we create a fake user before
- Now create a class named FunctionalTestHelpers and add the following method:
- Now you can use the code below in your tests to get a fake cookie. The code above basically mimics what SecureSocial does for creating a cookie.
- Now lets see it in action:
@Before
public void setUp() throws Exception {
User user = new User();
User user = new User();
user.firstName = "jack";
user.lastName = "sparrow";
user.email = "jack.sparrow@caribbean.com";
user.providerId = "userpasswordid";
user.password = "$2a$10$ywqls6dRsN4wLr.xNydi2uDVFNkOlmi9WSAfRy.RXdN5sgKKnKhau";
user.authMethod = "userPassword";
user.save();
}
Please note that the password that you see above is a hash produced with "Bcrypt" encryption and the value depends on how you have implemented this. See Secure Social Password Plugin for more info.
public static Http.Cookie getFakeCookie(String email){
User user = User.findByEmail(email);
SocialUser socialUser = new SocialUser(new IdentityId(user.email,user.providerId),
user.firstName,
user.lastName,
String.format("%s %s", user.firstName, user.lastName),
Option.apply(user.email),
null,
new AuthenticationMethod("userPassword"),
null,
null,
Some.apply(new PasswordInfo("bcrypt", user.password, null))
);
Either either = Authenticator.create(socialUser);
Authenticator auth = (Authenticator) either.right().get();
Cookie scalaCookie = auth.toCookie();
return new Http.Cookie(scalaCookie.name(),
scalaCookie.value(),
null,
scalaCookie.path(),
null,
scalaCookie.secure(),
scalaCookie.httpOnly());
}
Http.Cookie fakeCookie = FunctionalTestHelpers.getFakeCookie("jack.sparrow@caribbean.com");
final Result deleteResult = callAction(controllers.routes.ref.TaskController.removeTask(taskId),fakeRequest().withCookies(fakeCookie).withHeader("Csrf-Token", "nocheck"));
assertThat(status(deleteResult)).isEqualTo(OK);
Wednesday, 26 November 2014
How to test actions annotated with @RequireCSRFCheck in Play Framework 2?
@RequireCSRFCheck
public Result saveUser() {
// Handle body (process a form)
return ok();
}
Now suppose you want to write some functional tests for this action. All you need to do is to add fake "nocheck" to your header in "callAction" as below:
final Result result = callAction(controllers.routes.ref.UserController.saveUser(),fakeRequest().withHeader("Csrf-Token", "nocheck"));
assertThat(status(result)).isEqualTo(OK);
For more information about CSRF checks in Play Framework 2 see: JavaCsrf
Tuesday, 25 November 2014
Importing a CSV file into a SQLite3 database table in Python
import csv, sqlite3
con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("CREATE TABLE t (col1, col2);")
Now, lets load our .csv file into a dictionary:
with open('data.csv','rb') as fin:
dr = csv.DictReader(fin) # comma is default delimiter
to_db = [(i['col1'], i['col2']) for i in dr]
csv.DictReader uses first line in the .csv file for column headings by default. Comma is also the default delimiter.
The actual import:
cur.executemany("INSERT INTO t (col1, col2) VALUES (?, ?);", to_db)
con.commit()
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys, csv, sqlite3
def main():
con = sqlite3.connect(sys.argv[1]) # database file input
cur = con.cursor()
cur.executescript("""
DROP TABLE IF EXISTS t;
CREATE TABLE t (COL1 TEXT, COL2 TEXT);
""") # checks to see if table exists and makes a fresh table.
with open(sys.argv[2], "rb") as f: # CSV file input
reader = csv.reader(f, delimiter=',') # no header information with delimiter
for row in reader:
to_db = [unicode(row[0], "utf8"), unicode(row[1], "utf8")] # Appends data from CSV file representing and handling of text
cur.execute("INSERT INTO neto (COL1, COL2) VALUES(?, ?);", to_db)
con.commit()
con.close() # closes connection to database
if __name__=='__main__':
main()
Please not that the code above, we encode the input.
Preventing the modification of a private field in Java
public class Test
{
private String[] arr = new String[]{"1","2"};
public String[] getArr()
{
return arr;
}
}
Test test = new Test();
test.getArr()[0] ="some value!"; //!!!
Bam! We were able to modify a private field outside of the class. This not what you want! To avoid this situation, you can use of the following solutions:
- Either create a defensive copy:
- If you can use a List instead of an array, Collections provides an unmodifiable list:
public String[] getArr() {
return arr == null ? null : Arrays.copyOf(arr, arr.length);
}
public List getList() {
return Collections.unmodifiableList(list);
}
What is the use of “assert” in Python?
assertstatement/function exists in mostly every other programming language out there. When you do...
assert a_condition
... you're telling the program to test that condition, and trigger an error if the condition is false.
In Python, it's roughly equivalent to this:
if not condition:
raise AssertionError()
Try it in the Python shell:
>>> assert True
>>> assert False
Traceback (most recent call last):
File "", line 1, in
AssertionError
Assertions can include an optional message, and you can disable them when you're done debugging. See here for the relevant documentation.
What is a percolator in Elasticsearch?
How to set specific logging for tests in Play Framework 2 ?
Play Framework 2's default logging is logback. To set specific logging configurations for tests follow the steps below:
- Just create a logback configuration file (eg test-logger.xml):
-
Go to root project folder, open
build.sbt
file and add:
Now whenever you run your tests, the logging configuration written injavaOptions in Test +="-Dlogger.resource=test-logger.xml"test-logger.xml
will be read.
<configuration>
<conversionRule conversionWord="coloredLevel" converterClass="play.api.Logger$ColoredLevel" />
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>${application.home}/logs/application.log</file>
<encoder>
<pattern>%date - [%level] - from %logger in %thread %n%message%n%xException%n</pattern>
</encoder>
</appender>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%coloredLevel %logger{15} - %message%n%xException{5}</pattern>
</encoder>
</appender>
<logger name="play" level="INFO" />
<logger name="application" level="DEBUG" />
<!-- Off these ones as they are annoying, and anyway we manage configuration ourself -->
<logger name="com.avaje.ebean.config.PropertyMapLoader" level="OFF" />
<logger name="com.avaje.ebeaninternal.server.core.XmlConfigLoader" level="OFF" />
<logger name="com.avaje.ebeaninternal.server.lib.BackgroundThread" level="OFF" />
<logger name="com.gargoylesoftware.htmlunit.javascript" level="OFF" />
<root level="ERROR">
<appender-ref ref="STDOUT" />
<appender-ref ref="FILE" />
</root>
</configuration>
Thursday, 2 August 2012
Installing psycopg in ubuntu for python
libpq-dev python-dev using sudo apt-get install. and then easy_install psycopg2
Wednesday, 27 June 2012
Installing numpy and scipy inside a virtualenev
- sudo apt-get install git gfortran g++
- sudo apt-get install libatlas-base-dev liblapack-dev
- pip install numpy scipy
How to install virtualenv, virtualenvwrapper in ubuntu
sudo apt-get update
sudo apt-get install python-setuptools python-dev build-essential git-core -y
sudo easy_install pip
sudo pip install virtualenv
sudo pip install virtualenvwrapper
mkdir ~/virtualenvs
echo "export WORKON_HOME=~/virtualenvs" >> ~/.bashrc
echo "source /usr/local/bin/virtualenvwrapper.sh" >> ~/.bashrc
echo "export PIP_VIRTUALENV_BASE=~/virtualenvs" >> ~/.bashrc
source ~/.bashrc
mkvirtualenv blog
If you want to get out/off your virtualenv use this command:
deactivate
If you want to jump back on the virtualenv we just created and installed django use this command:
workon xxx
And finally if you want to remove the virtualenv altogether
rmvirtualenv blog
Create a new PyDev Project
File -> New -> PyDev ProjectA window will popup asking about the project details. Alternatively if you have already created a project go to
Project -> PropertiesClick on "Click here to configure an interpreter no listed"
Click the New buttonA new window will popup
Interpreter name: VIRTUALENVNAME (or whatever you like)
Interpreter executable: ~.virtualenvs/VIRTUALENVNAME/bin/python (or your custom location to the virtualenv/bin/python)
Tuesday, 26 June 2012
Standard Directory Layout in Maven
Look here: Standard Folder Structure in Maven
Monday, 25 June 2012
Which dependency in the hierarchy does Maven use when managing dependencies
The truth is that it uses Maven resolves the version nearest to the top of the dependency tree in the end. To view this dependency tree type:
mvn dependency:tree
resource: Maven dependency management
Setting up jdk path (JAVA_HOME) for Tomcat7 in ubuntu
- no JDK found - please set JAVA_HOME
#Java Environment Variable
JAVA_HOME=/usr/lib/jvm/jdk1.7.0/
export JAVA_HOME
JRE_HOME=/usr/lib/jvm/jdk1.7.0/jre
export JRE_HOME
PATH=$PATH:$JAVA_HOME:$JRE_HOME
export PATH
Now, normally, after reopening the terminal and issuing "sudo service tomcat7 start" should start the tomcat. But if you see the error above again:
- no JDK found - please set JAVA_HOME
Just to this:
"gksudo gedit /etc/default/tomcat7" and uncomment the line that sets the JAVA_HOME variable:Now run the tomcat. This should do the trick.
If you are interested in seeing some examples in Java 8, checkout my new blog about Java 8 Examples click on this link: Java 8 Examples
Thursday, 21 June 2012
Difference between "Provided" and "Compiled" scopes Maven?
compile and provided
when artifact is builded as a JAR? If it was WAR, then I understand -
artifact would be attached or not to WEB-INF/lib. But in case of the JAR
it doesn't matter - dependencies aren't attached. They have to be on
classpath when their scope is compile or provided. I know that provided dependencies aren't transitive - but is it only one difference?A:
This is the default scope, used if none is specified. Compile dependencies are available in all classpaths of a project. Furthermore, those dependencies are propagated to dependent projects.
- compile
This is much like compile, but indicates you expect the JDK or a container to provide the dependency at runtime. For example, when building a web application for the Java Enterprise Edition, you would set the dependency on the Servlet API and related Java EE APIs to scope provided because the web container provides those classes. This scope is only available on the compilation and test classpath, and is not transitive.
- provided
- dependencies are not transitive (as you mentioned)
- provided scope is only available on the compilation and test classpath, whereas compile scope is available in all classpaths.
- provided dependencies are not packaged
Source: http://stackoverflow.com/questions/6646959/difference-between-maven-scope-compile-and-provided-for-jar-packaging


