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...

Wednesday, October 29, 2014

Role Based Access Control–JBoss

Role & Permissions

  1. Monitor
    Has the fewest permissions Only read configuration and current runtime state No access to sensitive resources or data or audit logging resources
  2. Operator
    Monitor Can modify the runtime state, e.g. reload or shutdown the server, pause/resume JMS destination, flush database connection pool. Does not have permission to modify persistent state.
  3. Maintainer
    Operator Can modify the persistent state, e.g. deploy an application, setting up new data sources, add a JMS destination
  4. Deployer
    Maintainer Permission is restricted to applications only, cannot make changes to container configuration
  5. Administrator
    Maintainer View and modify sensitive data such as access control system No access to administrative audit logging system
  6. Auditor
    Monitor View and modify resources to administrative audit logging system Cannot modify sensitive resources or data outside auditing, can read any sensitive data
  7. Super User
    Has all the permissions Equivalent to administrator in previous versions

See more details and here

See introductory videos:

Tuesday, September 2, 2014

HandleBars JS

Handlebars provides the power necessary to let you build semantic templates effectively with no frustration. Handlebars is largely compatible with Mustache templates. In most cases it is possible to swap out Mustache with Handlebars and continue using your current templates. Complete details can be found here.

Monday, April 7, 2014

Cannot create a server using the selected type - FIX

To fix the error 'Cannot create a server using the selected type' run the following:

cd ~/workspace/.metadata/.plugins/org.eclipse.core.runtime/.settings/    
rm org.eclipse.jst.server.tomcat.core.prefs
rm org.eclipse.wst.server.core.prefs


temp

Java Enterprise Edition (Java EE) Technologies on AppEngine

Supported

While we do not support the entirety of the Java EE specification, many of its individual components are supported. These include:

  • Java Data Objects (JDO)
  • Java Persistence API (JPA)
  • Java Server Faces (JSF) 1.1 - 2.0
  • Java Server Pages (JSP) + JSTL
  • Java Servlet API 2.4
  • JavaBeans™ Activation Framework (JAF)
  • Java Architecture for XML Binding (JAXB)
  • Java API for XML Web Services (JAX-WS) 4
  • JavaMail
  • XML processing APIs including DOM, SAX, and XSLT
  • 1 For a guide on "converting" between JPA and JDO.

    2 JSF 1.1 appears to be working out-of-the-box. JSF 1.2 and JSF 2.0 should also work if you set the com.sun.faces.enableMultiThreadedStartup context parameter to false to your web.xml file. Setting this parameter to false (it's set to true by default) will prevent additional threads from being spawned. For more information on running JSF 2.0 in App Engine.

    3 JSP session beans are not supported; to enable EL parsing, add <%@page isElIgnored="false" %> to your JSPs and <%@tag isElIgnored="false" %> to your tag files.

    4 JAX-WS is supported for web service clients but not for servers. To write a SOAP server on App Engine you must use javax.xml.soap and JAXB.

     

    Not supported

    There are various APIs and technologies that are not supported by App Engine at present for various reasons. These include:

  • Enterprise Java Beans (EJB)
  • JAX-RPC
  • Java Database Connectivity (JDBC)
  • Java EE™ Connector Architecture (JCA)
  • Java Management Extensions (JMX)
  • Java Message Service (JMS)
  • Java Naming and Directory Interface (JNDI)
  • Remote Method Invocation (RMI)
  • App Engine's underlying datastore is based on BigTable, not a traditional SQL-based RDBMS like MySQL or PostgreSQL. You may either use the low-level datastore API or the JDO or JPA object-relational mapping interfaces provided. Various JDBC wrappers are available for the datastore, and you may still be able to connect to in-memory databases such as the H2 database engine or HSQLDB.

    Sunday, March 16, 2014

    Blinking text CSS

    Works on Firefox, Chrome, IE latest versions.

    Check this link

    .blink_me {
    -webkit-animation-name: blinker;
    -webkit-animation-duration: 1s;
    -webkit-animation-timing-function: linear;
    -webkit-animation-iteration-count: infinite;

    -moz-animation-name: blinker;
    -moz-animation-duration: 1s;
    -moz-animation-timing-function: linear;
    -moz-animation-iteration-count: infinite;

    animation-name: blinker;
    animation-duration: 1s;
    animation-timing-function: linear;
    animation-iteration-count: infinite;
    }

    @-moz-keyframes blinker {
    0% { opacity: 1.0; }
    50% { opacity: 0.0; }
    100% { opacity: 1.0; }
    }

    @-webkit-keyframes blinker {
    0% { opacity: 1.0; }
    50% { opacity: 0.0; }
    100% { opacity: 1.0; }
    }

    @keyframes blinker {
    0% { opacity: 1.0; }
    50% { opacity: 0.0; }
    100% { opacity: 1.0; }
    }

    Saturday, March 1, 2014

    Google Sites API in java

    import com.google.gdata.client.http.HttpGDataRequest;
    import com.google.gdata.client.sites.SitesService;
    import com.google.gdata.data.Link;
    import com.google.gdata.data.MediaContent;
    import com.google.gdata.data.OutOfLineContent;
    import com.google.gdata.data.PlainTextConstruct;
    import com.google.gdata.data.XhtmlTextConstruct;
    import com.google.gdata.data.acl.AclEntry;
    import com.google.gdata.data.acl.AclFeed;
    import com.google.gdata.data.media.MediaFileSource;
    import com.google.gdata.data.media.MediaSource;
    import com.google.gdata.data.sites.ActivityFeed;
    import com.google.gdata.data.sites.AnnouncementEntry;
    import com.google.gdata.data.sites.AnnouncementsPageEntry;
    import com.google.gdata.data.sites.AttachmentEntry;
    import com.google.gdata.data.sites.BaseActivityEntry;
    import com.google.gdata.data.sites.BaseContentEntry;
    import com.google.gdata.data.sites.BasePageEntry;
    import com.google.gdata.data.sites.CommentEntry;
    import com.google.gdata.data.sites.ContentFeed;
    import com.google.gdata.data.sites.FileCabinetPageEntry;
    import com.google.gdata.data.sites.ListItemEntry;
    import com.google.gdata.data.sites.ListPageEntry;
    import com.google.gdata.data.sites.RevisionFeed;
    import com.google.gdata.data.sites.SiteFeed;
    import com.google.gdata.data.sites.SiteEntry;
    import com.google.gdata.data.sites.SitesLink;
    import com.google.gdata.data.sites.Theme;
    import com.google.gdata.data.sites.WebAttachmentEntry;
    import com.google.gdata.data.sites.WebPageEntry;
    import com.google.gdata.data.spreadsheet.Column;
    import com.google.gdata.data.spreadsheet.Field;
    import com.google.gdata.util.AuthenticationException;
    import com.google.gdata.util.ServiceException;
    import com.google.gdata.util.XmlBlob;
    import com.google.gdata.util.XmlParser;

    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.util.logging.ConsoleHandler;
    import java.util.logging.Level;
    import java.util.logging.Logger;

    import javax.activation.MimetypesFileTypeMap;

    /**
    * Wrapper class for lower level Sites API calls.
    *
    *
    */
    public class SitesHelper {

    private String domain;
    private String siteName;

    public SitesService service;
    public MimetypesFileTypeMap mediaTypes;

    public static final String[] KINDS = {
    "announcement", "announcementspage", "attachment", "comment",
    "filecabinet", "listitem", "listpage", "webpage", "webattachment"
    };

    /**
    * Constructor
    *
    * @param applicationName The name of the application.
    * @param domain The Site's Google Apps domain or "site".
    * @param siteName The webspace name of the Site.
    */
    public SitesHelper(String applicationName, String domain, String siteName) {
    this(applicationName, domain, siteName, false);
    }

    /**
    * Constructor
    *
    * @param applicationName The name of the application.
    * @param domain The Site's Google Apps domain or "site".
    * @param siteName The webspace name of the Site.
    * @param logging Whether to enable HTTP requests to stdout
    */
    public SitesHelper(String applicationName, String domain, String siteName,
    boolean logging) {
    if (logging) {
    turnOnLogging(false);
    }

    this.domain = domain;
    this.siteName = siteName;
    this.service = new SitesService(applicationName);

    registerMediaTypes();
    }

    private void registerMediaTypes() {
    // Common MIME types used for uploading attachments.
    mediaTypes = new MimetypesFileTypeMap();
    mediaTypes.addMimeTypes("application/msword doc");
    mediaTypes.addMimeTypes("application/vnd.ms-excel xls");
    mediaTypes.addMimeTypes("application/pdf pdf");
    mediaTypes.addMimeTypes("text/richtext rtx");
    mediaTypes.addMimeTypes("text/csv csv");
    mediaTypes.addMimeTypes("text/tab-separated-values tsv tab");
    mediaTypes.addMimeTypes("application/x-vnd.oasis.opendocument.spreadsheet ods");
    mediaTypes.addMimeTypes("application/vnd.oasis.opendocument.text odt");
    mediaTypes.addMimeTypes("application/vnd.ms-powerpoint ppt pps pot");
    mediaTypes.addMimeTypes("application/vnd.openxmlformats-officedocument."
    + "wordprocessingml.document docx");
    mediaTypes.addMimeTypes("application/vnd.openxmlformats-officedocument."
    + "spreadsheetml.sheet xlsx");
    mediaTypes.addMimeTypes("audio/mpeg mp3 mpeg3");
    mediaTypes.addMimeTypes("image/png png");
    mediaTypes.addMimeTypes("application/zip zip");
    mediaTypes.addMimeTypes("application/x-tar tar");
    mediaTypes.addMimeTypes("video/quicktime qt mov moov");
    mediaTypes.addMimeTypes("video/mpeg mpeg mpg mpe mpv vbs mpegv");
    mediaTypes.addMimeTypes("video/msvideo avi");
    }

    /**
    * Authenticates the user using ClientLogin
    *
    * @param username User's email address.
    * @param password User's password.
    */
    public void login(String username, String password) throws AuthenticationException {
    service.setUserCredentials(username, password);
    }

    /**
    * Authenticates the user using AuthSub
    *
    * @param authSubToken A valid AuthSub session token.
    */
    public void login(String authSubToken) {
    service.setAuthSubToken(authSubToken);
    }

    /**
    * Logs HTTP requests and XML to stdout.
    */
    private void turnOnLogging(boolean logXML) {
    // Create a log handler which prints all log events to the console
    ConsoleHandler logHandler = new ConsoleHandler();
    logHandler.setLevel(Level.ALL);

    // Configure the logging mechanisms
    Logger httpLogger =
    Logger.getLogger(HttpGDataRequest.class.getName());
    httpLogger.setLevel(Level.ALL);
    httpLogger.addHandler(logHandler);

    if (logXML) {
    Logger xmlLogger = Logger.getLogger(XmlParser.class.getName());
    xmlLogger.setLevel(Level.ALL);
    xmlLogger.addHandler(logHandler);
    }
    }

    /**
    * Returns an entry's numeric ID.
    */
    private String getEntryId(BaseContentEntry<?> entry) {
    String selfLink = entry.getSelfLink().getHref();
    return selfLink.substring(selfLink.lastIndexOf("/") + 1);
    }

    /**
    * Returns an entry's numeric ID.
    */
    private String getEntryId(String selfLink) {
    return selfLink.substring(selfLink.lastIndexOf("/") + 1);
    }

    public String getContentFeedUrl() {
    return "https://sites.google.com/feeds/content/" + domain + "/" + siteName + "/";
    }

    public String getRevisionFeedUrl() {
    return "https://sites.google.com/feeds/revision/" + domain + "/" + siteName + "/";
    }

    public String getActivityFeedUrl() {
    return "https://sites.google.com/feeds/activity/" + domain + "/" + siteName + "/";
    }

    public String getSiteFeedUrl() {
    return "https://sites.google.com/feeds/site/" + domain + "/";
    }

    public String getAclFeedUrl(String siteName) {
    return "https://sites.google.com/feeds/acl/site/" + domain + "/" + siteName + "/";
    }

    /**
    * Fetches and displays the user's site feed.
    */
    public void getSiteFeed() throws IOException, ServiceException {
    SiteFeed siteFeed = service.getFeed(
    new URL(getSiteFeedUrl()), SiteFeed.class);
    for (SiteEntry entry : siteFeed.getEntries()){
    System.out.println("title: " + entry.getTitle().getPlainText());
    System.out.println("site name: " + entry.getSiteName().getValue());
    System.out.println("theme: " + entry.getTheme().getValue());
    System.out.println("");
    }
    }

    /**
    * Fetches and displays a Site's acl feed.
    */
    public void getAclFeed(String siteName) throws IOException, ServiceException {
    AclFeed aclFeed = service.getFeed(
    new URL(getAclFeedUrl(siteName)), AclFeed.class);
    for (AclEntry entry : aclFeed.getEntries()) {
    System.out.println(entry.getScope().getValue() + " (" +
    entry.getScope().getType() + ") : " + entry.getRole().getValue());
    }
    }

    /**
    * Fetches and displays the Site's activity feed.
    */
    public void getActivityFeed() throws IOException, ServiceException {
    ActivityFeed activityFeed = service.getFeed(
    new URL(getActivityFeedUrl()), ActivityFeed.class);
    for (BaseActivityEntry<?> entry : activityFeed.getEntries()){
    System.out.println(entry.getSummary().getPlainText());
    }
    }

    /**
    * Fetches and displays the revisions feed for an entry.
    */
    public void getRevisionFeed(String contentEntryId) throws IOException, ServiceException {
    URL url = new URL(getRevisionFeedUrl() + contentEntryId);
    RevisionFeed revisionFeed = service.getFeed(url, RevisionFeed.class);
    for (BaseContentEntry<?> entry : revisionFeed.getEntries()) {
    System.out.println(entry.getTitle().getPlainText());
    System.out.println(" updated: " + entry.getUpdated().toUiString() + " by " +
    entry.getAuthors().get(0).getEmail());
    System.out.println(" revision #: " + entry.getRevision().getValue());
    }
    }

    /**
    * Fetches and displays entries from the content feed.
    *
    * @param kind An entry kind to fetch. For example, "webpage". If null, the
    * entire content feed is returned.
    */
    public void listSiteContents(String kind) throws IOException, ServiceException {
    String url = kind.equals("all") ? getContentFeedUrl() : getContentFeedUrl() + "?kind=" + kind;
    ContentFeed contentFeed = service.getFeed(new URL(url), ContentFeed.class);

    for (WebPageEntry entry : contentFeed.getEntries(WebPageEntry.class)) {
    System.out.println("WebPageEntry:");
    System.out.println(" title: " + entry.getTitle().getPlainText());
    System.out.println(" id: " + getEntryId(entry));
    if (entry.getParentLink() != null) {
    System.out.println(" parent id: " + getEntryId(entry.getParentLink().getHref()));
    }
    System.out.println(" authors: " + entry.getAuthors().get(0).getEmail());
    System.out.println(" content: " + getContentBlob(entry));
    System.out.println("");
    }

    for (ListPageEntry entry : contentFeed.getEntries(ListPageEntry.class)) {
    System.out.println("ListPageEntry:");
    System.out.println(" title: " + entry.getTitle().getPlainText());
    System.out.println(" id: " + getEntryId(entry));
    if (entry.getParentLink() != null) {
    System.out.println(" parent id: " + getEntryId(entry.getParentLink().getHref()));
    }
    for (Column col : entry.getData().getColumns()) {
    System.out.print(" [" + col.getIndex() + "] " + col.getName() + "\t");
    }
    System.out.println("");
    }

    for (ListItemEntry entry : contentFeed.getEntries(ListItemEntry.class)) {
    if (entry.getParentLink() != null) {
    System.out.println(" parent id: " + getEntryId(entry.getParentLink().getHref()));
    }
    for (Field field : entry.getFields()) {
    System.out.print(" [" + field.getIndex() + "] " + field.getValue() + "\t");
    }
    System.out.println("\n");
    }

    for (FileCabinetPageEntry entry : contentFeed.getEntries(FileCabinetPageEntry.class)) {
    System.out.println("FileCabinetPageEntry:");
    System.out.println(" title: " + entry.getTitle().getPlainText());
    System.out.println(" id: " + getEntryId(entry));
    if (entry.getParentLink() != null) {
    System.out.println(" parent id: " + getEntryId(entry.getParentLink().getHref()));
    }
    System.out.println(" content: " + getContentBlob(entry));
    System.out.println("");
    }

    for (CommentEntry entry : contentFeed.getEntries(CommentEntry.class)) {
    System.out.println("CommentEntry:");
    System.out.println(" id: " + getEntryId(entry));
    if (entry.getParentLink() != null) {
    System.out.println(" parent id: " + getEntryId(entry.getParentLink().getHref()));
    }
    System.out.println(" in-reply-to: " + entry.getInReplyTo().toString());
    System.out.println(" content: " + getContentBlob(entry));
    System.out.println("");
    }

    for (AnnouncementsPageEntry entry : contentFeed.getEntries(AnnouncementsPageEntry.class)) {
    System.out.println("AnnouncementsPageEntry:");
    System.out.println(" title: " + entry.getTitle().getPlainText());
    System.out.println(" id: " + getEntryId(entry));
    if (entry.getParentLink() != null) {
    System.out.println(" parent id: " + getEntryId(entry.getParentLink().getHref()));
    }
    System.out.println(" content: " + getContentBlob(entry));
    System.out.println("");
    }

    for (AnnouncementEntry entry : contentFeed.getEntries(AnnouncementEntry.class)) {
    System.out.println("AnnouncementEntry:");
    System.out.println(" title: " + entry.getTitle().getPlainText());
    System.out.println(" id: " + getEntryId(entry));
    if (entry.getParentLink() != null) {
    System.out.println(" parent id: " + getEntryId(entry.getParentLink().getHref()));
    }
    System.out.println(" draft?: " + entry.isDraft());
    System.out.println(" content: " + getContentBlob(entry));
    System.out.println("");
    }

    for (AttachmentEntry entry : contentFeed.getEntries(AttachmentEntry.class)) {
    System.out.println("AttachmentEntry:");
    System.out.println(" title: " + entry.getTitle().getPlainText());
    System.out.println(" id: " + getEntryId(entry));
    if (entry.getParentLink() != null) {
    System.out.println(" parent id: " + getEntryId(entry.getParentLink().getHref()));
    }
    if (entry.getSummary() != null) {
    System.out.println(" description: " + entry.getSummary().getPlainText());
    }
    System.out.println(" revision: " + entry.getRevision().getValue());
    MediaContent content = (MediaContent) entry.getContent();
    System.out.println(" src: " + content.getUri());
    System.out.println(" content type: " + content.getMimeType().getMediaType());
    System.out.println("");
    }

    for (WebAttachmentEntry entry : contentFeed.getEntries(WebAttachmentEntry.class)) {
    System.out.println("WebAttachmentEntry:");
    System.out.println(" title: " + entry.getTitle().getPlainText());
    System.out.println(" id: " + getEntryId(entry));
    if (entry.getParentLink() != null) {
    System.out.println(" parent id: " + getEntryId(entry.getParentLink().getHref()));
    }
    if (entry.getSummary() != null) {
    System.out.println(" description: " + entry.getSummary().getPlainText());
    }
    System.out.println(" src: " + ((MediaContent) entry.getContent()).getUri());
    System.out.println("");
    }
    }

    public String getContentBlob(BaseContentEntry<?> entry) {
    return ((XhtmlTextConstruct) entry.getTextContent().getContent()).getXhtml().getBlob();
    }

    private void setContentBlob(BaseContentEntry<?> entry) {
    XmlBlob xml = new XmlBlob();
    xml.setBlob(String.format(
    "content for %s", entry.getCategories().iterator().next().getLabel()));
    entry.setContent(new XhtmlTextConstruct(xml));
    }

    public SiteEntry createSite(String title, String summary)
    throws MalformedURLException, IOException, ServiceException {
    return createSite(title, summary, null);
    }

    /**
    * Creates a new Google Sites.
    *
    * @param title A name for the site.
    * @param summary A description for the site.
    * @param theme A theme to create the site with.
    * @return The created site entry.
    * @throws ServiceException
    * @throws IOException
    * @throws MalformedURLException
    */
    public SiteEntry createSite(String title, String summary, String theme)
    throws MalformedURLException, IOException, ServiceException {
    SiteEntry entry = new SiteEntry();
    entry.setTitle(new PlainTextConstruct(title));
    entry.setSummary(new PlainTextConstruct(summary));

    // Set theme if user specified it.
    if (theme != null) {
    Theme tt = new Theme();
    tt.setValue(theme);
    entry.setTheme(tt);
    }

    return service.insert(new URL(getSiteFeedUrl()), entry);
    }

    /**
    * Copies a Google Site from an existing site.
    *
    * @param title A title heading for the new site.
    * @param summary A description for the site.
    * @param theme A theme to create the site with.
    * @param sourceHref The self link of the site entry to copy this site from.
    * If null, an empty site is created.
    * @return The created site entry.
    * @throws ServiceException
    * @throws IOException
    * @throws MalformedURLException
    */
    public SiteEntry copySite(String title, String summary, String sourceHref)
    throws MalformedURLException, IOException, ServiceException {
    SiteEntry entry = new SiteEntry();
    entry.setTitle(new PlainTextConstruct(title));
    entry.setSummary(new PlainTextConstruct(summary));
    entry.addLink(SitesLink.Rel.SOURCE, Link.Type.ATOM, sourceHref);

    return service.insert(new URL(getSiteFeedUrl()), entry);
    }

    public BaseContentEntry<?> createPage(String kind, String title)
    throws MalformedURLException, SitesException, IOException, ServiceException {
    return createPage(kind, title, null);
    }

    /**
    * Creates a new (sub)page.
    *
    * @param kind The type of page to created (e.g. webpage, filecabinet, listpage, etc).
    * @param title A title heading for the page
    * @param parent The full URL of the parent to create the subpage under
    * or the parent entry's ID (e.g. 1234567890).
    * @return The created entry.
    * @throws SitesException
    * @throws ServiceException
    * @throws IOException
    * @throws MalformedURLException
    */
    public BaseContentEntry<?> createPage(String kind, String title, String parent)
    throws SitesException, MalformedURLException, IOException, ServiceException {
    BaseContentEntry<?> entry = null;
    if (kind.equals("announcement")) {
    entry = new AnnouncementEntry();
    } else if (kind.equals("announcementspage")) {
    entry = new AnnouncementsPageEntry();
    } else if (kind.equals("comment")) {
    entry = new CommentEntry();
    } else if (kind.equals("filecabinet")) {
    entry = new FileCabinetPageEntry();
    } else if (kind.equals("listitem")) {
    entry = new ListItemEntry();
    } else if (kind.equals("listpage")) {
    entry = new ListPageEntry();
    } else if (kind.equals("webpage")) {
    entry = new WebPageEntry();
    } else {
    if (kind.equals("attachment") || kind.equals("webattachment")) {
    throw new SitesException("Trying to create " + kind
    + ". Please use upload command instead.");
    } else {
    throw new SitesException("Unknown kind '" + kind + "'");
    }
    }

    entry.setTitle(new PlainTextConstruct(title));
    setContentBlob(entry);

    // Upload to a parent page?
    if (parent != null) {
    if (parent.lastIndexOf("/") == -1) {
    parent = getContentFeedUrl() + parent;
    }
    entry.addLink(SitesLink.Rel.PARENT, Link.Type.ATOM, parent);
    }

    return service.insert(new URL(getContentFeedUrl()), entry);
    }

    /**
    * Downloads a file from the specified URL to disk.
    *
    * @param downloadUrl The full URL to download the file from.
    * @param fullFilePath The local path to save the file to on disk.
    * @throws ServiceException
    * @throws IOException
    */
    private void downloadFile(String downloadUrl, String fullFilePath) throws IOException,
    ServiceException {
    System.out.println("Downloading file from: " + downloadUrl);

    MediaContent mc = new MediaContent();
    mc.setUri(downloadUrl);
    MediaSource ms = service.getMedia(mc);

    InputStream inStream = null;
    FileOutputStream outStream = null;

    try {
    inStream = ms.getInputStream();
    outStream = new FileOutputStream(fullFilePath);

    int c;
    while ((c = inStream.read()) != -1) {
    outStream.write(c);
    }
    } finally {
    if (inStream != null) {
    inStream.close();
    }
    if (outStream != null) {
    outStream.flush();
    outStream.close();
    }
    }
    }

    /**
    * Downloads an attachment.
    *
    * @param entry The attachment (entry) to download.
    * @param directory Path to a local directory to download the attach to.
    * @throws ServiceException
    * @throws IOException
    */
    public void downloadAttachment(AttachmentEntry entry, String directory)
    throws IOException, ServiceException {
    String url = ((OutOfLineContent) entry.getContent()).getUri();
    downloadFile(url, directory + entry.getTitle().getPlainText());
    }

    /**
    * Downloads an attachment.
    *
    * @param entry The attachment (entry) to download.
    * @param entryId The content entry id of the attachment (e.g. 1234567890)
    * @throws ServiceException
    * @throws IOException
    */
    public void downloadAttachment(String entryId, String directory)
    throws IOException, ServiceException {
    AttachmentEntry attachment = service.getEntry(
    new URL(getContentFeedUrl() + entryId), AttachmentEntry.class);
    String url = ((OutOfLineContent) attachment.getContent()).getUri();
    ///*MediaSource mediaSource = service.getMedia((MediaContent) entry.getContent());*/
    downloadFile(url, directory + attachment.getTitle().getPlainText());
    }

    /**
    * Downloads all attachments from a Site and assumes they all have different names.
    *
    * @param entry The attachment (entry) to download.
    * @param directory Path to a local directory to download the attach to.
    * @throws ServiceException
    * @throws IOException
    */
    public void downloadAllAttachments(String directory) throws IOException, ServiceException {
    URL contentFeedUrl = new URL(getContentFeedUrl() + "?kind=attachment");
    ContentFeed contentFeed = service.getFeed(contentFeedUrl, ContentFeed.class);
    for (AttachmentEntry entry : contentFeed.getEntries(AttachmentEntry.class)) {
    downloadAttachment(entry, directory);
    }
    }

    /**
    * Uploads an attachment to a selected parent page.
    *
    * @param file The file contents to upload.
    * @param parentPage Entry of the page to upload the attachment to.
    * @return Created attachment entry.
    * @throws ServiceException
    * @throws IOException
    */
    public AttachmentEntry uploadAttachment(File file, BasePageEntry<?> parentPage)
    throws IOException, ServiceException {
    return uploadAttachment(file, parentPage.getSelfLink().getHref(), file.getName(), "");
    }

    /**
    * Uploads an attachment to a selected parent page.
    *
    * @param file The file contents to upload,
    * @param parentPage Entry of the page to upload the attachment to.
    * @param title A title to name the attachment.
    * @return Created attachment entry.
    * @throws ServiceException
    * @throws IOException
    */
    public AttachmentEntry uploadAttachment(File file, BasePageEntry<?> parentPage, String title)
    throws IOException, ServiceException {
    return uploadAttachment(file, parentPage.getSelfLink().getHref(), title, "");
    }

    /**
    * Uploads an attachment to a selected parent page.
    *
    * @param file The file contents to upload.
    * @param parentPage Entry of the page to upload the attachment to.
    * @param title A title to name the attachment.
    * @param description A description for the file.
    * @return Created attachment entry.
    * @throws ServiceException
    * @throws IOException
    */
    public AttachmentEntry uploadAttachment(File file, BasePageEntry<?> parentPage,
    String title, String description) throws IOException, ServiceException {
    return uploadAttachment(file, parentPage.getSelfLink().getHref(), title, description);
    }

    /**
    * Uploads an attachment to a selected parent page.
    *
    * @param filename Path of the file to upload.
    * @param parentPage Entry of the page to upload the attachment to.
    * @return Created attachment entry.
    * @throws ServiceException
    * @throws IOException
    */
    public AttachmentEntry uploadAttachment(String filename, BasePageEntry<?> parentPage)
    throws IOException, ServiceException {
    File file = new File(filename);
    return uploadAttachment(file, parentPage.getSelfLink().getHref(), file.getName(), "");
    }

    /**
    * Uploads an attachment to a selected parent page.
    *
    * @param filename Path of the file to upload.
    * @param parentUrl Full self id of the parent entry to upload the attachmen to.
    * @param description A file description.
    * @return Created attachment entry.
    * @throws ServiceException
    * @throws IOException
    */
    public AttachmentEntry uploadAttachment(String filename, String parentUrl, String description)
    throws IOException, ServiceException {
    File file = new File(filename);
    return uploadAttachment(file, parentUrl, file.getName(), description);
    }

    /**
    * Uploads an attachment to a parent page using the file name for a title.
    *
    * @param file The file contents to upload.
    * @param parentUrl Feed URL of the page to upload the attachment to.
    * @return Created attachment entry.
    * @throws ServiceException
    * @throws IOException
    */
    public AttachmentEntry uploadAttachment(File file, String parentUrl)
    throws IOException, ServiceException {
    return uploadAttachment(file, parentUrl, file.getName(), "");
    }

    /**
    * Uploads an attachment to a parent page using the file name for a title.
    *
    * @param file The file contents to upload
    * @param parentLink Full self id of the parent entry to upload the attach to.
    * @param description A file description.
    * @return The created attachment entry.
    * @throws ServiceException
    * @throws IOException
    */
    public AttachmentEntry uploadAttachment(File file, String parentLink, String description)
    throws IOException, ServiceException {
    return uploadAttachment(file, parentLink, file.getName(), description);
    }

    /**
    * Uploads an attachment to a parent page.
    *
    * @param file The file contents to upload
    * @param parentLink Full self id of the parent entry to upload the attach to.
    * @param title A title for the attachment.
    * @param description A description for the attachment.
    * @return The created attachment entry.
    * @throws ServiceException
    * @throws IOException
    */
    public AttachmentEntry uploadAttachment(File file, String parentLink, String title,
    String description) throws IOException, ServiceException {
    String fileMimeType = mediaTypes.getContentType(file);

    AttachmentEntry newAttachment = new AttachmentEntry();
    newAttachment.setMediaSource(new MediaFileSource(file, fileMimeType));
    newAttachment.setTitle(new PlainTextConstruct(title));
    newAttachment.setSummary(new PlainTextConstruct(description));
    newAttachment.addLink(SitesLink.Rel.PARENT, Link.Type.ATOM, parentLink);

    return service.insert(new URL(getContentFeedUrl()), newAttachment);
    }

    /**
    * Creates a web attachment under the selected file cabinet.
    *
    * @param contentUrl The full URL of the hosted file.
    * @param filecabinet File cabinet to create the web attachment on.
    * @param title A title for the attachment.
    * @param description A description for the attachment.
    * @return The created web attachment.
    * @throws ServiceException
    * @throws IOException
    * @throws MalformedURLException
    */
    public WebAttachmentEntry uploadWebAttachment(String contentUrl,
    FileCabinetPageEntry filecabinet, String title, String description)
    throws MalformedURLException, IOException, ServiceException {
    MediaContent content = new MediaContent();
    content.setUri(contentUrl);

    WebAttachmentEntry webAttachment = new WebAttachmentEntry();
    webAttachment.setTitle(new PlainTextConstruct(title));
    webAttachment.setSummary(new PlainTextConstruct(description));
    webAttachment.setContent(content);
    webAttachment.addLink(SitesLink.Rel.PARENT, Link.Type.ATOM,
    filecabinet.getSelfLink().getHref());

    return service.insert(new URL(getContentFeedUrl()), webAttachment);
    }

    /**
    * Updates an existing attachment with new content.
    *
    * @param entry Attachment entry to update.
    * @param newFile The replacement file content.
    * @return The created attachment.
    * @throws ServiceException
    * @throws IOException
    */
    public AttachmentEntry updateAttachment(AttachmentEntry entry, File newFile)
    throws IOException, ServiceException {
    return updateAttachment(entry, newFile, null, null);
    }

    /**
    * Updates an existing attachment's metadata.
    *
    * @param entry Attachment entry to update.
    * @param newTitle A new title for the attachment.
    * @param newDescription A new description for the attachment.
    * @return The created attachment.
    * @throws ServiceException
    * @throws IOException
    */
    public AttachmentEntry updateAttachment(AttachmentEntry entry, String newTitle,
    String newDescription) throws IOException, ServiceException {
    entry.setTitle(new PlainTextConstruct(newTitle));
    entry.setSummary(new PlainTextConstruct(newDescription));

    return entry.update();
    }

    /**
    * Updates an existing attachment's metadata and content.
    *
    * @param entry Attachment entry to update.
    * @param newFile The replacement file content.
    * @param newTitle A new title for the attachment.
    * @param newDescription A new description for the attachment.
    * @return The created attachment.
    * @throws ServiceException
    * @throws IOException
    */
    public AttachmentEntry updateAttachment(AttachmentEntry entry, File newFile,
    String newTitle, String newDescription) throws IOException, ServiceException {
    entry.setMediaSource(new MediaFileSource(newFile, mediaTypes.getContentType(newFile)));
    if (newTitle != null) {
    entry.setTitle(new PlainTextConstruct(newTitle));
    }
    if (newDescription != null) {
    entry.setSummary(new PlainTextConstruct(newDescription));
    }

    return entry.updateMedia(true);
    }

    }

    Wednesday, February 26, 2014

    Regex in java

    Radix sort in java

    Grouping of the items with their MSB and then compare and merge. The number of digits in each element should be made same. In the below example it is 2 ie, 3 = 03 or 8 = 08.


    import java.util.ArrayList;

    public class RadixSort {

    public void radixSort(int arr[], int maxDigits){
    int exp = 1;//10^0;
    for(int i =0; i < maxDigits; i++){
    ArrayList bucketList[] = new ArrayList[10];
    for(int k=0; k < 10; k++){
    bucketList[k] = new ArrayList();
    }
    for(int j =0; j < arr.length; j++){
    int number = (arr[j]/exp)%10;
    bucketList[number].add(arr[j]);
    }
    exp *= 10;
    int index =0;
    for(int k=0; k < 10; k++){
    for(int num: bucketList[k]){
    arr[index] = num;
    index++;
    }
    }
    }

    System.out.println("Sorted numbers");
    for(int i =0; i < arr.length; i++){
    System.out.print(arr[i] +", ");
    }
    }

    public static void main(String[] argv){
    int n = 5;
    int arr[] = {1,4,2,3,5,10,8};
    new RadixSort().radixSort(arr, 2);
    }
    }

    Merge sort in java

    Splitting the array into sets and compare / merge them during iterations. The time complexity is O(n log n) 
    import java.util.*;

    public class MergeSort {
    public static void main(String[] args) {
    int[] list = {14, 32, 67, 76, 23, 41, 58, 85};
    System.out.println("before: " + Arrays.toString(list));
    mergeSort(list);
    System.out.println("after: " + Arrays.toString(list));
    }

    // Places the elements of the given array into sorted order
    // using the merge sort algorithm.
    // post: array is in sorted (nondecreasing) order
    public static void mergeSort(int[] array) {
    if (array.length > 1) {
    // split array into two halves
    int[] left = leftHalf(array);
    int[] right = rightHalf(array);

    // recursively sort the two halves
    mergeSort(left);
    mergeSort(right);

    // merge the sorted halves into a sorted whole
    merge(array, left, right);
    }
    }

    // Returns the first half of the given array.
    public static int[] leftHalf(int[] array) {
    int size1 = array.length / 2;
    int[] left = new int[size1];
    for (int i = 0; i < size1; i++) {
    left[i] = array[i];
    }
    return left;
    }

    // Returns the second half of the given array.
    public static int[] rightHalf(int[] array) {
    int size1 = array.length / 2;
    int size2 = array.length - size1;
    int[] right = new int[size2];
    for (int i = 0; i < size2; i++) {
    right[i] = array[i + size1];
    }
    return right;
    }

    // Merges the given left and right arrays into the given
    // result array. Second, working version.
    // pre : result is empty; left/right are sorted
    // post: result contains result of merging sorted lists;
    public static void merge(int[] result,
    int[] left, int[] right) {
    int i1 = 0; // index into left array
    int i2 = 0; // index into right array

    for (int i = 0; i < result.length; i++) {
    if (i2 >= right.length || (i1 < left.length &&
    left[i1] <= right[i2])) {
    result[i] = left[i1]; // take from left
    i1++;
    } else {
    result[i] = right[i2]; // take from right
    i2++;
    }
    }
    }
    }

    Quick sort in java

    Input must be a list of distinct integers. Time complexity is O(n2
    import java.io.*;
    import java.util.*;

    public class QuickSort
    {
    public static void swap (int A[], int x, int y)
    {
    int temp = A[x];
    A[x] = A[y];
    A[y] = temp;
    }

    // Reorganizes the given list so all elements less than the first are
    // before it and all greater elements are after it.
    public static int partition(int A[], int f, int l)
    {
    int pivot = A[f];
    while (f < l)
    {
    if (A[f] == pivot || A[l] == pivot)
    {
    System.out.println("Only distinct integers allowed - C321");
    System.out.println("students should ignore this if statement");
    System.out.exit(0);
    }
    while (A[f] < pivot) f++;
    while (A[l] > pivot) l--;
    swap (A, f, l);
    }
    return f;
    }

    public static void Quicksort(int A[], int f, int l)
    {
    if (f >= l) return;
    int pivot_index = partition(A, f, l);
    Quicksort(A, f, pivot_index);
    Quicksort(A, pivot_index+1, l);
    }

    // Usage: java QuickSort [integer] ...
    // All integers must be distinct
    public static void main(String argv[])
    {
    int A[] = new int[argv.length];
    for (int i=0 ; i < argv.length ; i++)
    A[i] = Integer.parseInt(argv[i]);

    Quicksort(A, 0, argv.length-1);

    for (int i=0 ; i < argv.length ; i++) System.out.print(A[i] + " ");
    System.out.println();
    }
    }

    Selection sort in java

    The  first iteration will give the smallest number at the first end of the list. The elements starting from the first is compared / swapped with the rest of the positions.

    N-1 iterations for N items. Time complexity is O(n2)

    public class MySelectionSort {

    public static int[] doSelectionSort(int[] arr){

    for (int i = 0; i < arr.length - 1; i++)
    {
    int index = i;
    for (int j = i + 1; j < arr.length; j++)
    if (arr[j] < arr[index])
    index = j;

    int smallerNumber = arr[index];
    arr[index] = arr[i];
    arr[i] = smallerNumber;
    }
    return arr;
    }

    public static void main(String a[]){

    int[] arr1 = {10,34,2,56,7,67,88,42};
    int[] arr2 = doSelectionSort(arr1);
    for(int i:arr2){
    System.out.print(i);
    System.out.print(", ");
    }
    }
    }


    Output will be like



    2, 7, 10, 34, 42, 56, 67, 88, 

    Insertion sort in java

    Time complexity is O(n2)
    public class MyInsertionSort {

    public static void main(String[] args) {

    int[] input = { 4, 2, 9, 6, 23, 12, 34, 0, 1 };
    insertionSort(input);
    }

    private static void printNumbers(int[] input) {

    for (int i = 0; i < input.length; i++) {
    System.out.print(input[i] + ", ");
    }
    System.out.println("\n");
    }

    public static void insertionSort(int array[]) {
    int n = array.length;
    for (int j = 1; j < n; j++) {
    int key = array[j];
    int i = j-1;
    while ( (i > -1) && ( array [i] > key ) ) {
    array [i+1] = array [i];
    i--;
    }
    array[i+1] = key;
    printNumbers(array);
    }
    }
    }


    Output will be like:



    2, 4, 9, 6, 23, 12, 34, 0, 1, 

    2, 4, 9, 6, 23, 12, 34, 0, 1,

    2, 4, 6, 9, 23, 12, 34, 0, 1,

    2, 4, 6, 9, 23, 12, 34, 0, 1,

    2, 4, 6, 9, 12, 23, 34, 0, 1,

    2, 4, 6, 9, 12, 23, 34, 0, 1,

    0, 2, 4, 6, 9, 12, 23, 34, 1,

    0, 1, 2, 4, 6, 9, 12, 23, 34,

    Bubble sort in java

    The logic is to swap the 2 items in the list during iterations. At the end of first iteration the list will have the largest no. at the end.

    n-1 iterations for n items. Time complexity is O(n2)

    import java.util.Scanner;

    class BubbleSort {
    public static void main(String []args) {
    int n, c, d, swap;
    Scanner in = new Scanner(System.in);

    System.out.println("Input number of integers to sort");
    n = in.nextInt();

    int array[] = new int[n];

    System.out.println("Enter " + n + " integers");

    for (c = 0; c < n; c++)
    array[c] = in.nextInt();

    for (c = 0; c < ( n - 1 ); c++) {
    for (d = 0; d < n - c - 1; d++) {
    if (array[d] > array[d+1]) /* For descending order use < */
    {
    swap = array[d];
    array[d] = array[d+1];
    array[d+1] = swap;
    }
    }
    }

    System.out.println("Sorted list of numbers");

    for (c = 0; c < n; c++)
    System.out.println(array[c]);
    }
    }


    Output will be like:



    op

    Friday, February 21, 2014

    IndexOf Logic in Java

    Logic of the following function:

    IndexOf(String,Sub String) – Gives the position of the first occurrence of the substring.

    Please check and comment.

    import java.io.IOException;
    import javax.servlet.http.*;

    @SuppressWarnings("serial")
    public class TestIndexOf extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws IOException {
    resp.setContentType("text/plain");
    resp.getWriter().println("String IndexOf Implementation...");

    resp.getWriter().println("Pos = " + IndexOf("Hello Jeetu", "llo"));

    }

    public int IndexOf(String main, String sub) {

    char[] mainc = main.toCharArray();
    char[] subc = sub.toCharArray();

    for (int i = 0; i < mainc.length; i++) {
    if (mainc[i] == subc[0]) {
    for (int j = 0; j < subc.length; j++) {
    if (mainc[i + j] != subc[j])
    break;
    else if (j == subc.length - 1)
    return i + 1;
    }

    }
    }
    return -1;
    }
    }