11/21/2013

Cloud OCR Project: Learn to Develop for Windows Azure Today

A few months ago, we conducted a Cloud Development training course for our engineers. The attendees learned the main concepts of Cloud Computing, found out about the capabilities of the most popular cloud providers on the market, and learned the key design decisions for building highly available, scalable and fault-tolerant distributed systems in the cloud.

We concluded the course with a simple hands-on project: a Windows Azure cloud service that performs OCR (Optical Character Recognition) on images uploaded by users on a Web interface. The service works in a distributed manner, leveraging a fleet of Web and Worker roles that communicate asynchronously using queues:


The reference implementation is available on GitHub under Apache License 2.0. It uses Windows Azure Storage Tables, Blobs and Queues for data persistence and communication, Tesseract for OCR, and ASP.NET MVC 4 and Twitter Boostrap for the Web application. If you always wanted to learn the basics of implementing Web and Worker Roles for Windows Azure and using cloud storage services, this would be a great project to start. It does not involve a lot of abstraction and advanced features, so it will keep you focused on the important parts.


You're welcome to fork this project and send us pull requests.
Have fun!

About the author: Yuriy Guts is an AWS Certified Solutions Architect with several years of experience with architecting cloud solutions for various companies across the globe. He is responsible for the cloud solutions stream at ELEKS R&D and specializes in AWS and Windows Azure.

11/13/2013

js2js: why so serious?

JavaScript is the Assembly of the Web. There are dozens of tools that compile some programming language to JavaScript. You can do it with C++, Java, C#, Python, Ruby or plenty of other languages. It seems that there's one language that remains to be covered for JavaScript to dominate the world: JavaScript itself.

Last week we were joking about this and decided to fix this situation. Meet js2js, a revolutionary open-source compiler that transforms JavaScript directly to JavaScript! Have fun!

11/12/2013

Google Glass: Consumer Device in Enterprise World

You've heard of Google Glass, you have the basic idea of what it does, but you're not sure how it touches you. Right? Then we have something to talk about.
In this article I'm going to shed some light on what it is(and what it's not), how it fits into the enterprise(and how it doesn't), and finally - how can you benefit from it and what will stop you from doing it. You'll also find lots of examples down the road. So, let's start!

Englishman in New York Google Glass in Enterprise

What it is
Well actually it is anything but glasses - it's just a computer with camera, attached to your head:) But let's go step by step.
First of all, we have Android on board, i.e. a POSIX-compatible operating system, which means we could do almost anything we’ve done on mobile phones or desktop computers. The issue is that, as of now, the only official way to build apps for Glass is limited to showing pictures and text. But, unofficially Google lets us use all the features, and as the community is demanding, it seems like a matter of time when it will be official.
Second, we have a smart screen. Why is it smart? Because it’s there when you need it, and gone when you don’t. At least they say so:). The screen turns on on notifications, which you are subscribed to, and manually, by nodding your head lightly. And actually it’s not a screen, it’s projection into infinity. When I tried Glass it took me 5-10 minutes to get used to this.
Then, we have a voice control! That means that we don’t actually need to press any buttons and can keep our hands free. That’s a huge feature. Of course, there’s still a touch pad to cover cases when you want to remain silent. And speaking of sound…they’ve been experimenting with it. Let’s just say that Google Glass can produce sound.
Next, we have a camera, comfortably sitting on your head and seeing everything you see. Most of glass explorers say it’s a killer feature, actually the one that makes glass worth buying. Sharing video while doing your job, gives us a whole new set of opportunities.
And last is the connectivity module. We have Wi-Fi to be self-sufficient, but mostly Glass pairs with mobile phone via Bluetooth and gives us 3G or LTE network together with GPS tracking.
I didn't mention some minor Glass' parts, but you can have a look here for more details.

What it's not
There have been a lot of myths going through the Internet about Google Glass, and I’d like to bust some of them. So, what Google Glass doesn’t do?

First of all it doesn’t do augmented reality. You don’t see the world through the Glass, you see Glass’ screen on top right corner of your view field. So it just doesn’t fit.
Second, you can’t use the camera “secretly”. Google has foreseen this threat and made a design decision to avoid such cases. So, to take a picture we’ll have to say “OK Glass, take a picture” or lift our hand towards our head and press the touch pad. Same goes for video, but while recording, the screen is on, so people will notice you filming them.
Similar situation with face recognition. Google has cut out all standard libraries for face recognition, and also doesn’t allow such applications into their official "store". It is technically possible to implement it but is probably illegal. Yet.
And again the screen. I’ve heard lots of complains that a constant screen in one’s view field will drive people crazy. As I said, the screen is off most of the time and turns on when you need it. Period

Enterprise
Now we're getting to an interesting part. How can we apply it to the enterprise. I'll start from the examples.

Healthcare
Recently Philips together with Accenture have published results of their experiment with Google Glass, which was focused on healthcare. Functionality varied from integrating with Medical Records System, helping managing patients, showing vital signs during the operation and much more.

Warehousing
Another giant, SAP, together with Vuzix have produced their own glasses, specialized for this type of workers. As their demo shows, warehouses workers use optimized path finding, identifying needed palette, scanning barcodes, fixing technical issues by connecting to remote technician and streaming their video.


Maintenance/Tech support
Speaking of tech support, the whole procedure could be simplified, by providing busy technicians with this smart assistant. They could contact their peers and share their screen, look up repair history or take a quick look into the instruction guide while working, and all hands-free!
What's even more important, is that engineers, who use handheld devices at work are actually distracted by them. Moving this device to the default view field would make it more safe.

When is it worth it?
So, following these examples, how do we know when it’s actually worth considering investments into wearables?
Let’s take a look at typical enterprise mobility model. We have field workers, and we equip them with mobile devices, mobile applications and access to corporate network. In return we strongly increase their productivity and improve the business process. Now, there’s this type of workers, whose job requires intensive hand usage. If we equip them with wearable, i.e. hands-free devices, we would not just optimize their work flow, we would also increase their safety. So the key driver to adopting Google Glass-like devices in enterprise is the presence of hands-intensive workers, which would benefit from assistance.

But that’s just the tip of the iceberg. Why limit ourselves with B2E apps? It’s actually more probable that wearables will come into the enterprise from customer side, as it’s a consumer device. A very bright example is banking.

Banking
Most of us already know how important mobile banking is for the customers, and Google Glass could take it to another level. My favorite Google Glass ad is from one of the leading Ukrainian banks PrivatBank, where they show how Glass can simplify our lives. It includes buying things by just taking a look at them, loading car with fuel without even leaving it, finding the ATMs and withdrawing money without the card, and much much more. 

Learning
This is an area where glass explorers have already done a lot. I'll give 2 bright examples
1. A doctor making a knee operation while video-streaming his actions to the students.
2. A physicist having a lesson with his class, while cycling around Hadron Collider
There's also a nice article focused on Google Glass' role in education.

Sports
This is an area where we at ELEKS decided to experiment, as one of the most fruitful sources for integrating wearables into the process and thus expanding interaction scenarios. We've shown how race sports can be changed by equipping participants with live map and leader board, or how group sports can be changed by equipping players with live radar and possibility to see what teammates' see and much more. You can see the interactive video at glass.eleks.com.

Advertising

And what about e-commerce? Retail? Advertising? Public services? At this point wearables come into a perfect combination with contextual awareness. Imagine coming into the airport and automatically receiving notification about your registration desk number, departure gate and flight status. I recommend watching the presentation on NoUI concept and wearables for a bigger picture.

When is it worth it?#2
So Glass can be a very good way to reach your audience. And think of it - these people have consciously put a computer on their head and encouraged you to interact with them in such way. So its probably not a mainstream part of your audience.

Challenges
But let’s step away from the perfect world and face the reality. There is couple of major issues with implementing wearables in the enterprise.

Battery
Seriously, Google glass can take 40 minutes watching youtube, 4 hours standard mode(I didn't expect more from Android:)). There is a great struggle between producing more powerful batteries and wearing them on your head. So good luck here.

Security
We are still in the process of handling current security issues, and bringing this new type of device would cause tones of new concerns. Yes, Google Glass has a good theft protection, but authentication needs to be improved. Also, I imagine, coming to a secure workplace with a camera on your head may be an issue.

User Experience
As I said, screen is smaller, and obviously the interaction is different, so we again need to adapt application logic to it. There are special UX guidelines for building apps for Glass. So we can’t, or at least shouldn’t simply port mobile apps to Glass, just like we shouldn’t port desktop websites to mobile phones. They need to be reconsidered and rebuilt with new usage context in mind.

Priority
I believe most of you have more important problems to solve right now, like BYOD, mobile strategy, teaching your enterprise engineers mobile development, learning about your employees’ workflows and habits, choosing between cross-platform tools or struggling to find a reliable third-party vendor to do this for you... I do not think that focusing main efforts on Glass implementation while having that much on your shoulders is the right thing to do. 

Mass Adoption
Currently there is 10 000 Google Glass items on planet. Comparing to several billions mobile devices. For now, Google Glass is kind of a futuristic device, something cool, unexplored and compelling. But people haven’t got used to it like they did with mobile phones. So adopting it now will take time, efforts and probably training.

And let me guess what you're thinking about right now - "last time we saw mass adoption in mobility, we ended up with BYOD!". So I feel a need to at least touch BYOW

Bring Your Own Wearable?

Obviously Google Glass is not the only "Glass". There is a whole set of other wearable devices: GlassUp, Telepathy, ReconJet, Meta SpaceGlasses and many others. So one could wonder whether BYOD will repeat again.
It’s not clear whether wearables have same future. As technology grows, we see a certain resistance from people to accept them as they become too smart. For example - are you OK with what Google Now does? I sometimes feel uncomfortable, lots of my friends turend it off. Let’s take a look at the numbers. In a recent survey 18% said they’d buy the device. 20% of people agreed that Glass should be banned. More than a half had privacy concerns.  And 69% demanded greater regulation of people wearing the devices in public places. So it remains a great question, whether this new kind of interaction will go massive.
But we have to admit it - Google Glass is the first and probably the only wearable device with potential for mass adoption. Google made a really good marketing job here, which I personally admire.
For more information you can also read this article by Forbes on BYOD and Glass.

What can I do now?
First of all, we have a lot of more important problems and brighter opportunities with mobile devices right now. And I don’t recommend focusing on Google Glass before having more or less stable mobile strategy.
But if you do, you have a whole new set of opportunities! Now, whenever you detect hands intensive job, you know that you can improve it by introducing wearables.
Also, if you’re looking for new ways to reach your customers, Google Glass may just be it – the most effective way to please your most modern target audience.
And although Google Glass is not in public sale yet, you can choose other wearables, or you start building apps for it today, without the device itself.

So, let me finish my saying this - implementing mobility into known business processes and changing them is inspiring. But introducing things like Google Glass, applying them  to the areas where they actually bring value, and being among the first people who've done it - that's just awesome! So let's do it, and let's do it together!

p.s. I've been lucky to get involved in introducing Glass into one of the complex business processes. So in near future you'll see a big success or failure story.

11/06/2013

AWS: 10 Things You're Probably Doing Wrong as an Architect

Amazon Web Services is a powerful and mature cloud platform that keeps growing rapidly. Quite often, new features are added in such pace that many developers and architects barely have a chance to experiment with all of them on real projects. However, as with any cloud platform, the god is in the details. If you want to make the most out of your cloud services, you must know how to use them wisely, and, more important, how NOT to use them.
Based on what I've seen in my experience of training, consulting, designing and implementing cloud solutions, I've compiled a list of common 'gotchas' that might help you avoid many pitfalls on your own projects.
Update: Shortly after writing this blog post, I was excited to discover a very recent HighScalability article by Chris Fregly, a former Netflix Streaming Platform Engineer, which describes similar interesting facts you might encounter with AWS. Make sure to check it out as well!

1. Assuming the identity of Availability Zones across different AWS accounts. 

When you launch AWS resources in a specific AZ, you refer to this AZ by name, such as us-east-1a or us-east-1b. However, these names are purely virtual: when you create a new AWS account and use the us-east region (which has 5 different AZs at the time of this writing), AWS randomly selects 3 physical AZs in this region and assigns the letters a, b, and c to them. The primary purpose of such design decision is to balance the load across multiple AZs in the same region. Otherwise, the users would be more likely to select the first option, us-east-1a, causing an uneven load distribution across the AWS insfrastructure. As a result, us-east-1a in one AWS account is probably a completely different AZ than us-east-1a in another account.

2. Referring to Elastic Load Balancers (ELB) using IP addresses.

The golden rule of designing highly available and fault tolerant systems in the cloud is: do not assume fixed location, health or availability of individual components. The same applies to ELBs: as they scale to accommodate the traffic of your application, AWS may need to relocate or replace them, causing the IP address to change. Therefore, when dealing with ELBs, always refer to them by their DNS names. If you use a custom public domain for your application, create a CNAME record pointing to the DNS of the ELB.
If you use Route 53, there is a special kind of A record available for you: the Alias record. In this case, you can create an A record for your domain that points to the name of the ELB instead of its IP address. In this case, AWS would perform a double DNS resolution behind the scenes and substitute the alias with the particular IP address of the ELB.

3. Performing load testing without pre-warming the ELB.

Behind the scenes, ELB is a load balancing software, which is most likely installed on the instances similar to EC2. And, as any other instance in your infrastructure, it takes time to scale it up and down to accommodate the changes to the traffic. Therefore, if you plan to perform load testing on your application, or if you expect sudden significant load spikes, you should contact AWS support to "pre-warm" your ELBs ahead of time.
Update: Chris Fregly describes the DNS side of this phenomenon in his recent post on HighScalability.

4. Hard-coding the API keys inside AMIs or instances.

When you deploy computations on the EC2 instances, at some point they will inevitably need to use other AWS services (S3, SQS, DynamoDB, CloudWatch, you name it). In order to authenticate on these services, you'll need an IAM key pair: an Access Key ID and a Secret Key. Naturally, the problem is: how does an EC2 instance acquire these keys? An obvious (but a very suboptimal) solution would be to store the keys in a configuration file somewhere in the storage volume. It would work, but you'd have a lot of trouble with securing and rotating these keys.
So there's a better way: use the EC2 Metadata Service. Using this HTTP-based service, you can query many interesting details from within the instance: its public and private IP, name of its security group(s), region and availability zone, etc. The same applies to API keys: if you assign an IAM role to your EC2 instance, you can get the API credentials in your bootstrap script using a simple query:

$ curl http://169.254.169.254/iam/security-credentials/role-name

Note that 169.254.169.254 is the metadata service address that is the same for all EC2 instances.

5. Launching EC2 instances outside VPCs.

According to the release notes, new AWS accounts are now VPC-enabled by default, which means that every EC2 instance should be associated with a particular VPC at launch time. While VPC is one of the more complicated AWS features, launching EC2 instances inside VPC provides numerous benefits, particularly:
  • You can assign persistent static IP addresses that 'survive' stop and reboot operations. You can also assign multiple IPs and network interfaces to a single instance.
  • You get a more fine-grained control over the security configuration. In VPC, the security groups involve both egress and ingress filtering, compared to classic security groups where you can only configure ingress filtering.
  • You can run your instance on a single-tenant hardware.
  • You can launch resources in private subnets, which is particularly useful for database servers and  private ELBs.
So, if you're designing a new solution on an old AWS account, consider using VPC for all your instances. Probably the only case when you wouldn't want to do so is when you have a large legacy system built on top of EC2-Classic instances that would involve a lot of migration effort.

6. Performing port scanning or penetration testing without being authorized.

Doing such things is a violation of AWS Terms of Service. If you need to test your cloud applications for vulnerabilities, you should contact AWS support beforehand so that they would temporarily disable their intrusion detection systems for certain machines and services.

7. Using S3 ACL for managing access to S3 buckets.

Amazon S3 is one of the oldest AWS services. When it appeared on the market, there was no IAM yet. As a result, to manage access to S3 buckets, S3 implemented its own security mechanism, known as S3 ACLs. Nowadays, the preferred way of managing access to S3 is using IAM policies. Not only do they offer a more fine-grained control over access to S3 operations, but they also provide a unified way of managing access to other AWS services.

8. Involving your application servers for transferring data from browser to S3.

S3 supports direct browser-to-bucket uploads. All you need to do is generate a couple of hidden fields in the HTML to authenticate the client properly. If you define your form as <form enctype=“multipart/form-data">, the browser would even perform a multipart upload for large files.
Also, if you develop mobile applications that upload data to S3, you can use the AWS Security Token Service (STS) to generate temporary access keys for S3 and upload the data directly to buckets without proxying it through your servers.

9. Waiting for the EBS snapshot operation to complete before unfreezing the filesystem.

If you need to perform hot backups of your production environment, you must ensure that the backup captures the filesystem in a consistent state. To do this, you should freeze the filesystem (e.g., xfs_freeze) and then issue the snapshot creation command. However, you don't need to wait for the entire copying operation to finish before unfreezing the FS. Since the backup operation "captures a point in time", it only takes a matter of seconds for EBS services to capture the blocks that need to be persisted. Therefore, the right way would be to freeze the FS, issue the snapshot command, and then unfreeze the FS and expect the copy operation to be completed asynchronously. This helps you to ensure the minimum downtime of your environment.

10. Using On-Demand EC2 instances for every case.

An important aspect of designing solutions for the cloud is not only availability, scalability, security and fault-tolerance, but also cost-effectiveness. AWS provides you with a variety of cost-saving options under particular use cases. For example, if you expect to use a fixed amount of EC2 instances for a long period of time, consider using Reserved Instances. If you need a fleet of short-lived instances, outages of which can be tolerated, consider using Spot Instances (check out the blog post on Spot Instances by our engineer, Taras Kushnir). Choosing the right type of instance can make a dramatic improvement to the TCO of your infrastructure and you get a much bigger bang for your buck.

About the author: Yuriy Guts is an AWS Certified Solutions Architect with several years of experience with architecting cloud solutions for various companies across the globe. He is responsible for the cloud solutions stream at ELEKS R&D and specializes in AWS and Windows Azure.

11/04/2013

Getting more from the AWS: the spot instances (via SDK for .NET)

Intro

We have discussed basic principles of work with On-Demand instances of AWS web-services in the previous post. On-Demand instances are quite straightforward and have expected behaviour. But... what about something more stochastic and thus more interesting?

Amazon EC2 instance types

Amazon offers us several types of it's compute instances: on-demand, reserved and spot instances. One can read an article on the AWS website but to make long story short there are several types of instances:
  • On-Demand instances are fixed hourly rate mostly always available instances which are often used for applications which need some basic guarantees about start time of the instance
  • Reserved instances are instances, which we can (as it comes from their name) reserve for some period of time and they will be always available within this reserved time period
  • Spot instances are the most interesting kind of instances, because we act like auction player and set a price which we are willing to pay to run such an instance and if our bid beats other customers at the moment we are able to launch requested instances for some time period. If current spot price moves higher than our's, Amazon EC2 service shuts down our instance
More about Spot instances

Spot instances are kind of tricky instances which are not guaranteed to run when we request them. We have to place a bid and wait until it wins (if it will someday) in order to run a spot instance. To do this we can send spot instance request with our suggested price to Amazon EC2 service. Each request has a state which indicates if our bid won. Initially request has state "open". Our request’s state becomes "active" in case our bid won and we can see new running instances which are connected to our request with SpotInstanceRequestId property.

Describing spot requests

A DescribeSpotInstanceRequestsRequest is used to describe our spot requests state. We can query opened and active spot requests using filter property. For example, that is how one can query opened spot requests:

var describeSpotRequestsRequest = new DescribeSpotInstanceRequestsRequest();

describeSpotRequestsRequest.Filter.Add(new Filter(){Name="state", Value="open"});

var openedSpotInstanceRequests = ec2Client.DescribeInstances(describeSpotRequestsRequest);
var openedRequests =
openedSpotInstanceRequests.SpotInstanceRequest;


Running spot instances

To launch Spot instances we have to send RequestSpotInstances request and pass our price, maximum desirable spot instances number and usual launch parameters like image Id,  instance type, key pair name, security groups etc. If our price wins AWS will try to launch as many instances as it can limited by our desired maximum number.

var ec2Client = new AmazonEC2Client(accessKey, secretKey);
var spotRequest = new RequestSpotInstancesRequest();

spotRequest.SpotPrice = "2.0";
spotRequest.InstanceCount = maxInstancesCount;
spotRequest.LaunchSpecification = new LaunchSpecification() {ImageID = imageID};

var spotResponse = ec2Client.RequestSpotInstances(spotRequest);
var spotResult = spotResponse.RequestSpotInstancesResult;
var placedSpotRequests = spotResult.SpotInstanceRequest.Select(rq => rq.SpotInstanceRequestId);

Spot request can throw several exceptions, one of which is AmazonEC2Exception with ErrorCode “MaxSpotInstanceCountExceeded”. This exception means we requested more instances than our account allows us to launch.

Requesting spot instances can fail even not for our fault, but because Amazon is not able to provide us with such number of EC2 instances in our region at the moment. A “InsufficientInstanceCapacity” error code is thrown with AmazonEC2Exception in this case.

Requesting current spot price

It is useful to know the current price of spot instances when placing your own bid. AWS SDK has DescribeSpotPriceHistoryRequest for this purposes.

var ec2Client = new AmazonEC2Client(accessKey, secretKey);

var spotPriceHistoryRequest = new DescribeSpotPriceHistoryRequest();
spotPriceHistoryRequest.StartTime = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss.000Z");
spotPriceHistoryRequest.EndTime = spotPriceHistoryRequest.StartTime;

var spotPriceHistoryResponse = ec2Client.DescribeSpotPriceHistory(spotPriceHistoryRequest);
var priceHistory = spotPriceHistoryResponse.DescribeSpotPriceHistoryResult.SpotPriceHistory;

var currentPrice = priceHistory.First().SpotPrice;


A note: as it is said in the official documentation: “You can view the Spot Price history over a period from one to 90 days based on the instance type, the operating system you want the instance to run on, the time period, and the Availability Zone in which it will be launched.”

Tagging spot instances

There is a problem with tagging of spot instances: we cannot tag them just after start, because we don’t know when they will start. But there is a simple workaround: when we place spot requests, we can tag them and when actual spot instances would be launched, we can match each running instance spot request id and get corresponding tags.

Stopping spot instances

To stop Spot instances we have to work with SpotInstanceRequest but not with the running spot instance itself just like when launching spot instances. CancelSpotInstanceRequestsRequest does the job with SpotInstanceRequest Id’s to stop in parameters.

var ec2Client = new AmazonEC2Client(accessKey, secretKey);

var cancelSpotRequestsRequest = new CancelSpotInstanceRequestsRequest();
cancelSpotRequestsRequest.SpotInstanceRequestId.Add(spotRequestId);

var cancelSpotInstancesResponse = ec2Client.CancelSpotInstanceRequests(cancelSpotRequestsRequest);
var cancelledSpotRequests = cancelSpotInstancesResponse.CancelSpotInstanceRequestsResult.CancelledSpotInstanceRequest.Select(csr => csr.SpotInstanceRequestId);


After the spot request is cancelled AWS shuts down corresponding Spot instance.

Conclusion

Spot instances service from Amazon is interesting, tricky yet powerful. It allows using Amazon unused capacities at a lower price. You can purchase these instances by placing a bid, which you are willing to pay for those instances and for the time your bid is highest, you get them. Spot instances are useful in a number of situations when losing partial work is acceptable like cost-driven workloads or application testing. They help you to save your money when used wisely.

11/01/2013

Google Glass Development without Glass



Here are the slides of my "Google Glass Development without Glass" presentation. As I promised, here is the follow-up blogpost with some code samples. If you haven't seen my presentation, I strongly suggest clicking through the slides!

0.Intro

Technologies emerge. Extremely. Wearable trend takes over the world. It seems like every week we start with articles about brand new devices, which would change our life! We've heard about lots of glasses, watches, wristbands, you name it. The most popular one is definitely Google Glass. Actually, it is Glass, who started this wearable hype!
You can just imagine, how all the wearbles can impact our daily and extreme activities. Check out, how we imagined that at eleks: https://glass.eleks.com/

From the other point of view, each new device brings new UX, SDKs and APIs. That's why we, developers, have to quickly adopt to the new techs. In this sense, Google Glass is a rather good device for developers. It runs the world-known Android OS. It just has an extremely strange UI and UX.

Google created a set of "best practices" of awesome Glassware. Actually, it can be applied to any wearble software:
  • Design for device -- know & test your device and it's abilities. 
  • Don't get in the way -- show the best data when users want it and be out of the way when they don't.
  • Keep it timely -- platform is the most effective when in-the-moment and up-to-date.
  • Avoid the unexpected -- surprising users with unexpected functionality is bad. On any platform.
Glass is different from the regular phone or tablet. The usual way of creating Android apps is through the Android SDK. Because of specific Glass's usage principles, Google introduced Mirror API. We'll dive into both of them later in the post.

1. Obtaining Glass

If you are among those 10000 people, who have Glass, you can skip this chapter. Unfortunately, that's just 0.000002% of the world's population. So, welcome Stranger to this amazing world of Glass hacking without Glass.



Hopefully, you have some Android device. Then, you can install Google Glass UI there (disclaimer: I've tried this with Nexus 7 tablet with 4.2.2 rom and it worked perfectly, but I can't guarantee it will work on other device). In short, Google Glass UI is just another Home screen provider for your Android. In order to set it up, follow these steps:
  1. Go to: https://github.com/zhuowei/Xenologer
  2. Download Glass APKs: https://github.com/zhuowei/Xenologer#install
  3. Install them as you usually install APKs from third-parties
  4. Follow steps at http://imgur.com/a/IBqFf to set up your "Nexus Glass"
  5. Say "ok glass, take a picture" and share your "woohoo-reaction" with the world #throughglass
You've obtained Glass. Now its time to hack!
Let's dive into Glass development with the help of our friend Mr. Bond. James Bond.
Once upon a time, he was in London. Somehow, he's got his Google Glass and enjoys the experience on a daily basis.

2. Example #1: Mirror API

If you are eager to try Mirror API out and don't want to mess with quick-start projects, I have a shortcut for you!
Let's try inserting a simple card into Glass Timeline:
  1. Go to: Google API Explorer --> Mirror API --> mirror.timeline.insert 
  2. Authorise via OAuth 2.0. Use Glass scopes:
    • https://www.googleapis.com/auth/glass.timeline
    • https://www.googleapis.com/auth/glass.location
  3. Populate request fields with values from the API.
  4. Execute request!
  5. Here's a link with some pre-populated data.
Now it's time to have even more fun! Let's try setting up demo-project.
  1. Set up a new project in https://code.google.com/apis/console
  2. Go to API Access, update project settings:
    1. Add to Redirect URIs: 
      • http://localhost:8080/oauth2callback
    2. Add to JavaScript origins: 
      • https://plusone.google.com
      • http://localhost:8080
      • https://mirror-api-playground.appspot.com (will be useful later) 
  3. Clone https://github.com/googleglass/mirror-quickstart-java
  4. Update file src/main/resources/oauth.properties with the values provided in Google API Access Console.
  5. mvn jetty:run it.
If everything goes smooth, you'll be able to authorize and have fun with your Glass Timeline! If you want to have even more fun with Mirror API, especially with Subscriptions to Location and Notifications, you should deploy your war to the real webserver. Google sends these updates only to https secured web-sites. For development purposes you can use provided ssl-proxy. Just modify MirrorClient#insertSubscription method.

3. Example #2: GDK

Update: Google recently released GDK Sneak Peak. Right now, when you try creating apps with it and running it on Nexus Glass, you'll get [INSTALL_FAILED_MISSING_SHARED_LIBRARY]. We're trying to find the way, to avoid that. As of now, there's no support for the official GDK Sneak Peak (auth, live cards, etc).


Google Glass is just another Android device with 640x360 screen (hello, screen fragmentation), Android 4.0.4, API level 15. Maybe, in the next releases of Glass, this will change. Now, when you want to port your existing Android app to Google Glass, you should just:
  1. Build your APK.
  2. Install it.
  3. Run via adb.
  4. Understand, that you need to update touch gestures support.
  5. Understand, that your UI is hardly usable.
  6. Understand, that your awesome Google Maps stopped working.
  7. So, double-check your application on real device! Everything can change in the near future!
It's a good idea to check out Google Glass Quick Start by Google. It explains a lot about Timeline, UI, Gestures and current limitations of the GDK.
In order to support touch gestures of Google Glass, have a look at this article: Touch Gestures. In short, here's the table with events corresponding to keycodes:
TapKEYCODE_DPAD_CENTER
Swipe rightKEYCODE_TAB
Swipe leftKEYCODE_TAB + isShiftPressed()
Swipe downKEYCODE_BACK
CameraKEYCODE_CAMERA

4. Example #3: GDK + Timeline API

Update: Google released GDKvXE12 update. It has Static Card support, but it is still limited and lacks menus, html templates, etc. The code mentioned below follows hacky way and may not work on the latest version of Glass.
So far, we've tried the official Mirror API way and the hacky GDK road. Now its time to combine both approaches. Let's insert a card into Timeline from withing your app!

I've  set up a sample project at github for you: https://github.com/pif/ukrbash-for-glass. After you fork/clone it, you can see glasslib.jar inside libs folder. This library would probably become the aforementioned GDK. It provides everything you need to know about Timeline UI.

All the magic is done via these steps:
  1. Initialise Timeline, get Timeline contentresolver. Look at:
    com.andrusiv.glass.bash.GlassService#onStartCommand(Intent, int, int).
  2. Create MenuItems for your card.
  3. Create TimelineItem.
  4. Insert it into ContentResolver.
Look through the classes & methods provided inside glasslib.jar. I hope, you'll find loads of interesting information!

5. Outro

Thanks everyone, for reading all the way down here. I hope now you have your pseudo-Glass and know how to develop for it. Share your experience in the comments and on github! Ok guys, have fun #throughglass!