Latest Entries »

Tuesday, October 25, 2011

Android HTML parser in less than 5 minutes.

Yes it's true. You can create a simple application that parse a html document and get all data you need in less than 5 minutes.

Introduction

In this tutorial I will use standalone Java SE parser called Jsoup. We have few jsoup files available:

In android world size matter so I want only my jsoup-1.6.1-sources.jar. So far jar is an archive so I use 7-zip to extract content of  jsoup-1.6.1-sources.jar into folder. Next thing is to create Android Application from Eclipse IDE. 
After extracting sources from jsoup you should copy all directories inside your src folder. You should have similar application structure:




public class HtmlAParseActivity extends Activity {
 EditText text1;
 Button btn1;

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  text1 = (EditText) findViewById(R.id.editText1);
  btn1 = (Button) findViewById(R.id.button1);
  btn1.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    Document doc;
    try {
     doc = Jsoup.connect(text1.getText().toString()).get();
     Elements links = doc.select("a[href]");
     Elements media = doc.select("[src]");
     Elements imports = doc.select("link[href]");
     print("\nMedia: (%d)", media.size());
     for (Element src : media) {
      if (src.tagName().equals("img"))
       print(" * %s: <%s> %sx%s (%s)", src.tagName(),
         src.attr("abs:src"), src.attr("width"),
         src.attr("height"),
         trim(src.attr("alt"), 20));
      else
       print(" * %s: <%s>", src.tagName(),
         src.attr("abs:src"));
     }

     print("\nImports: (%d)", imports.size());
     for (Element link : imports) {
      print(" * %s <%s> (%s)", link.tagName(),
        link.attr("abs:href"), link.attr("rel"));
     }

     print("\nLinks: (%d)", links.size());
     for (Element link : links) {
      print(" * a: <%s>  (%s)", link.attr("abs:href"),
        trim(link.text(), 35));
     }
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }

   }
  });
 }

 private static void print(String msg, Object... args) {
  System.out.println(String.format(msg, args));
 }

 private static String trim(String s, int width) {
  if (s.length() > width)
   return s.substring(0, width - 1) + ".";
  else
   return s;
 }
}
Of course don't forget to add permission for internet connection.

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.persmission.ACCESS_NETWORK_STATE" />

Code in HtmlAParseActivity  was from org.jsoup.example package with some modifications.

Thats all.

Tuesday, September 27, 2011

Insert Update row with MERGE keyword SQL 2008

Few days ago I've got question how to perform insert/update taks in one query. I couldn't answer because I've never used MERGE in SQL 2008 Server. With my curiosity I make reaserch and google and found a solution. Furthermore almost all examples about MERGE was connected with two tables joining by PK-FK but I needed MERGE with one table. For show this query let first prepare a simple table:
CREATE TABLE [dbo].[Target](
	[EmployeeID] [int] IDENTITY(1,1) NOT NULL,
	[EmployeeName] [nvarchar](500) NOT NULL,
 CONSTRAINT [PK_Target] PRIMARY KEY CLUSTERED 
(
	[EmployeeID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,
 ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

Now It's time for write stored procedure that takes adventage of MERGE.

ALTER PROCEDURE [dbo].[TargetInsertUpdate]
(
   @EmployeeID INT,
   @EmployeeName NVARCHAR(500),
   @NewEmployeeID   int OUTPUT
)
AS
SET NOCOUNT ON


MERGE dbo.[Target]  T
-- To check if row is in database we put
-- existing row data inside USING (Source table )(S)
-- if row exists then name is updated
-- otherwise new row is added
-- and @NewEmployeeID indicates newly added ID
USING (SELECT @EmployeeID as EmployeeID,@EmployeeName as EmployeeName) as S
ON T.EmployeeID = S.EmployeeID
WHEN NOT MATCHED BY TARGET THEN
INSERT(EmployeeName) VALUES(S.EmployeeName)
WHEN MATCHED THEN
UPDATE SET T.EmployeeName = S.EmployeeName;

SET @NewEmployeeID = scope_identity()
GO

Monday, June 20, 2011

How to Send Email via Java Mail, CKEditor with NetBeans IDE

This post is copy of my article from here.


Introduction

In this tutorial I will show you how to create a simple JFrame to send email containing HTML content:

This article is divided into several parts, covering topics from the writing of simple e-mail sender Java classes to the integration of a JFrame with CKEditor, which is a rich web HTML editor.


Downloading and Registering Libraries in NetBeans IDE 6.8

First of all, you need to download the latest version of Java Mail from this page, as well as DJ Native Swing. After you download the libraries, you need to put them into the NetBeans Library Manager. I recommend you store all libraries in, for example, C:\Program Files\Java\libraries.


Creating a Java Application and Adding Libraries to the Project

Take the following steps to begin creating the application:
  1. Choose File -> New Project -> Java Application. Click Next.
  2. When Name and Location Window shows up, name your project FCKEditorEmailSender and uncheck Create Main Class so that you end up creating an empty project. Click Finish.
  3. In the Projects Tab click right click Libraries and Add Library from the menu. Then select the libraries which you added from Library Manager. You should have now Java Mail and DJNativeSwing JAR files. Your project should now look like the image shown below:


Creating the Package and Java Classes

Now let's do the real coding work. Go to the project you created and then create a package named EmailSender. In this package, create a Java class named EmailSender (the same name, don't worry) from the New File dialog. In the class, create private fields as shown below:
public class EmailSender {
  private String smtpServer;
  private String port;
  private String user;
  private String password;
  private String auth;
  private String from;
Provide a simple constructor by pressing ALT + INSERT and selecting Constructor... . Select all the fields in the window.

To enable the sending of e-mails by the Java Mail API, you need to create a Properties object where you put all the needed information about SMTP session, such as the server, port, and user. For this purpose create the following method: 
private Properties prepareProperties()
Next, when you prepare the Properties object, you can simply model an email message. This method returns a MimeMessage (which stands for Multipurpose Internet Mail Extensions Message Class). Then create this method:
private MimeMessage prepareMessage(Session mailSession,String charset,
String from, String subject,
String HtmlMessage,String[] recipient) 
The next step about sending emails via Internet involves creating a method for sending HTML content messages. Create this method:
public void sendEmail(String subject,String HtmlMessage,String[] to) 
Now we add the implementations of the methods shown above:
private Properties prepareProperties()
{
   Properties props = new Properties();
   props.setProperty("mail.smtp.host", smtpServer);
   props.setProperty("mail.smtp.port", port);
   props.setProperty("mail.smtp.user", user);
   props.setProperty("mail.smtp.password", password);
   props.setProperty("mail.smtp.auth", auth);
   return props;
}
private MimeMessage prepareMessage(Session mailSession,String charset,
                                        String from, String subject,
                                        String HtmlMessage,String[] recipient) {
        //Multipurpose Internet Mail Extensions
        MimeMessage message = null;
        try {
            message = new MimeMessage(mailSession);
            message.setFrom(new InternetAddress(from));
            message.setSubject(subject);
            for (int i=0;i<recipient.length;i++)
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient[i]));
            message.setContent(HtmlMessage, "text/html; charset=\""+charset+"\"");
        } catch (Exception ex) {
            Logger.getLogger(EmailSender.class.getName()).log(Level.SEVERE, null, ex);
        }
        return message;
    }
public void sendEmail(String subject,String HtmlMessage,String[] to)
    {
        Transport transport = null;
        try {
            Properties props = prepareProperties();
            Session mailSession = Session.getDefaultInstance(
                            props, new SMTPAuthenticator(from, password, true));
            transport =  mailSession.getTransport("smtp");
            MimeMessage message = prepareMessage(mailSession, "ISO-8859-2",
                                                from, subject, HtmlMessage, to);
            transport.connect();
            Transport.send(message);
        } catch (Exception ex) {    
        }
        finally{
            try {
                transport.close();
            } catch (MessagingException ex) {
                Logger.getLogger(EmailSender.class.getName()).
                                                    log(Level.SEVERE, null, ex);
            }
        }
    }
package EmailSender;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

public class SMTPAuthenticator extends Authenticator{
    private String username;
    private String password;
    private boolean needAuth;

    public SMTPAuthenticator(String username, String password,boolean needAuth)
    {
        this.username = username;
        this.password = password;
        this.needAuth = needAuth;
    }

    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        if (needAuth)
            return new PasswordAuthentication(username, password);
                else return null;
    }
}


Creating a Swing Form to Provide a Nice GUI

Now that we have finished the e-mail work, we concentrate on the Swing and FCKEditor integration. You need to click right button over package EmailSender and choose New -> JFrame Form, call this class SendEmail and put this class in EmailSender package. Now right click over JFrame Design View and select: Set Layout -> Border Layout.
Now when you try to drop JPanel from Pallete into Design View you will see a few borders which are simpy Content Holders of Border Layout. Please read about BorderLayout from official Java Docs. Click Panel from Pallete and drop panel as is in image below. In this area you will next put controls to get smtp values.
Now right click over the panel above and select : Set Layout -> Null Layout. This will make your controls not floating when user will resize window and secondly controls will be in the same position as it was created in Design view. Test with some diffrent Layouts when you run your application to see what will happen :) Now you will need to create buttons to interact with user. Put new JPanel into lower "Place holder".
Add the two buttons:
And we are close to finishing the tutorial. Last thing to do is put FCKEditor in main method. Modify your:
public static void main(String[] args) 
    UIUtils.setPreferredLookAndFeel();
    NativeInterface.open();
    final String configurationScript =
      "FCKConfig.ToolbarSets[\"Default\"] = [\n" +
      "['Source','DocProps','-','Save','NewPage','Preview','-','Templates'],\n" +
      "['Cut','Copy','Paste','PasteText','PasteWord','-','Print','SpellCheck'],\n" +
      "['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'],\n" +
      "['Form','Checkbox','Radio','TextField','Textarea','Select','Button','ImageButton','HiddenField'],\n" +
      "'/',\n" +
      "['Style','FontFormat','FontName','FontSize'],\n" +
      "['TextColor','BGColor'],\n" +
      "'/',\n" +
      "['Bold','Italic','Underline','StrikeThrough','-','Subscript','Superscript'],\n" +
      "['OrderedList','UnorderedList','-','Outdent','Indent','Blockquote'],\n" +
      "['JustifyLeft','JustifyCenter','JustifyRight','JustifyFull'],\n" +
      "['Link','Unlink','Anchor'],\n" +
      "['Image','Flash','Table','Rule','Smiley','SpecialChar','PageBreak', '-', 'ShowBlocks'],\n" +
      "];\n" +
      "FCKConfig.ToolbarCanCollapse = false;\n";
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                htmlEditor = new JHTMLEditor(HTMLEditorImplementation.FCKEditor,
JHTMLEditor.FCKEditorOptions.setCustomJavascriptConfiguration(configurationScript));
                SendEmail es2 = new SendEmail();
                es2.setSize(new Dimension(800,600));
                es2.add(htmlEditor,BorderLayout.CENTER);
                es2.setLocationByPlatform(true);
                es2.setVisible(true);
            }
        });
    }
Now when you replace main method go to your Design View and double click both buttons to generate actionPerformed . Put this codes into proper buttons.Notice that I used code below to provide new Thread to prevent block Graphical User Interface during send e-mail:
javax.swing.SwingUtilities.invokeLater(new Runnable() {
  public void run() {
    emailer.sendEmail(subject.getText(),
    htmlEditor.getHTMLContent(),
    recipientsString); 
    }
});  
private void sendEmailActionPerformed(java.awt.event.ActionEvent evt) {                                          
        // TODO add your handling code here:
                StringTokenizer recepientsTokenizer = new StringTokenizer(to.getText(), ",");
                final String[] recipientsString = new String[recepientsTokenizer.countTokens()];
                for (int i = 0; i < recipientsString.length; i++) {
                    recipientsString[i] = recepientsTokenizer.nextToken();
                }
                 final EmailSender emailer = new EmailSender(smtpServer.getText(),
                        port.getText(), username.getText(),
                        password.getPassword().toString(),
                        "true", from.getText());
              javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                emailer.sendEmail(subject.getText(),
                        htmlEditor.getHTMLContent(),
                        recipientsString);
            }
        });
    }
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
  // TODO add your handling code here:
  dispose();
} 
Now you can build your project and show off to your friends :)
Here you can download the packed NetBeans project.
Tip:
When you download DJ Native you can double-click the DJNativeSwing-SWTDemo.jar to look closer into the various amazing classesm such as JWebBrowser JHtmlEditor with different HtmlEditors.

After many reqests for source code of project which was unavailable due to closed magaupload I uploaded project one time more. So I Uploaded again source code. 

Thursday, June 16, 2011

Persist checkbox client side row selection inside GridView in asp:UpdatePanel

Comming Soon :-) //After defend my thesis.

Monday, June 13, 2011

Disappearing content in FCKEditor after mode change.

Comming soon :-)