Tech Rocks

Coldfusion
Java
JQuery

An online resource for latest web technologies like Coldfusion, JRun, Pro*C, JQuery, HTML5, PHP, W3C, Java, J2EE, C, C++, ORACLE, PL/SQL, MySql, Ajax, Coldbox, Fusebox, UNIX, JavaScript, NodeJS and much more... contact@tech-rocks.org

Tuesday, December 17, 2013

Enabling SSL on the ColdFusion

Open a command prompt.

 

Execute the following command:
cd C:\ColdFusion8\runtime\jre\bin

Create the keystore with this command:
keytool -genkey -dname "cn=127.0.0.1, ou=CF, o=jeetu, L=Decatur, ST=GA, C=US" -keyalg rsa -keystore mykey

 

If you have previously configured a keystore you might run into this error:
keytool error: java.lang.Exception: Key pair not generated, alias already exists

If you got the “already exists” error run this command to list the keystores:
keytool -list -v | more

If you got the “already exists” error run this command to delete the keystore:
keytool -delete -alias mykey

If you got the “already exists” error re-run the command to create the keystore.

 

Enter in a password when prompted (2 times)

 

Move the keystore file (mykey) to C:\ColdFusion8\runtime\lib\

 

Edit the config file C:\ColdFusion8\runtime\servers\coldfusion\SERVER-INF\jrun.xml with an xml editor of choice. This file is VERY sensitive so be sure to not screw up the syntax of it. You should probably make a copy of it before you edit it.


<!-- Uncomment this service to use SSL with the JRun Web Server
Note that you MUST create your own keystore before using this service -->
<service class="jrun.servlet.http.SSLService" name="SSLService">
<attribute name="enabled">true </attribute>
<attribute name="interface">* </attribute>
<attribute name="port">9100 </attribute>
<attribute name="keyStore">{jrun.rootdir}/lib/mykey </attribute>
<attribute name="keyStorePassword">mypassword </attribute>
<attribute name="trustStore">{jrun.rootdir}/lib/trustStore </attribute>
<attribute name="socketFactoryName">jrun.servlet.http.JRunSSLServerSocketFactory </attribute>
</service>


Restart the ColdFusion application service.

 

Create a test page in the ColdFusion 8 wwwroot and opening it in a web browser using: https://127.0.0.1:9100/testpage.cfm

Wednesday, November 27, 2013

Google Chrome vs Chromium

Google Chrome Chromium Notes
Logo Colorful Blue
Crash reporting Yes, if you turn it on None Please include symbolized backtraces in bug reports if you don't have crash reporting
User metrics Yes, if you turn it on No
Video and audio tags AAC, MP3, Vorbis and Theora Vorbis and Theora by default May vary by distro
Adobe Flash custom (non-free) plugin included in release supports NPAPI plugins, including the one from Adobe
PDF support custom (non-free) plugin included in release downloads and displays with system PDF viewer The Chrome PDF plugin uses 3rd-party non-free code; no Free Software PDF plugin exists that supports all the PDF features we'd like (such as filling in forms). :(
Code Tested by Chrome developers May be modified by distributions Please include distribution information if you report bugs
Sandbox Always on Depending on the distribution (navigate to about:sandbox to confirm)
Package Single deb/rpm Depending on the distribution
Profile Kept in ~/.config/google-chrome Kept in ~/.config/chromium
Cache Kept in ~/.cache/google-chrome Kept in ~/.cache/chromium
Quality Assurance New releases are tested before sending to users Depending on the distribution Distributions are encouraged to track stable channel releases: see http://googlechromereleases.blogspot.com/ , http://omahaproxy.appspot.com/ and http://gsdview.appspot.com/chromium-browser-official/
Google API keys Added by Google Depending on the distribution See http://www.chromium.org/developers/how-tos/api-keys

Monday, November 11, 2013

URL Encoding Codes

Character

Character Name

URL Encoding

ASCII

 

Space

+ or %20

32

a-z

Lower case letters

-

97-122 (&61-&7A)

A-Z

Upper case letters

-

65-90 (&41-&5A)

0-9

Numbers

-

48-57 (&30-&39)

`

Accent Grave

%60

96

~

Tilde

%7E

126

!

Exclamation

%21

33

@

At

-

64 (&40)

#

Number Sign

%23

35

$

Dollar Sign

%24

36

%

Percent

%25

37

^

Circumflex

%5E

94

&

Ampersand

%26

38

*

Asterisk

-

42 (&2A)

(

Open Parenthesis

%28

40

)

Close Parenthesis

%29

41

-

Hyphen

-

45 (&2D)

_

Underscore

-

95 (&5F)

=

Equals

%3D

61

+

Plus

%2B

43

\

Back Slash *

%5C

92

|

Bar

%7C

124

[

Left Bracket

%5B

91

]

Right Bracket

%5D

93

{

Left Brace

%7B

123

}

Right Brace

%7D

125

;

Semi-colon

%3B

59

:

Colon

%3A

58

'

Single Quote

%27

39

"

Double Quote *

%22

34

,

Comma

%2C

44

.

Period

-

46 (&2E)

<

Less Than

%3C

60

>

Greater Than

%3E

62

/

Forward Slash

-

47 (&2F)

?

Question Mark

%3F

63

Tuesday, October 22, 2013

Open source in-memory data grid vs Oracle Coherence

Hazelcast is the leading open source in-memory data grid it provides java developers an easy-to-use and powerful solution for data distribution that can be used as a clustering solution, a distributed cache and a NoSQL key-value store. For Enterprise customers needing hundreds of nodes of distributed in-memory computing, our off-heap elastic memory provide highly scalable, highly available, low latency and highly predictable clustered memory and distributed computing.

 

Click here for more info

Spring JSR-250 Annotations

Spring has JSR-250 based annotations which include @PostConstruct, @PreDestroy and @Resource annotations.

  • @PostConstruct: This annotation can be used as an alternate of initialization callback.

  • @PreDestroy: This annotation can be used as an alternate of destruction callback.

  • @Resource : This annotation can be used on fields or setter methods. The @Resource annotation takes a 'name' attribute which will be interpreted as the bean name to be injected. You can say, it follows by-name autowiring semantics.

Spring Bean Auto wiring

The Spring container is able to autowire relationships between collaborating beans. This means that it is possible to automatically let Spring resolve collaborators (other beans) for your bean by inspecting the contents of the BeanFactory without using <constructor-arg> and <property> elements.

 

The autowiring functionality has five modes which can be used to instruct Spring container to use autowiring for dependency injection:

  • no: This is default setting which means no autowiring and you should use explicit bean reference for wiring. You have nothing to do special for this wiring. This is what you already have seen in Dependency Injection chapter.

  • byName: Autowiring by property name. Spring container looks at the properties of the beans on which autowire attribute is set to byName in the XML configuration file. It then tries to match and wire its properties with the beans defined by the same names in the configuration file.

  • byType: Autowiring by property datatype. Spring container looks at the properties of the beans on which autowire attribute is set to byType in the XML configuration file. It then tries to match and wire a property if its type matches with exactly one of the beans name in configuration file. If more than one such beans exist, a fatal exception is thrown.

  • constructor: Similar to byType, but type applies to constructor arguments. If there is not exactly one bean of the constructor argument type in the container, a fatal error is raised.

  • autodetect: Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by byType.

  •  

    Limitations of autowiring are:

  • Overriding possibility: You can still specify dependencies using <constructor-arg> and <property> settings which will always override autowiring.

  • Primitive data types: You cannot autowire so-called simple properties such as primitives, Strings, and Classes.

  • Confusing nature: Autowiring is less exact than explicit wiring, so if possible prefer using explicit wiring.

  •  

    Annotation wiring is not turned on in the Spring container by default. So, before we can use annotation-based wiring, we will need to enable it in our Spring configuration file by configuring <context:annotation-config/>.

     

    Note: null and empty string values can be injected in Spring

    Inject Java Collection in Spring

    Spring offers four types of collection configuration elements which are as follows:

    • <list>: This helps in wiring i.e. injecting a list of values, allowing duplicates.

    • <set>: This helps in wiring a set of values but without any duplicates.

    • <map>: This can be used to inject a collection of name-value pairs where name and value can be of any type.

    • <props>: This can be used to inject a collection of name-value pairs where the name and value are both Strings.

    Spring Bean Lifecycle

    • Instantiate - First the spring container finds the bean's definition from the XML file and instantiates the bean..

    • Populate properties - Using the dependency injection, spring populates all of the properties as specified in the bean definition..

    • Set Bean Name - If the bean implements BeanNameAware interface, spring passes the bean's id to setBeanName() method.

    • Set Bean factory - If Bean implements BeanFactoryAware interface, spring passes the beanfactory to setBeanFactory() method.

    • Pre Initialization - Also called postprocess of bean. If there are any bean BeanPostProcessors associated with the bean, Spring calls postProcesserBeforeInitialization() method.

    • Initialize beans - If the bean implements IntializingBean,its afterPropertySet() method is called. If the bean has init method declaration, the specified initialization method is called.

    • Post Initialization - If there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.

    • Ready to use - Now the bean is ready to use by the application.

    • Destroy - If the bean implements DisposableBean , it will call the destroy() method .

    Spring Container - configuration metadata

    There are following three important methods to provide configuration metadata to the Spring Container:

    • XML based configuration file.

    • Annotation-based configuration

    • Java-based configuration

    Spring Bean

    The objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. These beans are created with the configuration metadata that you supply to the container, for example, in the form of XML <bean/> definitions.

     

    The bean definition contains the information called configuration metadata which is needed for the container to know the followings:

    • How to create a bean
    • Bean's lifecycle details
    • Bean's dependencies

     

    When defining a <bean> in Spring, you have the option of declaring a scope for that bean. For example, to force Spring to produce a new bean instance each time one is needed, you should declare the bean's scope attribute to be prototype. Similar way if you want Spring to return the same bean instance each time one is needed, you should declare the bean's scope attribute to be singleton.

     

    The Spring Framework supports following five scopes, three of which are available only if you use a web-aware ApplicationContext.

    • singleton: This scopes the bean definition to a single instance per Spring IoC container.
    • prototype: This scopes a single bean definition to have any number of object instances.
    • request: This scopes a bean definition to an HTTP request. Only valid in the context of a web-aware Spring ApplicationContext.
    • session: This scopes a bean definition to an HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.
    • global-session: This scopes a bean definition to a global HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.

    The default scope of bean is Singleton for Spring framework and No, singleton beans are not thread-safe in Spring framework.

     

    Inner beans in Spring

    A <bean/> element inside the <property/> or <constructor-arg/> elements defines a so-called inner bean. An inner bean definition does not require a defined id or name; the container ignores these values. It also ignores the scope flag. Inner beans are always anonymous and they are always scoped as prototypes.

     

    To add a bean in spring application

    <?xml version="1.0" encoding="UTF-8"?>

    <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="helloWorld" class="com.jeetu.HelloWorld">
    <property name="message" value="Hello World!"/>
    </bean>

    </beans>

    Spring Bean Factory vs ApplicationContext

    • Application contexts provide a means for resolving text messages, including support for i18n of those messages.

    • Application contexts provide a generic way to load file resources, such as images.

    • Application contexts can publish events to beans that are registered as listeners.

    • Certain operations on the container or beans in the container, which have to be handled in a programmatic fashion with a bean factory, can be handled declaratively in an application context.

    • The application context implements MessageSource, an interface used to obtain localized messages, with the actual implementation being pluggable.

    Spring ApplicationContext

    The three commonly used implementation of 'Application Context' are as below:

    • FileSystemXmlApplicationContext: This container loads the definitions of the beans from an XML file. Here you need to provide the full path of the XML bean configuration file to the constructor.

    • ClassPathXmlApplicationContext: This container loads the definitions of the beans from an XML file. Here you do not need to provide the full path of the XML file but you need to set CLASSPATH properly because this container will look bean configuration XML file in CLASSPATH.

    • WebXmlApplicationContext: This container loads the XML file with definitions of all beans from within a web application.

    XmlBeanFactory class

    The most commonly used BeanFactory implementation is the XmlBeanFactory class. This container reads the configuration metadata from an XML file and uses it to create a fully configured system or application.

    Spring IOC Containers

    There are two types of IoC containers:

    • Bean Factory container: This is the simplest container providing basic support for DI .The BeanFactory is usually preferred where the resources are limited like mobile devices or applet based applications

    • Spring ApplicationContext Container: This container adds more enterprise-specific functionality such as the ability to resolve textual messages from a properties file and the ability to publish application events to interested event listeners.

    Aspect-oriented programming - AOP

    Aspect-oriented programming, or AOP, is a programming technique that allows programmers to modularize crosscutting concerns, or behavior that cuts across the typical divisions of responsibility, such as logging and transaction management. The core construct of AOP is the aspect, which encapsulates behaviors affecting multiple classes into reusable modules.

    Benefits of IOC

    • Minimizes the amount of code in your application.

    • Makes your application easy to test as it doesn't require any singletons or JNDI lookup mechanisms in your unit test cases.

    • Loose coupling is promoted with minimal effort and least intrusive mechanism.

    • IOC containers support eager instantiation and lazy loading of services.

    Spring Dependency Injection Concept

    This concept says that you do not create your objects but describe how they should be created. You don't directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (the IOC container) is then responsible for hooking it all up.

     

    2 Types:

     

    • Constructor-based dependency injection: Constructor-based DI is accomplished when the container invokes a class constructor with a number of arguments, each representing a dependency on other class.

    • Setter-based dependency injection: Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.

     

    Since you can mix both, Constructor- and Setter-based DI, it is a good rule of thumb to use constructor arguments for mandatory dependencies and setters for optional dependencies. Note that the use of a @Required annotation on a setter can be used to make setters required dependencies. The Spring IoC creates the objects, wire them together, configure them, and manage their complete lifecycle from creation till destruction. The Spring container uses dependency injection (DI) to manage the components that make up an application.

    Spring Modules

    • Core module

    • Bean module

    • Context module

    • JDBC module

    • ORM module

    • Expression Language module

    • OXM module

    • Java Messaging Service(JMS) module

    • Transaction module

    • Web module

    • Web-Servlet module

    • Web-Struts module

    • Web-Portlet module

    Spring Framework Benefits

    • Lightweight: Spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 2MB.

    • Aspect oriented (AOP): Spring supports Aspect oriented programming and enables cohesive development by separating application business logic from system services.

    • Exception Handling: Spring provides a convenient API to translate technology-specific exceptions (thrown by JDBC, Hibernate, or JDO, for example) into consistent, unchecked exceptions.

    • Container: Spring contains and manages the life cycle and configuration of application objects.

    • MVC Framework: Spring's web framework is a well-designed web MVC framework, which provides a great alternative to web frameworks such as Struts or other over engineered or less popular web frameworks.

    • Transaction Management: Spring provides a consistent transaction management interface that can scale down to a local transaction (using a single database, for example) and scale up to global transactions (using JTA, for example).

    • Inversion of control (IOC): Loose coupling is achieved in spring using the technique Inversion of Control. The objects give their dependencies instead of creating or looking for dependent objects.

    Friday, October 18, 2013

    Thursday, October 10, 2013

    Tuesday, October 8, 2013

    Google Web Designer Tool

    Create engaging, interactive HTML5-based designs and motion graphics that can run on any device.

    gwt

    Check this link

    Thursday, September 12, 2013

    Google Plus list activities - java api

    List retval = new ArrayList();

    Plus.Activities.List listActivities =
    plusSvc.activities().list(userid, "public");

    listActivities.setMaxResults(100L);

    // get the 1st page of activity objects
    ActivityFeed activityFeed = listActivities.execute();

    // unwrap the request and extract the pieces we want
    List pageOfActivities = activityFeed.getItems();

    // loop through until we arrive at an empty page
    while (pageOfActivities != null) {
    for (Activity activity : pageOfActivities) {
    retval.add(activity);
    System.out.println("ID " + activity.getId() + " Content: " +
    activity.getPlusObject().getContent());
    }

    // we will know we are on the last page when the next page token
    // is null (in which case, break).
    if (activityFeed.getNextPageToken() == null) {
    break;
    }

    // prepare to request the next page of activities
    listActivities.setPageToken(activityFeed.getNextPageToken());

    // execute and process the next page request
    activityFeed = listActivities.execute();
    pageOfActivities = activityFeed.getItems();
    }

    Wednesday, September 4, 2013

    Google OAuth Scope List

    Service

    Scope

    Google Drive

    https://www.googleapis.com/auth/drive

    Google Drive Files

    https://www.googleapis.com/auth/drive.file

    Chrome Web store

    https://www.googleapis.com/auth/chromewebstore.readonly

    Google Docs

    https://docs.google.com/feeds/

    Google Finance

    https://finance.google.com/finance/feeds/

    Gmail

    https://mail.google.com/mail/feed/atom

    Google Health

    https://www.google.com/health/feeds/

    Google Spreadsheets

    https://spreadsheets.google.com/feeds/

    Google Tasks

    https://www.googleapis.com/auth/tasks

    Google URL Shortener

    https://www.googleapis.com/auth/urlshortener

    Google Wave

    http://wave.googleusercontent.com/api/rpc

    Google Webmaster Tools

    https://www.google.com/webmasters/tools/feeds/

    User Info (Email)

    https://www.googleapis.com/auth/userinfo.email

    User Info (Profile)

    https://www.googleapis.com/auth/userinfo.email

    Youtube

    https://gdata.youtube.com

    Google H9

    https://www.google.com/h9/feeds/

    Google Maps

    https://maps.google.com/maps/feeds/

    Moderator

    https://www.googleapis.com/auth/moderator

    Open Social

    https://www-opensocial.googleusercontent.com/api/people/

    Orkut Rest API

    https://www.googleapis.com/auth/orkut

    Orkut

    https://orkut.gmodules.com/social/rest

    Picassa Web

    https://picasaweb.google.com/data/

    Google + login

    https://www.googleapis.com/auth/plus.login

    Google +

    https://www.googleapis.com/auth/plus.me

    Side Wiki

    https://www.google.com/sidewiki/feeds/

    Google Sites

    https://sites.google.com/feeds/

    Google Analytics

    https://www.google.com/analytics/feeds/

    Google App state

    https://www.googleapis.com/auth/appstate

    Google Base

    https://www.google.com/base/feeds/

    Goolge Buzz

    https://www.googleapis.com/auth/buzz

    Google Books

    https://www.google.com/books/feeds/

    Blogger

    https://www.blogger.com/feeds/

    Google Calendar

    https://www.google.com/calendar/feeds/

    Google Games

    https://www.googleapis.com/auth/games

    Google Cloud Messaging for Android

    https://android.apis.google.com/c2dm

    Google Cloud Messaging for Browser

    https://www.googleapis.com/auth/gcm_for_chrome

    Google Contacts

    https://www.google.com/m8/feeds/

    Sunday, August 25, 2013

    Getting Started with YouTube Java API

    See example

    YouTube Data API - Java Code Samples

    Check the documentation here

    
    package com.google.api.services.samples.youtube.cmdline.youtube_cmdline_channelbulletin_sample;
    
    import java.io.File;
    import java.util.Calendar;
    import java.util.List;
    
    import com.google.api.client.auth.oauth2.Credential;
    import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
    import com.google.api.client.extensions.java6.auth.oauth2.FileCredentialStore;
    import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
    import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
    import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
    import com.google.api.client.googleapis.json.GoogleJsonResponseException;
    import com.google.api.client.http.HttpTransport;
    import com.google.api.client.http.javanet.NetHttpTransport;
    import com.google.api.client.json.JsonFactory;
    import com.google.api.client.json.jackson2.JacksonFactory;
    import com.google.api.services.youtube.YouTube;
    import com.google.api.services.youtube.model.Activity;
    import com.google.api.services.youtube.model.ActivityContentDetails;
    import com.google.api.services.youtube.model.ActivityContentDetails.Bulletin;
    import com.google.api.services.youtube.model.ActivitySnippet;
    import com.google.api.services.youtube.model.Channel;
    import com.google.api.services.youtube.model.ChannelListResponse;
    import com.google.api.services.youtube.model.ResourceId;
    import com.google.common.collect.Lists;
    
    /**
     * Creates a video bulletin that is posted to the user's channel feed.
     *
     * @author Jeremy Walker
     */
    public class ChannelBulletin {
    
      /** Global instance of the HTTP transport. */
      private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
    
      /** Global instance of the JSON factory. */
      private static final JsonFactory JSON_FACTORY = new JacksonFactory();
    
      /** Global instance of YouTube object to make all API requests. */
      private static YouTube youtube;
    
      /*
       * Global instance of the video id we want to post as a bulletin into our channel feed. You will
       * probably pull this from a search or your app.
       */
      private static String VIDEO_ID = "L-oNKK1CrnU";
    
      /**
       * Authorizes the installed application to access user's protected data.
       *
       * @param scopes list of scopes needed to run upload.
       */
      private static Credential authorize(List scopes) throws Exception {
    
        // Load client secrets.
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(
            JSON_FACTORY, ChannelBulletin.class.getResourceAsStream("/client_secrets.json"));
    
        // Checks that the defaults have been replaced (Default = "Enter X here").
        if (clientSecrets.getDetails().getClientId().startsWith("Enter")
            || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
          System.out.println(
              "Enter Client ID and Secret from https://code.google.com/apis/console/?api=youtube"
              + "into youtube-cmdline-channelbulletin-sample/src/main/resources/client_secrets.json");
          System.exit(1);
        }
    
        // Set up file credential store.
        FileCredentialStore credentialStore = new FileCredentialStore(
            new File(System.getProperty("user.home"), ".credentials/youtube-api-channelbulletin.json"),
            JSON_FACTORY);
    
        // Set up authorization code flow.
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, scopes).setCredentialStore(credentialStore)
            .build();
    
        // Build the local server and bind it to port 8080
        LocalServerReceiver localReceiver = new LocalServerReceiver.Builder().setPort(8080).build();
    
        // Authorize.
        return new AuthorizationCodeInstalledApp(flow, localReceiver).authorize("user");
      }
    
      /**
       * Authorizes user, runs Youtube.Channnels.List to get the default channel, and posts a bulletin
       * with a video id to the user's default channel.
       *
       * @param args command line args (not used).
       */
      public static void main(String[] args) {
    
        // Scope required to upload to YouTube.
        List scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube");
    
        try {
          // Authorization.
          Credential credential = authorize(scopes);
    
          // YouTube object used to make all API requests.
          youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(
              "youtube-cmdline-channelbulletin-sample").build();
    
          /*
           * Now that the user is authenticated, the app makes a channel list request to get the
           * authenticated user's channel. https://developers.google.com/youtube/v3/docs/channels/list
           */
          YouTube.Channels.List channelRequest = youtube.channels().list("contentDetails");
          channelRequest.setMine("true");
          /*
           * Limits the results to only the data we need making your app more efficient.
           */
          channelRequest.setFields("items/contentDetails");
          ChannelListResponse channelResult = channelRequest.execute();
    
          /*
           * Gets the list of channels associated with the user.
           */
          List channelsList = channelResult.getItems();
    
          if (channelsList != null) {
            // Gets user's default channel id (first channel in list).
            String channelId = channelsList.get(0).getId();
    
            /*
             * We create the snippet to set the channel we will post to and the description that goes
             * along with our bulletin.
             */
            ActivitySnippet snippet = new ActivitySnippet();
            snippet.setChannelId(channelId);
            Calendar cal = Calendar.getInstance();
            snippet.setDescription("Bulletin test video via YouTube API on " + cal.getTime());
    
            /*
             * We set the kind of the ResourceId to video (youtube#video). Please note, you could set
             * the type to a playlist (youtube#playlist) and use a playlist id instead of a video id.
             */
            ResourceId resource = new ResourceId();
            resource.setKind("youtube#video");
            resource.setVideoId(VIDEO_ID);
    
            Bulletin bulletin = new Bulletin();
            bulletin.setResourceId(resource);
    
            // We construct the ActivityContentDetails now that we have the Bulletin.
            ActivityContentDetails contentDetails = new ActivityContentDetails();
            contentDetails.setBulletin(bulletin);
    
            /*
             * Finally, we construct the activity we will write to YouTube via the API. We set the
             * snippet (covers description and channel we are posting to) and the content details
             * (covers video id and type).
             */
            Activity activity = new Activity();
            activity.setSnippet(snippet);
            activity.setContentDetails(contentDetails);
    
            /*
             * We specify the parts (contentDetails and snippet) we will write to YouTube. Those also
             * cover the parts that are returned.
             */
            YouTube.Activities.Insert insertActivities =
                youtube.activities().insert("contentDetails,snippet", activity);
            // This returns the Activity that was added to the user's YouTube channel.
            Activity newActivityInserted = insertActivities.execute();
    
            if (newActivityInserted != null) {
              System.out.println(
                  "New Activity inserted of type " + newActivityInserted.getSnippet().getType());
              System.out.println(" - Video id "
                  + newActivityInserted.getContentDetails().getBulletin().getResourceId().getVideoId());
              System.out.println(
                  " - Description: " + newActivityInserted.getSnippet().getDescription());
              System.out.println(" - Posted on " + newActivityInserted.getSnippet().getPublishedAt());
            } else {
              System.out.println("Activity failed.");
            }
    
          } else {
            System.out.println("No channels are assigned to this user.");
          }
        } catch (GoogleJsonResponseException e) {
          e.printStackTrace();
          System.err.println("There was a service error: " + e.getDetails().getCode() + " : "
              + e.getDetails().getMessage());
    
        } catch (Throwable t) {
          t.printStackTrace();
        }
      }
    }
    
    

    Sunday, August 4, 2013

    appcfg.cmd deploy to Google

    cd C:\appengine-java-sdk-1.8.2\bin

    appcfg.cmd update C:\Users\jeetu\workspace-xxx\projectxxx\war

    email: xxx

    password: xxx

    Restlet on Google App Engine

    Download the API here

    Check this tutorial & tutorial 1