<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>
Friday, December 30, 2016
Create GUID / UUID in JavaScript
Thursday, December 22, 2016
jQuery Check if element is visible after scrolling
Html Part:
jQuery Part:
Screenshot:
<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
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); } } }
Sunday, December 18, 2016
Start watch form field change listener - Angular JS
Download full example code from here
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Start watch form field change listener - Angular JS</title> <script type="text/javascript" src="jquery-min.js"></script> <script type="text/javascript" src="angular.js"></script> </head> <body> <div data-ng-app="myApp" data-ng-controller="MyCtrl"> <form name="myForm"> <table> <tr> <td>Name</td> <td><input type="text" data-ng-model="dataObject.Name"></td> </tr> <tr> <td>Group</td> <td> <select data-ng-model="dataObject.Group"> <option value="GROUP_1">Group 1</option> <option value="GROUP_2">Group 2</option> <option value="GROUP_3">Group 3</option> </select> </td> </tr> <tr> <td>Radio</td> <td> <input type="radio" data-ng-model="dataObject.Radio" value="1"/> <input type="radio" data-ng-model="dataObject.Radio" value="2"/> </td> </tr> <tr> <td>Checkbox</td> <td> <label ng-repeat="Option in Options"> <input type="checkbox" name="OptionValues[]" value="{{Option.Id}}" ng-model="Option.Checked"> {{Option.Name}} </label> </td> </tr> <tr> <td>Type</td> <td><input type="text" data-ng-model="Type"></td> </tr> </table> <div class="log"></div> </form> </div> <script type="text/javascript"> var myApp = angular.module('myApp', []), log = $(".log"); myApp.controller('MyCtrl', ['$scope', function($scope) { /* Start watching Object */ $scope.dataObject = {Name: "", Group: "GROUP_1", Radio: "1"}; $scope.$watch('dataObject', function(newVal, oldVal) { $scope.printChangedField(newVal, oldVal); }, true); $scope.printChangedField = function(newVal, oldVal) { Object.keys(oldVal).forEach(function (key) { if(newVal[key] != oldVal[key]) { log.prepend('Field \"' + key + '\" Changed From=\"' + oldVal[key] + '\" To=\"' + newVal[key] + '\"<BR>'); } }); }; /* Start watching checkboxes */ $scope.Options = [ {Id: 1, Name: "One", Checked: true}, {Id: 2, Name: "Two", Checked: false}, {Id: 3, Name: "Three", Checked: true} ]; $scope.OldOptions = []; $scope.$watch('Options', function (nv) { $scope.NewOptions = $.grep(nv.map(function (Option) { return Option.Checked ? Option.Name : null; }), function(Name) { return Name != null; }); log.prepend('Field \"Options\" Changed From=\"' + $scope.OldOptions + '\" To=\"' + $scope.NewOptions + '\"<BR>'); $scope.OldOptions = $scope.NewOptions; }, true); /* Start watching specific field */ $scope.Type = ""; $scope.$watch('Type', function(newVal, oldVal) { if(newVal != oldVal) { log.prepend('Field \"Type\" Changed From=\"' + oldVal + '\" To=\"' + newVal + '\"<BR>'); } }, true); }]); </script> </body> </html>
Sample Example:
Send Email Using Google OAuth & Java
Download source code & required jars from here
For get access token & google user id click here
package com.pkm.google_auth; import com.google.api.client.googleapis.GoogleUtils; import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; 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.client.repackaged.org.apache.commons.codec.binary.Base64; import com.google.api.services.gmail.Gmail; import com.google.api.services.gmail.model.MessagePartHeader; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.Multipart; import javax.mail.Session; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import java.io.ByteArrayOutputStream; import java.util.Properties; /** * Created by pritom on 18/12/2016. */ public class SendMail { private static final String USER_ID = "118224585672607576118"; private static final String ACCESS_TOKEN = "ya29.Ci-4A700L53csid7qv6786780mbRqI8hdwesj7H2RSRnBizwfWFUY0pzYsx_xa-XZA"; public static void main(String[] args) throws Exception { sendMail(); } private static void sendMail() throws Exception { Properties props = new Properties(); Session mailSession = Session.getInstance(props, new javax.mail.Authenticator() { }); MimeMessage message = new MimeMessage(mailSession); message.setSubject("Test subject", "UTF-8"); message.addRecipient(Message.RecipientType.TO, new InternetAddress("pritom@xxxxx.com", "Pritom Kumar")); Multipart multipart = new MimeMultipart(); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent("<DIV><B>BOLD HTML BODY</B></DIV>", "text/html"); multipart.addBodyPart(messageBodyPart); message.addHeader("CUSTOM_HEADER_1", "CUSTOM_HEADER_1_VALUE"); message.addHeader("CUSTOM_HEADER_2", "CUSTOM_HEADER_2_VALUE"); message.setContent(multipart ); GoogleCredential credential = new GoogleCredential().setAccessToken(ACCESS_TOKEN); Gmail gmail = new Gmail.Builder(_createHttpTransport(), _createJsonFactory(), credential).build(); com.google.api.services.gmail.model.Message email = createMessageWithEmail(message); email = gmail.users().messages().send(USER_ID, email).execute(); String emailID = email.getId(), messageID = getUniqueMessageIDByEMailId(emailID); System.out.println("EMAIL_SEND_WITH_GOOGLE_MAIL_ID=" + emailID); System.out.println("EMAIL_SEND_WITH_UNIQUE_MAIL_ID=" + messageID); } private static String getUniqueMessageIDByEMailId(String emailID) throws Exception { GoogleCredential credential = new GoogleCredential().setAccessToken(ACCESS_TOKEN); Gmail gmail = new Gmail.Builder(_createHttpTransport(), _createJsonFactory(), credential).build(); com.google.api.services.gmail.model.Message message = gmail.users().messages().get(USER_ID, emailID).execute(); for (MessagePartHeader messagePartHeader : message.getPayload().getHeaders()) { if (messagePartHeader.getName().equalsIgnoreCase("Message-ID")) { emailID = messagePartHeader.getValue().substring(1, messagePartHeader.getValue().length() - 1); } } return emailID; } private static com.google.api.services.gmail.model.Message createMessageWithEmail(MimeMessage email) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); email.writeTo(baos); String encodedEmail = Base64.encodeBase64URLSafeString(baos.toByteArray()); com.google.api.services.gmail.model.Message message = new com.google.api.services.gmail.model.Message(); message.setRaw(encodedEmail); return message; } private static HttpTransport _createHttpTransport() throws Exception { return new NetHttpTransport.Builder() .trustCertificates(GoogleUtils.getCertificateTrustStore()) .build(); } private static JsonFactory _createJsonFactory() { return new JacksonFactory(); } }
Saturday, December 17, 2016
Decoding UTF-8 email subject
In MIME terminology, those encoded chunks are called encoded-words. Check out
javax.mail.internet.MimeUtility.decodeText in JavaMail. The decodeText method will decode all the encoded-words in a string.You need to download javax.mail.jar from web. |
Subscribe to:
Posts (Atom)