Notes On How To Hack A Web Application

hacker

Overall
– Understand Software Security (sec = short form)
– Understand security features in web browsers
– List common attacks
– For each attack, understand the attack, it’s technique and how to mitigate

[Part 1 Intro to Soft Sec.]

– More code increases chance of bugs
– Threats can come from inside or outside the company

Problems
– Security and privacy expectations are implicit
– Software Security is a relatively young field
– Software failure is a real and pervasive problem
– We need to build software that is secure and can be secured
– The problem with penetration testing is that it does not provide a solution to the problems it discovers

Two Broad Classes of Security Defects

– Bugs happen in Implementation
– Flaws happen at Architecture Design
– Bugs/Flaws in software is 50/50

– Bugs fixed in code
– Flaws fixed in Architecture Risk Analysis
– Defect is both implementation and design vulnerability

Trinity of Trouble
– Connectivity: Everything is connected to the internet
– Complexity: Simple UX ironically leads to more complicated code
– Extensibility: Software must be flexible enough to work with code that hasn’t been made yet. Client-server model is the simplest attack pattern to exploit. As a server-side developer, you must ensure the system can defend itself against misbehaving clients.

Impacts of Software Failure
– Financial loss
– Data loss
– Performance loss
– Brand rep loss
– Customer trust loss
– Compliance failure

[Part 2 – The browser sec model]

Same origin policy: Prevent different domains from interacting with each other

Web Browsers and Web Applications
– Same origin policy: Permits scripts running on pages originated from the same site or origin; Client-side is responsible for enforcing strict separation
– Exclusions: HTML Img, Scripts, and Style sheets
– The browser security model prevents access of content from different origins
– DOM: Document Object Model: Used to represent HTML and XML
– Web browsers use DOM optionally but for JavaScript to execute, it is required
– Mashups: Getting data from multiple origins and having them interact with each other violates the Same Origin

[Part 3 – Attack & Defense Vulnerability Discovery, Prevention]

ATTACK #1: XSS – Cross Site Scripting

Bypass the Same Origin Policy. There are two types:

1) Persistent: Stored on the server-side, downloaded when client downloads compramised web page
2) Reflected: User input has the malicious script sent to the application, it’s executed on the server, the results are sent back to the browser

Examples of reflected:
– Cookie session hijack
– Re-writing HTML
– Impersonating requests as a legit user
– Faking a login/password screen
– Performing port scan on LAN

– Because the script comes from a trusted web server, it does not violate the Same Origin Policy
– Same origin policy limits HTML content but does not limit script blocks, images and CSS. It can load from another source but it limits what gets executed. This mean malicious scripts get downloaded at the same time the DOM is created.
– Man in the middle attack: Relay I/O the user sends and receives from a compromised site.

Protecting Against XSS
– Encode outputs: Select an encoding method that does not produce control sequences; HTML encoding for HTML output;
< is a “<" symbol; URL encoding for log files; This forces content to be treated like plain text instead of runnable code
- Constrain inputs: perform regEx and parsers to check syntax on the server side
- Safely store and process data using safe methods

Mitigation & Remediation
– Client-side validation can be easily by passed by an attacker
– Server-side must reject bad input rather than process it
– Java: Use jTidy as an encoding library

How to Test for XSS
– Check if input validation is being done on the server
– Check if output encoding is being done on the server
– Check if malicious XSS code is between HTML tags, inside HTML attributes, or in

<script/>

blocks
– XSS in HTML tag check: Embed JavaScript alerts (i.e. displaying your session ID) in your server-side code to check for vulnerabilities; if the alert is displayed properly, then you are not doing any output encoding. If it is done properly, the JS alert script will appear as plain text
– XSS in HTML attribute check: Check for presence of malicious code store in attributes/callbacks like onLoad,

onError, onMouseOver
– Rostering: Use a white list of acceptable location to reference remote resources i.e.

http://myWebsite.com/balloon.jpg vs http://atacker.com/ballon.jpg
– XSS in script tags: Ensure the content you have in the

<script/>

tags is the one you wrote

ATTACK #2: SQL Injection

1) SQL Concatenation: Ability to assemble to a dynamic SQL query with OR, SELECT, JOIN, UPDATE
2) Stored procedure w/ runtime variable: Inject un-intended parameters
3) Prepared Query object (name-value pairs) where the value references run-time server-variable i.e. currentDate()

– SQL Injections cause apps to return different data to the attacker than what should normally be returned
– Static Analysis tools: Scan code for SQL Queries that combine both user and hard coded defined input;
– General approach to discovering vulnerabilities is to add tautological parameter values and examine the results
– One example for a username and password would be ” and ‘1=1–‘
– Submit inputs via POST and GET, Cookie Values and Header Values

Check for input-based vulnerabilities:

– Integer:

http://foo.com/bar.jsp=?value=123*1

If this executes as 123, it is being interpreted as code instead of as an integer

– String:

http://foo.com/bar.jsp?value=A’+’BC

If this executes as ABC, it is being interpreted as code instead of as a string

– Errors:

http://foo.com/bar.jsp?value=123/0

If this throws an error, it’s because it’s being interpreted as code

Information leaking through back doors: Egress Connections; Timing Attacks

ATTACK #3: Header Manipulation

– Attackers modify the HTTP response coming from a trusted web app
– Attackers send HTTP request that forces server to send two HTTP responses; attackers control the 2nd response
– The headers in the response separate the original header using %0d%0a which is the URL-encoded equivalent of Carriage Return Line Feed characters

\r\n

and allow attackers to define a new http response containing a malicious payload. The client will make only one request but it will be sent two. The first one ends abruptly while the second one is malicious.
– Header manipulation is a great way to launch XSS.
– Solution #1: URL encode strings before they become a part of HTTP response headers
– Solution #2: Validate user input for

CRLF, \r\n, %0d%0a

, any other funny encoding

ATTACK #4: System Information Leak

– Attackers can learn about a system when it provides too much information or information that was unintended.
– Examples: Verbose error messages tip off what an attacker can and cannot do; Never display a stack trace to a user, although useless to a typical user, it would provide insight to an attacker (reverse engineering)

How to Test for information leaks:
– SQL/XPath injection; testing for valid username using the forgot password feature
– Data-type confusion: Pass an invalid date to get access to a stack trace
– XSS on the common error page

Solutions:
– try/catch blocks – handle the exceptions instead of display them
– redirect users to a relevant error page, i.e. NoSuchPage.html when a 404 happens

ATTACK #5: Path Manipulation/Directory Traversal

– Exposed File I/O operations allow for unauthorized CRUD calls on the system’s resources
– Example: http://foo.com/../../../../etc/passwd

String downloadFileName = request.getParameter(“filename”);
File file = new File(“c:\\tomcat\\webapps\\myapp\\imguploads\\” + downloadFileName;

On the user-interface, if we can specify the value of what would be downloadFileName variable, this would be allowed

“../../../../../../../../../../../boot.ini”

– Testing: Look for areas in the code that take in a string representing a file path; use “../../foo.txt” and add

“../” to go beyond the application directory

– Solution #1: RegEx only acceptable characters
– Solution #2: chroot directory permissions to define where can read and who can write

ATTACK #6: Cross-Site Request Forgery (CSRF)

Piggyback on victim’s sessionID so that an attacker can make legit requests on their behalf unbeknownst to them

– Exploit: Attackers create an

<img>, hidden <form>, <IFRAME>

or Javascript that calls actions in the background
– Example:

<img src="http://bank.com/transfer?to=attacker&amt=200"/>

Note how this is not a valid bitmap to display so nothing will show and it will work because it is being done on a valid user session.
– How to test: Use HTTP proxy software like Fiddler; inspect the request and response
– Prevention: Pair session ID’s with a security token; the unique random security token is store on the server and it’s store as a hidden parameter in the HTML form sent to the user

ATTACK #7: Hidden Field Manipulation

– Attackers change hidden or disabled form fields on a form
– Example #1: A disabled button is sent to the client; attackers enable the button locally and are able to click on the button thus executing the action
– Example #2: Instead of manipulating the HTML, they can just modify the request parameters to do what the button click would have done using tools like BurpProxy
– If attackers can manipulate the requests, they can control the application logic
– How to test #1: Use the same software proxy tools to intercept and change hidden field parameters on requests and observe the responses. If an exception is thrown
– How to test #1: Use browser tools like Firefox’s Web Developer plugin to enable form fields to see all hidden fields

– Solution #1: Input validation on the client side
– Solution #2: Resource permission check on the server-side to validate the current logged in user is allowed to access said resource

ATTACK #8: Cookie Security

Cookies are name-value stores to track userid, sessionid, and preferences; Attackers can then use this information to impersonate the user
– Attackers can transfer and view cookies using insecure protocols
– Attackers can access cookies if it is shared among multiple applications and the attacker is in control of one of those applications
– The longer a cookie persists, the longer an attacker has time to access it
– Allowing cookies to be accessed by JavaScript can be harmful if the JavaScript did not originate from the original application (i.e. XSS)
– Solution: Some browsers support HTTPOnly flag which prevent client-side JavaScript from reading it’s cookies
– How to test #1: 1) Go to the website you want to test 2) type

javascript:alert(document.cookie)

3) if you see an alert popup with name-value pairs, it means the HTTPOnly flag is not set
– How to test #2: Use HTTP proxy to see if the HTTP header cookie config like secure flag, domain, path and expiration
– How to test #3: Static analysis tools to search the code base for any areas where there is a Cookie object instantiated; there you can view what flags have been set
– Solution #1: Setting the secure flag on cookie so that it can only be sent over HTTPS
– Solution #2: Expire cookies to shortest time possible
– Solution #3: Set domain and path to be only used on your application; this prevents it from being shared with other apps thus reducing the attack surface
– Solution #4: Don’t use cross application cookies; less secure applications may have access to sensitive information stored on the shared cookie
– Solution #5: Set the HTTPOnly flag to true

ATTACK #9: Session and State Management

HTTP is stateless. Every request is discrete. The only way it knows any two requests are related is via a common sessionID. Application server software automates the creation of sessionID’s to be un-guessable, non-colliding, and exclusive for only session management (meaning don’t use this string for any other purpose).

Exploit #1: SessionID Theft can be done through XSS

– Malicious cross-site JavaScript can access the cookie i.e. alert(document.cookie); instead of displaying in a browser, the cookie information is relayed to a website under the control of the attacker. The attacker then sets their own browser’s request to the same sessionID and beings to impersonate the victim’s requests

Exploit #2: Man in the middle attack

– Attackers look at the un-encrypted network traffic and look for session Id’s in the HTTP requests

Exploit #3; Brute force prediction

– If the application is creating session Id’s based off a pattern (i.e. sequentially), it is easy for attackers to predict and create their own sessionID
– If the range of possible session Id’s is small, it can be predicted using basic math and script

Exploit #4: Session fixation; attackers define the SessionID and the server treats it as legit

– Attacker request from the application server an arbitrary sessionID
– Attacker then presents the victim with a web link to the application’s login page with the known sessionID
– Victim enters username and password with the known sessionID
– Application authenticates the user but does not overwrite the known sessionID with a new sessionID
– Attacker is now in possession of a sessionID that has been authenticated

Solution #1: Expire cookies which store session Id’s
Solution #2: On logout or on time out, application server must invalidate sessionID
Solution #3: Application server should ignore session Id’s stored in variables on GET and POST requests
Solution #4: Cookies should have random changing token
Solution #5: Encrypt network traffic using SSL/TLS to prevent man in the middle
Solution #6: Application logic should only associate users with session ID’s after authentication, not before
Solution #7: Session Id’s before authentication should be considered invalid by the application
Solution #8: When a session ID is created, it should be mapped to an IP address. May not work in environment with load balancers where IP addresses may not
Solution #9: For extra sensitive transactions (i.e $), have the user re-authenticate
Solution #10: Application server should only accept sessionID’s created by that application server
Solution #11: Regenerate a sesionID after login
Solution #12: On cookies that contain the sessionID, set the secure attribute making the SSL/TLS mandatory for transmission
Solution #13: Use large random IDs to make them less predictable
Solution #13: Reduce dependence on persistent cookies

ATTACK #10 Weak Access Controls

Attackers are able to perform operations outside of what a typical user is expected to perform.
– Horizontal access is when an attacker can see the data of others in the same role
– Vertical access is when an attacker is able to access behaviors and data outside of their role i.e. Employee role accessing administrator functions

How to test #1: Changing the query string (Horizontal access)

http://site.com/confirmation.jsp?refNo=123 is your own

http://site.com/confirmation.jsp?refNo=456 is someone else’s data

How to test #2: Changing the URL

http://site.com/adminConsole.jsp

How to test #3: Parameter Tampering – In REST operations, delete and update operations can put in a arbitrary record ID to artifacts they should not have access (Horizontal access)

Hot to test #4: Parameter Tampering – When they access an application as an admin (or monitor the transactions of admin), the request and response is recorded and studied. Then the attacker will attempt to perform the same actions as a lower privileged user.

Solution: Weak access controls are architectural flaws; Implement a white list of users (Entitlements) to dictate what data and behaviors a user can possess; Make the access permissions as close to the object as possible i.e. don’t make global entitlements.

Share

The Dilemna of Mobile Apps Development

Source – http://www.commitstrip.com/en/2014/08/18/the-dilemna-of-mobile-apps-development/

Share

Review – Google Cloud Platform Roadshow: Toronto Edition

[Update – Aug 15/14]: I may have misinterpret some parts of the presentation. Paul Newson took the time to help me make the corrections. Thanks man!

The Google Cloud Platform Roadshow landed in Toronto today at the head offices of Google Canada. It was a 4-hour high-level sales pitch of what is available in their current Cloud services offerings. It wasn’t a revisit to their DataStore or App Engine but their utility was mentioned quite often throughout the presentations. No one in the audience could doubt how impressive the technologies they have to offer at scale. However interesting questions from the audience did not hide the doubt could Google be trusted?

IMAG0095

The afternoon started off with Jeromy Carriere (@sjcarriere) telling a familiar tale where a large company (Google) has invested in so much infrastructure to the extent they can commercialize the technologies they’ve been using internally to support their own business. As prices for hardware go down over the years, Google has priced their services to transfer the savings to their Cloud customers.

IMAG0098

Mandy Waite (@tekgrrl) followed up with the first of her two presentations. In Blurring The IaaS/PasS Divide, she described the traditional model of how we’ve had to choose between one or the other and how it’s possible to have the best of both. AppEngine is a PaaS that saves web application developers a lot of headaches so that they may focus on the coding tasks. Compute Engine is an IaaS that allows you to manage many Virtual Machines that can come in a variety of Operating System flavors configured with whatever services running on them. She then did a pretty cool demo of a web app (App Engine) that asynchronously solved Sudoku puzzles when shown on a webcam. App Engine received the snapshot bitmap from the client, send it to the TaskQueue which then sends it to next available Computer Engine Managed VM. That VM is configured to run the OpenCV library which cannot be run within App Engine. OpenCV parses the displayed numbers and the empty cells. The result is then piped into an algorithm that will solve any Sudoku puzzle. The original image is then modified to have the empty cells populated with the computer generated solution. When that Task completes, the final solution image is sent back to the client via App Engine. A very cool demo of how App Engine can leverage libraries itself cannot run. Rather than have one VM process all requests, Compute Engine can be configured to scale up to as many services as needed by the demand. When the demand is gone, inactive instances can be shutdown.

sudoku

Next up was Paul Newson (https://plus.google.com/+PaulNewson) “From Data to Meaning”. He talked about how they’ve gone from MapReduce to Hadoop for processing large datasets in clusters. A common problem with large datasets we accumulate is that 1) The data is not where you want and 2) the data is not in the format you need it to be. He then provided a demonstration of how Hadoop can be the solution using the following “HDFS connectors”:

These connectors provide a way for Hadoop to talk to Google Cloud Storage, BigQuery, and Datastore as if it were talking to it’s native HDFS storage system.

A typical workflow would start off with your data in Cloud storage. Then the connectors would then transfer your data into Hadoop which will be distributed to many VM’s. Each VM would apply whatever operations on them. The results from each node get piped back to somewhere else in Cloud storage. Paul’s analogy was “Why use a wheelbarrow when you can use a big truck?” We’ve been doing ETL for years but what could take hours to process could be reduced to seconds through Hadoop instances. His second demo was equally as impressive as he took trillions 3 billion genomic records normalized by Hadoop and loaded all of into BigQuery. Then he was able to write SQL queries to derive insights in tens of seconds what could possibly take hours on a single machine.

Recommended video on the Evolution of MapReduce at Google and “Google Cloud Dataflow”

After a short break, the show continued with Paul Newson’s second presentation on “Containerizing the Cloud”. He described how Google has been able to perform reliable deployments to production with minimal disruption to end users. When you think about Search, Gmail, and Youtube, Google is multi-tenant and each of these services are made of different components that they themselves have been containerized. Each week, 2 billion containers are started to support these and many other services. This is not humanly possible to manage. A cluster scheduler is responsible for identifying the next available container to be initialized.

IMAG0100

Paul then talked about “Kubernetes” open source initiative which they use for cluster management written in Go. It’s a middleware that tracks which containers are communicating with other containers (i.e. Front Ends and Back Ends). Google uses Kubernates for staged rollouts some containers with old code can be brought offline while the containers with new code take its place. It’s not a good idea to bring down all instances all at once because once users start using the service when it’s back online, it will be difficult to rollback. Staged rollouts allows for production issues to make their appearance in an instance where their risk can be mitigated.

Related Video On Docker: Google I/O 2014 – Containerizing the Cloud with Docker on Google Cloud Platform

The final session of the day was done again by Mandy Waite in “How to Design, Build, and run a Cloud app”. She talked about a Google I/O app called WalkShare which collects GPS coordinates on your device, uploads them to an App Engine app which then will mashup with Google StreetView visualization of that GPS data. By sharing a walk with a user, they will see StreetView images of direction you were facing with each step you have previously taken. I dunno. Something makes me feel uneasy sharing my GPS position with strangers. Not only that but you can share the walk with complete strangers too so that they may be able to anonymously comment.

Mandy explained the architecture in high level detail. Google Cloud Datastore was used to store the GPS data. Google Cloud Endpoints where used to sync device GPS records to the data store. To allow for unauthenticated users to post comments on the walk, Capcha was implemented on Computer Engine Managed VM’s. The Captcha library cannot be run on App Engine because App Engine does not have the java.awt.* package that involves image processing (Great example of IaaS|PaaS hybrid). To demonstrate memcache on data that was not persisted, Compute Engine was used again to have managed VM’s run Redis. The key are the walks of users and the value was a set of GPS coordinates. It was a cool example that demonstrate most of the features of a typical web app but with the addition of a native mobile front end and showcased once again how Compute Engine can leverage 3rd party libraries that don’t run in App Engine.

Related Video On Walkshare: Google I/O 2014 – Zero to hero with Google Cloud Platform

The day concluded with “Networking reception with drinks and hors d’oeuvres”. Good thing they had food, beer and wine, I was starving. “Tall” Tom (The Roadshow’s MC), Jeromy, Mandy and Paul made up the Fireside chat panel. As the food was being laid out, all the deferred Q&A was unleashed towards the end. Some of the more controversial questions came up such as can we trust Google to store the private data of its users? It’s well known Google takes the data generated from it’s own users, analyzes it for patterns and takes action on those patterns to drive their main bread & butter which is advertising. Who is to say they will not take the data provided by their Cloud customers so that they may be able to take advantage of it? Tom and Paul re-iterated Google’s strict policies on the privacy of data and the extremes they go to protect it. There are number of protocols in place that range from the physical security of their secret data centers to the ethical governance on who can access and what kind of data can be accessed. Even though I am aware of these protocols, I still share the same fears as those in the audience.

IMAG0097

This didn’t come up but it reminded me of the story of the pedophile who was caught for having child porn in their Gmail. It’s a double-edge sword as probably the lives of one or more children were saved but then it demonstrates a means how privacy can be compromised. I digress. Paul did close out the privacy question by reminding us that the foundation of Google’s business is based on trust. Without it, they wouldn’t be there to sell Cloud services to us. He also reminded us there was a time where we were scared to buy things online. It took a while but eventually we started whipping out our credit cards to place online orders. The point was made that it’s a matter of time before companies can create a value proposition that alleviates and surpasses any fears consumers would have in using a public cloud service.

Some might argue that this time has been here for a while if you look at smaller younger companies. However if you look at larger companies that have a lot more to lose, many still have not made the transition into cloud because the risk of swapping technological pillars is so great. Jeromy’s keynote highlighted how competitive the Cloud business has become over the years. As prices for hardware continue to drop year after year, the price for cloud services drop but not as much. As a result, there is strong growth for large companies themselves to invest into their own private cloud infrastructure where they themselves can host multi-tenant their own services. While Google and other large tech companies continue to sway other large enterprises into using their services, some of the companies they target strive to keep their data and the insights it may yield in-house. At the end of the day, it will come down to money no matter how we developers code it. Cloud is a very exciting business to be in whether you are in the public or private.

Overall, I did enjoy spending my time at Google Canada HQ. The domain of problems that concerns me in the present and in the immediate future are of the native mobile sort. You cannot buy into a technology unless you know what it is capable of doing. The team did a great job in showing the audience how to leverage some of the technologies that have been a part of Google’s success. When the day comes I need to make decisions about making data available anywhere, anytime and to anybody, I’m glad I went to the session to become informed what choices are there available in scaling and distributed computing.

Minor improvements I may offer to future Roadshow event is to break the lull between 1-2pm with a Youtube playlist. I managed to kill the time with the free wi-fi which was great. The other improvement is to actually have a fireplace video running in loop during the “Fireside chat”. All in all, the team had the essentials covered. Great show guys and gal!

IMAG0104

One cannot go to Google Canada HQ and not take notice of the awesome amenities they have other than the prime downtown location. First of all the have a patio. Second the patio has mini golf course on it! Third is an on-site cafeteria where you never have to worry about food. Looks like a nice place to work at!

IMAG0101

IMAG0102

IMAG0103

Share

Navigation Drawer Checklist

When the Navigation Drawer is open,
1) the action bar changes it’s title with the App name
2) Remove any actions contextual to the screen behind it
3) Overflow menu will remain visible

Don’t place actions in the navigation drawer itself

If the user is in an Contextual Action Bar (i.e. Search, Copy & Paste, etc), replace the CAB with a standard action bar and the above rules apply

Upon first time installing the app, display the Navigation Drawer automatically. This will make the user aware of its existence

Disable automatically showing the Navigation Drawer, the first time the user opens it explicitly. This demonstrates the user understands how to open the drawer. Subsequent app launches will have the Navigation Drawer closed.

Navigation Drawer Styling – should be between 240-320dp in width, each row should be at least 48dp or more in height.

Create Navigation Drawer Icon – http://romannurik.github.io/AndroidAssetStudio/icons-nav-drawer-indicator.html

Source – “Navigation Drawer” @ https://developer.android.com/design/patterns/navigation-drawer.html

Share

Want to be a panelist @ #DevTO’s NCFOP?

splash-500

Who
Moderator
2-4 Senior Developers
Live audience of developers with varying experiences

When
Call for Panelists Deadline: Friday, July 18
Actual event: #DevTO Monday, September 29, 2014 @ 6:30pm

Where
Exact venue TBA in August 2014
Will be in Downtown Toronto or just outside it accessible via TTC

Panelists
2-4 senior programmers who continue to code/innovate in a relevant programming language today
Must have proven track record of re-inventing themselves as languages come and go
Currently in a position writing new code for an innovative role product and/or services in the past 12 months
Not in a support developer role performing routine maintenance and bug fixes
Each panelist will represent an industry sector they have experience in i.e. Medical, Finance, Marketing, Science, Enterprise, etc

What
Panelists will be interviewed in front of an audience asking questions like:
What goes through their mind when tackling a new language?
What are their reasons not to leave programming?
Why did they not leave for management or startup their own company?

They also be asked to answer tough questions:
Thoughts on job outsourcing to India, China, etc.
Losing their job, getting back on their feet
Does the industry make it hard for women or they getting a fair deal like anyone else?

Friday July 18th Friday July 25th is the Call For Panelists deadline. A shortlist will be created. Final panelist selection will be based on the balance between many years of experience and the relevance of the technology they are currently practicing (Sorry Microsoft Access Dev).

Why
Overall Goal/Takeaway: Inspire the younger generation of coders with knowledge from experienced folk so that they may have longevity and prosperity in the industry.

Share

Values for declare-styleable attr tags

Running through a tutorial for creating a custom views at http://developer.android.com/training/custom-views/create-view.htm, I was blocked by the lack of information what are the possible values for

<declare-styleable/>

Turns out as I learned from this helpful blog post at http://chaosinmotion.com/blog/?p=179, the possible follows are as follows:

  • reference
  • string
  • color
  • dimension
  • boolean
  • integer
  • float
  • fraction
  • enum
  • flag
Share

Eclipse SVN: Subclipse vs. Subversive

Where I work, we use both SVN and Git. I’ve dumped SourceTree for Eclipse Kepler’s integrated Git client which is actually pretty nice. For an integrated Subversive client, over the years I’ve jumped between Subclipse and Subversive. This here looks to be the Definitive Thread on which one to choose. For me, I’ve gone ahead with Subclipse with my current Eclipse Kepler install.

http://stackoverflow.com/questions/61320/svn-plugins-for-eclipse-subclipse-vs-subversive

Share

Easily Add Copyright Notice To *.java and *.xml Files In Your Projects

I’m still using Eclipse. Some habits are hard to get rid of. Finding gems like these make it harder. On the Eclipse Marketplace, there is a plugin called Copyright Wizard 1.4.0. Once installed, you can configure the templates in the Preferences as seen below:

copyright

Configuring the template is optional. When you’re ready to apply the copyright, right-click on the folder or java package, select the Apply copyright

copyright1

…Set your params and license…

copyright2

…right click and refresh your project and you will see the new copyright/license notice

copyright3

I experimented with another tool called Eclipse Releng Tools but I found it didn’t handle the XML use case I’ve documented above. This plugin is a pretty handy tool to have if you are a propitiatory developer or an open source one. Whatever tool you use, all that matters is you get it done.

Share

A Visual Guide To Embedding JSON Into Your Android Project

A colleague of mines shared his technique on creating hard-coded JSON strings to be embedded as a String in source code. This is helpful if you want to defer writing the HTTP request + response code or want to bypass existing steps like authentication.

The formatting is done using a web tool called http://www.freeformatter.com/. The first step is to take a well-formed JSON string from wherever:

[
    {
        "hello": "world"
    },
    {
        "foo": "bar"
    },
    {
        "apples": "oranges"
    }
]

If you copy and paste this into .java file, you will have issues. So using the webtool, you can prepare the above into something that will compile properly. On the website Free Formatter website click on the JSON Formatter:

freeFormatter_s1

Copy and paste the JSON into Option 1’s text input. Alternatively, you can enter the URL if the json is available online. Be sure to select the indentation to “Compact (1 line)”. This will ensure that it will strip carriage return characters.

freeFormatter_s2

Once you hit the FORMAT JSON button, you will see the compressed JSON but we’re not done yet. If you use this string as is in a .java file, you will have issues because the quotation marks need to be escaped. Next, hit the COPY TO CLIPBOARD button and go to “Java and .Net Escape” under String Escapers and Utilities

freeFormatter_s4

On the Java and .Net Escape tool then, hit the ESCAPE button.

freeFormatter_s5

Copy the resulting output and paste the prepared JSON string into your source code:

freeFormatter_s6

Once you’ve embedded the string into your java code, you can feed the JSON string into your favorite JSON parser implementation.

freeFormatter_s7

You could do this all without the aid of formatting tools but that process is prone to human error. Hope this helps.

Share

Notes: android.graphics.drawable.StateListDrawable

Makes a Drawable store many Drawables; It can switch between those different drawables if the Resource Id’s are provided; The resource Id’s are stored in an int[]; That int[] maps to a Drawable. Use addState(int[], Drawable) to build this dynamically

API Documentation:
StateListDrawable

Source:
StateListDrawable.java

StateListDrawable

Share

Older posts «