Android: Cloud Messaging Hello world using GCM, AWS SNS and Parse

Categories: AndroidDevelopment NotesJava; Tagged with: ; @ May 24th, 2015 23:12

Quick start using GCM

0. Create your project via “Google developers console”;

1. Prepare Client App:

  – Get device registration ID

– Receive message from GCM

Example: https://github.com/hmkcode/Android/tree/master/android-gcm-client

2. Send Message to GCM server

– Send(Post) message to GCM server
Example: https://github.com/hmkcode/Android/tree/master/java-post-gcm

3. Start your app(#1), then send message ( #2)

 

Push message via AWS SNS to Android devices

Login to AWS console

1. Create new application with your GCM API key

2. ‘Create platform endpoint’ using your device registration ID;

3. Select your device and ‘Publish to endpoint’ to publish a message

4. Check your device;

 

Push Message via Parse Push

Need to modify the client app and then push message from Parse console;

BDD: Cucumber Hello World Using Java and IntelliJ

Categories: Java; Tagged with: ; @ March 14th, 2015 16:42

Example:

Feature: Convert between different currencies
  Scenario: Convert SGD to CNY
    Given currency:"SGD", amount:10
    Given fxRate is 4.60
    When convert to "CNY"
    Then the result is 46 in CNY

JUnit Test: it can be generated by cucumber plugins, but not perfect for my IDE. (cannot generate all steps, but you still can copy the generated JUnit code from the output)

package com.liguoliang.bdd;

import cucumber.annotation.Before;
import cucumber.annotation.en.Given;
import cucumber.annotation.en.Then;
import cucumber.annotation.en.When;
import org.junit.Assert;

import java.math.BigDecimal;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

/**
 * Created by guoliang on 3/14/15.
 */
public class FxConverterTest {

    private FxConverter fxConverter;

    @Before
    public void setUp() {
        fxConverter = new FxConverter();
    }


    @Given("^currency:\"([^\"]*)\", amount:(\\d+)$")
    public void currency_amount(String currency, BigDecimal amount) throws Throwable {
        fxConverter.setCurrencySource(currency);
        fxConverter.setAmountInput(amount);
    }

    @Given("^fxRate is (.+)$")
    public void fxRate_is_(BigDecimal rate) throws Throwable {
        fxConverter.setFxRate(rate);
    }

    @When("^convert to \"([^\"]*)\"$")
    public void convert_to(String currency) throws Throwable {
        fxConverter.convertTo(currency);

    }

    @Then("^the result is (.+) in CNY$")
    public void the_result_is_in_CNY(BigDecimal resultExpected) throws Throwable {
        assertTrue(resultExpected.compareTo(fxConverter.getAmountResult()) == 0);
    }

}

Java: calculate number complement using BitSet

Categories: Java; Tagged with: ; @ March 10th, 2015 20:15

Two’s complement is the way every computer I know of chooses to represent integers. To get the two’s complement negative notation of an integer, you write out the number in binary. You then invert the digits, and add one to the result.

www.cs.cornell.edu/~tomf/notes/cps104/twoscomp.html

    	Integer input = 50;
    	
    	String binString = Integer.toBinaryString(input);
    	BitSet bitSet = BitSet.valueOf(new long[] {input});
    	
    	for (int i = 0; i < binString.length(); i++) {
			bitSet.flip(i);
		}
    	
    	System.out.println(Arrays.toString(bitSet.toByteArray()));

Switch: throw an exception if default section shouldn’t be reached? #Route 85 – Quick Tip: Don’t Default that Switch!

Categories: Java; Tagged with: ; @ March 8th, 2015 21:32

There’s a quick tip from Google developers about switch, the suggestion is getting rid of throwing exception in switch default section if the default handler shouldn’t be reached.

Here’s an example in Java:

package com.liguoliang.java.core.lang.enum_;

/**
 * Created by Guoliang, Li(liguoiang.com) on 3/8/2015.
 */

public class SwitchDefaultDemo {

    public static void main(String[] args) {
        System.out.println(getBookCategoryDesc(BookCategory.JAVA));
;    }

    private static String getBookCategoryDesc(BookCategory bookCategory) {
        String desc = null;
        switch (bookCategory) {
            case JAVA:
                desc = "It's a Java book";
                break;
            case PYTHON:
                desc = "It's a PHP book";
                break;
            default:
                throw new RuntimeException("Unknown book category");
        }

        return desc;
    }

    public static enum BookCategory {
        JAVA, PYTHON, PHP;
    }
}

The tip’s point is if developer added a new enum and forgot to update the switch statement accordingly, there’ll be a issue, it may fail the test or crash the application.

so to improve the switch statement, the video suggest to remove the default section. if some client calls getBookCategoryDesc(PHP), the method will be executed normally, instead of throwing an exception.

it seems debatable for me, I prefer to keep the exception,  throwing an exception to exposure the risk instead of hiding it, because the exception tells the details, developers can fix the bug immediately. otherwise, developers will realize the issue and start to debug until user reporting it.

Using bounded wildcards in Java Generics

Categories: Java March 3rd, 2015 22:29

Code:

package com.liguoliang.java.core.lang.generics;

import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

import static org.junit.Assert.*;

public class GenericsWildCardTest {

private GenericsWildCard genericsWildCard;

private List<Integer> listOfIntegers;
private List<Number> listOfNumbers;
private List<Long> listOfLong;
private List<Object> listOfObjects;

@Before
public void before() {
genericsWildCard = new GenericsWildCard();

listOfIntegers = new ArrayList<Integer>();
listOfIntegers.add(1);
listOfIntegers.add(2);

listOfNumbers = new ArrayList<Number>();
listOfNumbers.add(1.1);

listOfLong = new ArrayList<Long>();
listOfLong.add(100L);

listOfObjects = new ArrayList<Object>();
}

@Test
public void testMergeList_() throws Exception {
List<Integer> listOfIntegers = new ArrayList<Integer>();
List<Number> listOfNumbers = new ArrayList<Number>();

int sizeExpected = listOfIntegers.size() + listOfNumbers.size();
genericsWildCard.mergeList_(listOfIntegers, listOfNumbers);
assertEquals(sizeExpected, listOfNumbers.size());
}

@Test
public void testMergeListWithWildCard() {
int sizeExpected = listOfIntegers.size() + listOfNumbers.size();
genericsWildCard.mergeListWithBoundedWildCard(listOfIntegers, listOfNumbers);
assertEquals(sizeExpected, listOfNumbers.size());

sizeExpected = listOfLong.size()+ listOfObjects.size();
genericsWildCard.mergeListWithBoundedWildCard(listOfLong, listOfObjects);
assertEquals(sizeExpected, listOfObjects.size());
}
}

 
package com.liguoliang.java.core.lang.generics;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
* Created by Guoliang, Li(liguoiang.com) on 3/3/2015.
*/
public class GenericsWildCard {

protected void mergeList_ (List<Integer> subList, List<Number> superList) {
}

protected void mergeListWithBoundedWildCard(List<? extends Number> subList, List<? super Number> superList) {
for (Number number : subList) {
superList.add(number);
}

Number firstItem = subList.get(0);

// subList.add(firstItem); // cannot be applied to Number;
// subList.add(Integer.valueOf(1)); // cannot be applied to Interger;

// superList.add(firstItem);
// superList.add(Integer.valueOf(1));
// superList.add(new Object()); // cannot be applied to Object
}


private static void mergeList(List<? extends Number> subList, List<? super Number> superList) {
Integer i = (Integer) subList.get(0);
Number n = i;

//subList.add(n); // cannot be applied
Number n1 = 0;
// subList.add(0);
// subList.add(n1);
// subList.add(0);

superList.add(i);
superList.add(n);
}

public static void main(String[] args) {
List<Number> listOfNumbers = new ArrayList<Number>();
listOfNumbers.add(0.9);
listOfNumbers.add(2.1);

List<Integer> listOfIntegers = new ArrayList<Integer>();
listOfIntegers.add(1);
listOfIntegers.add(3);

List<Object> listOfObjects = new ArrayList<Object>();

mergeList(listOfNumbers, listOfNumbers);
// mergeList(listOfNumbers, listOfIntegers);
// mergeList(listOfIntegers, listOfObjects);
}
}
 

Notes:

List<Integer> is not List<Number>
List<Integer> is List<? extends Number>

PECS – producer-extends, consumer-super;

Cannot add any item to List<? extends Object>

Older Posts



// Proudly powered by Apache, PHP, MySQL, WordPress, Bootstrap, etc,.