Log4j2 configuration example

Here is a simple log4j2 configuration file with a custom logging level for select few packages

  1. Create a file log4j2.xml at src/main/resources directory
  1. <?xml version="1.0" encoding="UTF-8"?><Configuration status="WARN"> <Appenders> <Console name="Console" target="SYSTEM_OUT"> <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/> </Console> </Appenders> <Loggers> <Logger name="com.foo.Bar" level="trace"> <AppenderRef ref="Console"/> </Logger> <Root level="error"> <AppenderRef ref="Console"/> </Root> </Loggers></Configuration>

Howto marshal an instance of protobuf to JSON

Proto

syntax = "proto3";

package myproto;

message MyMessage {
    string name = 1;
    int32 age = 2;
}

package main

import (
    "fmt"
    "github.com/golang/protobuf/jsonpb"
    "github.com/golang/protobuf/proto"
    "myproto" // Import the generated protobuf package
)

func main() {
    // Create an instance of MyMessage
    myMessage := &myproto.MyMessage{
        Name: "Alice",
        Age:  30,
    }

    // Create a JSON marshaler
    marshaller := &jsonpb.Marshaler{}

    // Marshal the protobuf message to JSON
    jsonString, err := marshaller.MarshalToString(myMessage)
    if err != nil {
        fmt.Println("Error marshaling to JSON:", err)
        return
    }

    // Print the JSON string
    fmt.Println(jsonString)
}

How to unmarshal protobuf to json in golang

package main

import (
	"encoding/json"
	"fmt"
)

// Define a struct
type SomeStruct struct {
	ID    int    `json:"id"`
	Title string `json:"title"`
}

func main() {
	jsonString := `{
        "id": 1,
        "title": "Some title"
    }`

	var item SomeStruct

	// Unmarshal the JSON data into the struct
	if err := json.Unmarshal([]byte(jsonString), &item); err != nil {
		fmt.Println("Error unmarshaling content:", err)
		return
	}

	fmt.Println("ID:", item.ID)
	fmt.Println("Title:", item.Title)
}

Loop through dictionary/map/array

#PHP
foreach($map as $k => $v){
echo “key: {$k}, value:{$v}”;
}

#objective-c
for(id key in myDict){
NSLog(@”key:%@, value:%@”, key, [myDict objectForKey:key]);
}

#python
for key in myDict.iterkeys():
print (“key:{0}, value:{0}”.format(key, myDict[key])

#java
for (String key : map.keySet()) {
System.out.println(“key: ” + key + “, value:” + map.get(key));
}

iPhone – Protocol & Delegate Implementation

CustomHttpRequest.h

@protocol CustomHTTPRequestDelegate

@required
-(void) receivedDataForURL : (NSString *) reqUrl resultData: (NSDictionary *) result_;

@end
@property (retain) id delegate;

CustomHttpRequest.m
[[self delegate] receivedDataForURL:urlStr resultData:dic];

—–

.h
@interface VCAtm : UIViewController {
}

.m
CustomHttpRequest *httpReq = [[CustomHttpRequest alloc] initWithURL:url];
httpReq.delegate = self;

#pragma mark –
#pragma mark CustomHttpRequest Delegate

-(void) receivedDataForURL : (NSString *) reqUrl resultData:(NSDictionary *) result_{
NSLog(@”reqURL %@”, reqUrl);
NSLog(@”result data %@”, result_);

//show all values
for (id key in result_) {
id value = [result_ objectForKey:key];
NSString *keyAsString = (NSString *)key;
NSString *valueAsString = (NSString *)value;

NSLog(@”key: %@”, keyAsString);
NSLog(@”value: %@”, valueAsString);
}

NSArray *results = [result_ objectForKey:@”results”];
for (NSDictionary *result in results) {
NSString *name = [result objectForKey:@”name”];
[nameList addObject:name];
NSLog(@”Name : %@”, name);
}

atmTableView.delegate = self;
atmTableView.dataSource = self;
[atmTableView reloadData];

}

iPhone – Convert NSMutableData to ios JSON object and parse the data

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[self.responseData length];
//convert to json
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:nil];

//show all values
for (id key in dic) {
id value = [dic objectForKey:key];
NSString *keyAsString = (NSString *)key;
NSString *valueAsString = (NSString *)value;

NSLog(@"key: %@", keyAsString);
NSLog(@"value: %@", valueAsString);
}

NSArray *results = [dic objectForKey:@"results"];
for (NSDictionary *result in results) {
NSString *name = [result objectForKey:@"name"];

[nameList addObject:name];
NSLog(@"Name : %@", name);
}

Android Maps

The Location-based services in android offers two APIs
1. Mapping
2. Location-based

Here we’ll talk about the first API i.e mapping
– The mapping package is com.google.android.maps

Things needed for android map
1. Internet connectivity – Since mapping APIs often reach across the internet to invoke services from Google servers.
– In manifest file add following line outside the application

<uses-permission android:name=”android.permission.INTERNET” />

2. To use google maps APIs services, you must agree Google Terms and condition, the terms will be presented to you when you sign up for a Map API Key.

Steps:
1. First Obtain a Maps API key from Google
– Find where your keychain is
* Go to Eclipse -> Preference -> Android -> Build
* see Defalt debug keystone – Here you see the keystore path
e.g: /Users/tech/.android/debug.keystore
* Go to the keystore location
* now run below command
$ keytool -list -keystore debug.keystore

* Now, paste your certificate’s MD5 fingerprint in the appropriate field on this Google site:
http://code.google.com/android/maps-api-signup.html

3. Add the following lines in manifest file within the application tag

<application>

<uses-library android:name=”com.google.android.maps”/>

</application>

4. extends MapActivity class

e.g

public class ActivityMap extends MapActivity

– MapActivity implements the following method.

@Override
protected boolean isRouteDisplayed() {
return false;
}

5. Understanding MapView and MapActivity
* Mapping technology in Android relies on the MapView UI control and an extension of android.app.Activity called MapActivity.
* The MapView and MapActivity classes take care of the heavy lifting when it comes to displaying and manipulation a map in Android.
* MapView need to instantiate it within a MapActivity, when instantiation a MapView, we need to supply the Maps API key
E.g:
If we instantiate a MapView using an XML layout, we need to set the android:apiKey property

<?xml version=”1.0″ encoding=”utf-8″?>

<com.google.android.maps.MapView

xmlns:android=”http://schemas.android.com/apk/res/android&#8221;

android:id=”@+id/mapview”

android:layout_width=”fill_parent”

android:layout_height=”fill_parent”

android:clickable=”true”

android:apiKey=”Your Map Key”

/>

Android – Location Manger

The LocationManager Service is offered by the android.location package. There are three types of location providers:
1. GPS
2. Network – Use cell-phone towers or Wi-Fi networks
3. The Passive provider and it is like a location update sniffer

Here is the example:

public class MyApplication extends Application implements LocationListener {

private static MyApplication instance;

public void onCreate() {
  super.onCreate();
  instance = this;
  LocationManager locMgr = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
  locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, this);

}

public static Context getContext() {
  return instance;
}

public void onLocationChanged(Location location) {
   Log.i("Debug"," OnLocation Changed"+ location.getLatitude() + " " + location.getLongitude());

}

public void onProviderDisabled(String provider) {

}

public void onProviderEnabled(String provider) {

}

public void onStatusChanged(String provider, int status, Bundle extras) {

}