Friday, December 30, 2016

TinyMCE Get Word Counts Using jQuery

Sample code snippet (Full TinyMCE Example)

var log = $(".log"), previous_content = "";
var plugins = [
    "advlist autolink autosave link image lists charmap print preview hr anchor pagebreak spellchecker",
    "searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking",
    "table contextmenu directionality emoticons template textcolor paste fullpage textcolor colorpicker textpattern"
];
tinymce.init({
    selector: ".rich_editor",
    setup: function (editor) {
        editor.on('change redo undo', function () {
            editor.save();
            var body = tinymce.activeEditor.getBody();
            var content = tinymce.trim(body.innerText || body.textContent);
            if(content != previous_content) {
                content = $.trim(content.replace( /[^\w ]/g, " "));
                var word_count = content == "" ? 0 : content.split( /\s+/ ).length;
                log.prepend("Word_Count=" + word_count + "<br/>");
                log.prepend("Editor_Text=" + content + "<br/>");
                previous_content = content;
            }
        });
    }
});

Sample output


Simple TineMCE Editor Example With jQuery

Download full example from here

Sample code snippet


var plugins = [
    "advlist autolink autosave link image lists charmap print preview hr anchor pagebreak spellchecker aa_custom_text aa_inline_image",
    "searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking",
    "table contextmenu directionality emoticons template textcolor paste fullpage textcolor colorpicker textpattern"
];
tinymce.init({
    selector: "textarea.rich_editor",
    height: 400,
    plugins: plugins,
    contextmenu: "link image inserttable | cell row column deletetable",

    toolbar1: "newdocument | aa_custom_text aa_inline_image | bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | styleselect formatselect fontselect fontsizeselect",
    toolbar2: "cut copy paste | searchreplace | bullist numlist | outdent indent blockquote | undo redo | link unlink anchor image media code | insertdatetime preview | forecolor backcolor",
    toolbar3: "table | hr removeformat code | subscript superscript | charmap emoticons | print fullscreen | ltr rtl | spellchecker | visualchars visualblocks nonbreaking template pagebreak restoredraft",

    menubar: false,
    statusbar: false,
    toolbar_items_size: 'small'
});

Sample output


How to insert an item into an array at a specific index javascript

var arr = ["X1", "X2", "X3", "X4", "X5"];

Inserting "X2.2" into position "2" without deleting "0" item
arr.splice(2, 0, "X2.2");

First Array Values:
X1,   X2,   X3,   X4,   X5

After insert new value:
X1,   X2,   X2.2,   X3,   X4,   X5

Create GUID / UUID in JavaScript


<script type="text/javascript">
    function guid() {
        function s4() {
            return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
        }

        return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
    }
    alert(guid());
</script>

Thursday, December 22, 2016

jQuery Check if element is visible after scrolling

Html Part:

<script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<table style="width:100%;padding-top:100px;">
    <tr>
        <td style="width:50%;vertical-align:top">
            <h3>Partial Visibility Check</h3>

            <div class="scroll" style="height:320px;overflow:auto;border:1px solid blue;position:relative">
                <div class="check d1" style="height:100px;border:1px solid red">DIV 1</div>
                <div class="check d2" style="height:100px;border:1px solid red">DIV 2</div>
                <div class="check d3" style="height:100px;border:1px solid red">DIV 3</div>
                <div class="check d4" style="height:100px;border:10px solid red;padding-top:20px">DIV 4</div>
                <div style='padding:20px;position:relative;border:2px solid green;'>
                    <div style='border:2px solid blue;padding:30px;'>
                        <div class="check d5" style="height:100px;border:1px solid red">DIV 5</div>
                    </div>
                </div>
                <div class="check d6" style="height:100px;border:1px solid red">DIV 6</div>
                <div class="check d7" style="height:100px;border:1px solid red">DIV 7</div>
                <div class="check d8" style="height:100px;border:1px solid red">DIV 8</div>
            </div>
            <div class="log" style='height:140px;overflow:hidden'></div>
        </td>
        <td style="width:50%;vertical-align:top">
            <h3>Fully Visibility Check</h3>

            <div class="scroll full" style="height:320px;overflow:auto;border:1px solid blue;position:relative">
                <div style="height:3px"></div>
                <div class="check d1" style="height:100px;border:1px solid red">DIV 1</div>
                <div class="check d2" style="height:100px;border:1px solid red">DIV 2</div>
                <div class="check d3" style="height:100px;border:1px solid red">DIV 3</div>
                <div class="check d4" style="height:100px;border:1px solid red">DIV 4</div>
                <div class="check d5" style="height:100px;border:1px solid red">DIV 5</div>
                <div class="check d6" style="height:100px;border:1px solid red">DIV 6</div>
                <div class="check d7" style="height:100px;border:1px solid red">DIV 7</div>
                <div style="height:3px"></div>
            </div>
            <div class="log" style='height:128px;overflow:hidden'></div>
        </td>
    </tr>
</table>

jQuery Part:

var log = {};
$("div.scroll").scroll(function () {
    var boundary = $(this), block = boundary.closest("td"), full_view = boundary.hasClass("full");
    log = block.find(".log");
    boundary.find(".check").not(".visited").each(function () {
        var elem = $(this);
        var visited = isScrolledIntoView(boundary, elem, full_view);
        if (visited) {
            log.prepend("DIV.CLASS=\"" + elem.attr("class") + "\" VISITED<br/>");
        }
        else {
            log.prepend("DIV.CLASS=\"" + elem.attr("class") + "\" NOT VISITED<br/>");
        }
    });
});

function isScrolledIntoView(c, e, full_view) {
    var op = e[0].getBoundingClientRect().top - c[0].getBoundingClientRect().top;
    var oh = op + e[0].getBoundingClientRect().height;
    var v1 = c.height() > op && op >= 0;
    var v2 = oh <= c.height() && oh >= 0;
    return full_view === true ? (v1 && v2) : (v1 || v2);
}

Screenshot:




jQuery detect when user stops scrolling

<div class="scroll" style="height:300px;overflow:auto;border:1px solid blue">
    <div style="height:1000px"></div>
</div>
<div class="log"></div>

<script type="text/javascript">
    $("div.scroll").scroll(function() {
        clearTimeout($.data(this, 'scrollTimer'));
        $.data(this, 'scrollTimer', setTimeout(function() {
            $("div.log").prepend("Haven't scrolled in 250ms!<br/>");
        }, 250));
    });
</script>


Monday, December 19, 2016

Java Send Email Using Office 365 OAuth Connection

Download source code from here

To get oauth access token & other information used in this code snippet visit:
http://pritomkumar.blogspot.com/2016/11/write-php-app-to-get-outlook-office-365.html



package com.pkm.office_oauth;

import com.google.gson.Gson;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;

/**
 * Created by pritom on 18/12/2016.
 */
public class JavaSendMailUsingOffice365OAuth {
    private static final String OFFICE_ACCESS_TOKEN = "xxxxx";
    private static String mailUUID = "";

    /**
     * API URL
     * https://msdn.microsoft.com/en-us/office/office365/api/complex-types-for-mail-contacts-calendar#MessageResource
     * https://msdn.microsoft.com/en-us/office/office365/api/extended-properties-rest-operations
     */

    public static void main(String[] args) throws Exception {
        send();
    }

    private static void send() throws Exception {
        Map<String, Object> message = new HashMap<>();
        message.put("Subject", "Some Sample Subject");
        message.put("Body", getBody());
        addRecipients(message);
        addCustomHeader(message);
        addAttachment(message);

        Map<String, Map> messagePayload = new HashMap<>();
        messagePayload.put("Message", message);

        Gson gson = new Gson();
        String messageAsJson = gson.toJson(messagePayload);

        List<String> headers = new ArrayList<>();
        headers.add("Authorization: Bearer " + OFFICE_ACCESS_TOKEN);
        headers.add("Accept: application/json");
        headers.add("Content-Type: application/json");
        headers.add("Content-Length: " + messageAsJson.length());

        String url = "https://outlook.office.com/api/v2.0/me/sendmail";
        JavaSendMailUsingOffice365OAuth.Response response = executeSend(url, messageAsJson, headers);
        System.out.println("STATUS_CODE=" + response.httpCode);
        if (response.httpCode == 202) {
            System.out.println("MESSAGE SENT\r\n\r\nTRY TO RETRIEVE MAIL SENT");
            filterMessageSent();
        }
        else {
            System.out.println(response);
        }
    }

    private static void filterMessageSent() throws Exception {
        String query = "SingleValueExtendedProperties/Any" +
                URLEncoder.encode("(ep: ep/PropertyId eq 'String {" + mailUUID + "} Name CUSTOM_HEADER_1' and ep/Value eq 'CUSTOM_HEADER_1_VALUE_" + mailUUID + "')", "UTF-8");
        String select = "Id,InternetMessageId";
        String url = "https://outlook.office.com/api/v2.0/me/messages?$filter=" + query + "&$select=" + select;

        List<String> headers = new ArrayList<>();
        headers.add("Authorization: Bearer " + OFFICE_ACCESS_TOKEN);
        headers.add("Accept: application/json");
        JavaSendMailUsingOffice365OAuth.Response response = executeSend(url, "", headers);
        if (response.httpCode == 200) {
            Map result = new Gson().fromJson(response.httpResponse, Map.class);
            result = (Map) ((List) result.get("value")).get(0);
            System.out.println("UNIQUE_OFFICE_MAIL_ID_OF_SEND_EMAIL=" + result.get("Id"));
            System.out.println("UNIQUE_MESSAGE_ID_OF_SEND_EMAIL=" + result.get("InternetMessageId"));
        }
    }

    private static void addCustomHeader(Map<String, Object> message) {
        List<Map> list = new ArrayList<>();
        mailUUID = UUID.randomUUID().toString();

        Map<String, String> val1 = new HashMap<>();
        val1.put("PropertyId", "String {" + mailUUID + "} Name CUSTOM_HEADER_1");
        val1.put("Value", "CUSTOM_HEADER_1_VALUE_" + mailUUID);

        list.add(val1);

        message.put("SingleValueExtendedProperties", list);
    }

    private static JavaSendMailUsingOffice365OAuth.Response executeSend(String url, String messageAsJson, List<String> headers) throws Exception {
        int httpCode = 0, timeOutMilli = 1000 * 30;;
        String httpResponse = "", responseMessage = "";

        HttpURLConnection connection = null;
        try {
            System.setProperty("https.protocols", "TLSv1.1,SSLv3,SSLv2Hello");
            connection = (HttpURLConnection) new URL(url).openConnection();
            if (messageAsJson.length() > 0) {
                connection.setRequestMethod("POST");
            }
            else {
                connection.setRequestMethod("GET");
            }
            connection.setDoOutput(true);
            connection.setConnectTimeout(timeOutMilli);
            connection.setReadTimeout(timeOutMilli);
            connection.setRequestProperty("Pragma", "no-cache");

            for (int i = 0; i < headers.size(); i++) {
                String header = headers.get(i);
                connection.setRequestProperty(header.substring(0, header.indexOf(":")), header.substring(header.indexOf(":") + 1));
            }

            if (messageAsJson.length() > 0) {
                connection.setDoInput(true);
                OutputStreamWriter streamWriter = new OutputStreamWriter(connection.getOutputStream());
                streamWriter.write(messageAsJson);
                streamWriter.flush();
                streamWriter.close();
            }

            httpCode = connection.getResponseCode();
            responseMessage = connection.getResponseMessage();
            InputStream inputStream = null;

            if (httpCode >= 200 && httpCode <= 399) {
                inputStream = connection.getInputStream();
            }
            else {
                inputStream = connection.getErrorStream();
            }

            if (inputStream != null) {
                Writer writer = new StringWriter();
                char[] buffer = new char[1024];
                Reader reader = new BufferedReader(new InputStreamReader(inputStream));
                int n;
                while ((n = reader.read(buffer)) != -1) {
                    writer.write(buffer, 0, n);
                }
                httpResponse = writer.toString();
            }
        }
        catch (Exception ex) {
            ex.printStackTrace();
            responseMessage = ex.getMessage();
        }
        return new JavaSendMailUsingOffice365OAuth.Response(httpCode, responseMessage, httpResponse);
    }

    private static Map<String, Object> getBody() throws Exception {
        Map<String, Object> body = new HashMap<>();

        body.put("ContentType", "HTML");
        body.put("Content", new String("<DIV><B>HTML BODY CONTENT</B></DIV>".getBytes(), "UTF-8"));

        return body;
    }

    private static void addRecipients(Map<String, Object> message) {
        Map<String, Map> recipientMap = new HashMap<>();
        Map<String, String> recipientAddress = new HashMap<>();
        recipientAddress.put("Address", "pritom@xxxxx.com");
        recipientMap.put("EmailAddress", recipientAddress);

        List<Map> recipients = new ArrayList<>();
        recipients.add(recipientMap);

        message.put("ToRecipients", recipients);
    }

    private static void addAttachment(Map<String, Object> message) throws Exception {
        List<Map> attachments = new ArrayList<>();

        File file = new File("src/com/pkm/office_oauth/Attachment_Image_1.png");
        FileInputStream fileInputStream = new FileInputStream(file);
        byte[] toByte = new byte[(int) file.length()];
        fileInputStream.read(toByte);
        fileInputStream.close();

        file = new File("src/com/pkm/office_oauth/Attachment_Pdf_1.pdf");
        fileInputStream = new FileInputStream(file);
        toByte = new byte[(int) file.length()];
        fileInputStream.read(toByte);
        fileInputStream.close();

        Map<String, Object> attachment = new HashMap<>();
        attachment.put("@odata.type", "#Microsoft.OutlookServices.FileAttachment");
        attachment.put("Name", file.getName());
        attachment.put("ContentBytes", encodeBase64(toByte));

        attachments.add(attachment);
        message.put("Attachments", attachments);
    }

    private static String encodeBase64(byte[] bytes) throws Exception {
        BASE64Encoder base64Encoder = new BASE64Encoder();
        return base64Encoder.encodeBuffer(bytes);
    }

    private static class Response {
        int httpCode = 0;
        String httpResponse = "", responseMessage = "";

        public Response(int httpCode, String responseMessage, String httpResponse) {
            this.httpCode = httpCode;
            this.responseMessage = responseMessage;
            this.httpResponse = httpResponse;
        }

        public String toString() {
            Map<String, Object> output = new HashMap<>();
            output.put("httpCode", httpCode);
            output.put("responseMessage", responseMessage);
            output.put("httpResponse", httpResponse);
            return new Gson().toJson(output);
        }
    }
}