<?php $mobil = array( "jalan" => function($nomor_sim){ if($nomor_sim){ return "Caaw !"; }else{ return "Anda tidak punya SIM !"; } }, "berhenti" => function(){ return "Matikan mesin ..."; } ); echo $mobil['jalan'](); // Anda tidak punya SIM echo $mobil['jalan']("SIM123"); // Caaw ! echo $mobil['berhenti'](); // Matikan mesin ... ?>#php #nice #enlightenment #script
package main import ( "fmt" "github.com/gorilla/mux" "github.com/gorilla/sessions" // "github.com/fzzy/radix/redis" // "github.com/fatih/structs" "net" "net/http" "html/template" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" "regexp" "strings" "crypto/rand" "time" "strconv" // "encoding/json" // "reflect" ) var ( // MongoDB mongoConfig = "mongodb://localhost:27017/admin" MongoSession, err = mgo.Dial(mongoConfig) MDB = MongoSession.DB("admin") BlogCol = MDB.C("blog") UserCol = MDB.C("user") // Session store = sessions.NewCookieStore([]byte("something-very-secret")) // Blog skipHome = 0 limit = 10 rowsNum = 10 // Tag Factory tagPattern = "#([a-z]|[A-Z]|[_])+" // Path templatePath = "D:\\PROJECTS\\GO-APP\\webkoe\\templates\\" publicPath = "D:\\PROJECTS\\GO-APP\\webkoe\\public\\" ) func cekKodeJabatan(r *http.Request) string { session,_ := store.Get(r, "session-name") kode_jabatan := fmt.Sprintf("%s", session.Values["kode_jabatan"]) return kode_jabatan } func SmsHomeHandler(w http.ResponseWriter, r *http.Request) { if cekKodeJabatan(r) == "" { http.Redirect(w, r, "/login", 301) fmt.Println(cekKodeJabatan(r)) fmt.Println("*** @home -> No Data ") }else{ templates := template.Must(template.New("").ParseFiles(templatePath + "sms-base.html", templatePath + "sms-home.html")) err := templates.ExecuteTemplate(w, "base", cekKodeJabatan(r)) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } } } func SmsLoginFormHandler(w http.ResponseWriter, r *http.Request) { if cekKodeJabatan(r) == "" { templates := template.Must(template.New("").ParseFiles(templatePath + "sms-base.html", templatePath + "sms-loginform.html")) err := templates.ExecuteTemplate(w, "base", nil) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } }else{ http.Redirect(w, r, "/", 301) } } func SmsPostLoginHandler(w http.ResponseWriter, r *http.Request) { if cekKodeJabatan(r) == "" { username := r.FormValue("username") password := r.FormValue("password") var results map[string]interface{} err = UserCol.Find(bson.M{"username": username, "password" : password}).One(&results) if err != nil { http.Redirect(w, r, "/#error", 301) }else{ kode_jabatan, _ := results["kode_jabatan"] session, _ := store.Get(r, "session-name") session.Values["kode_jabatan"] = kode_jabatan session.Save(r, w) http.Redirect(w, r, "/", 301) } }else{ http.Redirect(w, r, "/", 301) } } func SmsLogoutHandler(w http.ResponseWriter, r *http.Request) { session, _ := store.Get(r, "session-name") session.Values["kode_jabatan"] = "" session.Save(r, w) http.Redirect(w, r, "/", 301) } func safehtml(text string) template.HTML { text = text + " " text = strings.Replace(text, "<", "<", -1) text = strings.Replace(text, ">", ">", -1) text = strings.Replace(text, "#go #script", "", -1) text = strings.Replace(text, "
", "", -1) text = strings.Replace(text, "", "", -1) text = strings.Replace(text, "", "", -1) text = strings.Replace(text, "", "", -1) text = strings.Replace(text, "", "", -1) text = strings.Replace(text, "", "", -1) text = strings.Replace(text, "=", "=", -1) text = strings.Replace(text, "<a href=", "", "", -1) text = strings.Replace(text, "<img src=", "", ">", -1) regexPagar, _ := regexp.Compile(tagPattern) tags := regexPagar.FindAllString(text, -1) for _ , value := range tags { tagAscii := strings.Replace(value, "#", "#", 1) tagOnly := strings.Replace(value, "#", "", 1) text = strings.Replace(text, value, "" + tagAscii + "", 1) } return template.HTML(text) } func timeFormatter(text string) template.HTML { text = strings.Replace(text, " ", "-", -1) text = strings.Replace(text, ":", "-", -1) split := strings.Split(text, "-") tahun, _ := strconv.Atoi(split[0]) bulan, _ := strconv.Atoi(split[1]) tanggal, _ := strconv.Atoi(split[2]) jam, _ := strconv.Atoi(split[3]) menit, _ := strconv.Atoi(split[4]) detik, _ := strconv.Atoi(split[5]) var _bulan time.Month if bulan == 1 { _bulan = time.January }else if bulan == 2 { _bulan = time.February }else if bulan == 3{ _bulan = time.March }else if bulan == 4{ _bulan = time.April }else if bulan == 5{ _bulan = time.May }else if bulan == 6{ _bulan = time.June }else if bulan == 7{ _bulan = time.July }else if bulan == 8{ _bulan = time.August }else if bulan == 9{ _bulan = time.September }else if bulan == 10{ _bulan = time.October }else if bulan == 11{ _bulan = time.November }else if bulan == 12{ _bulan = time.December } // const layout = "Mon Jan 2, 2006 at 3:04pm (MST)" (MST) --> WITA const layout = "Mon, 2 Jan 2006 3:04 pm" t := time.Date(tahun, _bulan, tanggal, jam, menit, detik, 0, time.Local) return template.HTML(t.Format(layout)) } func randStr(strSize int, randType string) string { var dictionary string if randType == "alphanum" { dictionary = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" } if randType == "alpha" { dictionary = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" } if randType == "number" { dictionary = "0123456789" } var bytes = make([]byte, strSize) rand.Read(bytes) for k, v := range bytes { bytes[k] = dictionary[v%byte(len(dictionary))] } return string(bytes) } func GetIP(r *http.Request) string { if ipProxy := r.Header.Get("X-FORWARDED-FOR"); len(ipProxy) > 0 { return ipProxy } ip, _, _ := net.SplitHostPort(r.RemoteAddr) return ip } func main() { mx := mux.NewRouter() // *** home *** mx.HandleFunc("/", SmsHomeHandler) // *** login *** mx.HandleFunc("/login", SmsLoginFormHandler).Methods("GET") mx.HandleFunc("/login", SmsPostLoginHandler).Methods("POST") // *** logout *** mx.HandleFunc("/logout", SmsLogoutHandler).Methods("GET") // *** static server *** mx.PathPrefix("/").Handler(http.FileServer(http.Dir( publicPath ))) http.ListenAndServe(":80", mx) }
func safehtml(text string) template.HTML { text = text + " " text = strings.Replace(text, "<", "<", -1) text = strings.Replace(text, ">", ">", -1) text = strings.Replace(text, "dan ini yang memanggil", "", -1) regexPagar, _ := regexp.Compile(tagPattern) tags := regexPagar.FindAllString(text, -1) for _ , value := range tags { tagAscii := strings.Replace(value, "#", "#", 1) tagOnly := strings.Replace(value, "#", "", 1) text = strings.Replace(text, value, "" + tagAscii + "", 1) } return template.HTML(text) }", -1) text = strings.Replace(text, "", "
func WkListHandler(w http.ResponseWriter, r *http.Request) { funcMap := template.FuncMap{ "safehtml": safehtml , } templates := template.Must(template.New("").Funcs(funcMap).ParseFiles(templatePath + "webkoe-base.html", templatePath + "webkoe-list.html")) var results []Blog err = MCol.Find(bson.M{}).Sort("-date").Limit(1000000000000).All(&results) if err != nil { panic(err) } // var finalResult []tagView // fmt.Println(reflect.TypeOf(results)) err := templates.ExecuteTemplate(w, "base", results) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } }#script #webkoe #go #enlightenment #nice
- Ubuntu : Awal PATH="/root/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games" root@webkoe:~# export PATH=$PATH:/root/go/bin Menjadi PATH="/root/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/root/go/bin" - Windows : Awal Path=C:\Python27\;C:\Python27\Scripts;D:\oracle\product\11.1.0\db_1\bin;C:\ProgramData\Oracle\Java\javapath;C:\Windows\system32;C:\Windows; C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;D:\PROJECTS\NODEAPP\Nodejs\;D:\PROJECTS\WEB\xampp\php; C:\Program Files\MongoDB 2.6 Standard\bin;C:\ProgramData\ComposerSetup\bin;C:\dart\dart-sdk\bin;D:\PROJECTS\GO\bin; C:\Program Files (x86)\Git\cmd;C:\Ruby21-x64\bin;C:\Users\lou\AppData\Roaming\npm C:\Users\lou>set PATH=%PATH%;D:\PROJECTS\GO\bin Menjadi Path=C:\Python27\;C:\Python27\Scripts;D:\oracle\product\11.1.0\db_1\bin;C:\ProgramData\Oracle\Java\javapath;C:\Windows\system32; C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;D:\PROJECTS\NODEAPP\Nodejs\;D:\PROJECTS\WEB\xampp\php; C:\Program Files\MongoDB 2.6 Standard\bin;C:\ProgramData\ComposerSetup\bin;C:\dart\dart-sdk\bin;D:\PROJECTS\GO\bin; C:\Program Files (x86)\Git\cmd;C:\Ruby21-x64\bin;C:\Users\lou\AppData\Roaming\npm;D:\PROJECTS\GO\bin#script #setting #go
- Bikin file .conf baru di /etc/init - Ketikkan perintahnya, misalnya service untuk server-gorilla # /etc/init/server-gorilla.conf start on filesystem or runlevel [2345] stop on runlevel [06] script exec /go-app/webkoe/server-gorilla end script - lalu SAVE - untuk start service cukup dengan perintah "service server-gorilla start" - untuk stop servicenya "service server-gorilla stop"dengan upstrat memory lebih ringan, ketimbang menggunakan forever ... dan lagi upstart bisa melakukan exec sepuasnya, bahkan seperti contoh .conf diatas tadi, upstart menjalankan executable file ... #nice bukan ? #webkoe #script #enlightenment
Ane awalnya rumit sekali mikirnya ... syukurlah ketemu link ini http://stackoverflow.com/questions/17306358/golang-removing-fields-from-struct-or-hiding-them-in-json-response Ternyata cukup serahkan pada map[string]interface{}, sudah bisa kirim variable apapun, sepuasnya ke templates func WkTagViewHandler(w http.ResponseWriter, r *http.Request) { tagName := mux.Vars(r)["tag"] funcMap := template.FuncMap{ "safehtml": func(text string) template.HTML { text = text + " " text = strings.Replace(text, "&#60;", "<", -1) text = strings.Replace(text, ">", ">", -1) text = strings.Replace(text, "#webkoe #go #script", "", -1) regexPagar, _ := regexp.Compile(tagPattern) tags := regexPagar.FindAllString(text, -1) for _ , value := range tags { tagAscii := strings.Replace(value, "#", "#", 1) tagOnly := strings.Replace(value, "#", "", 1) text = strings.Replace(text, value, "" + tagAscii + "", 1) } return template.HTML(text) }, } templates := template.Must(template.New("").Funcs(funcMap).ParseFiles(templatePath + "webkoe-base.html", templatePath + "webkoe-tagview.html")) var results []Blog err = MCol.Find(bson.M{"tag": tagName}).Sort("-date").Limit(1000000000000).All(&results) if err != nil { panic(err) } finalResult := map[string]interface{}{ "tagName" : tagName, "tagList" : results, } err := templates.ExecuteTemplate(w, "base", finalResult) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } }", -1) text = strings.Replace(text, "", "
package main import ( "fmt" "github.com/gorilla/mux" "github.com/gorilla/sessions" "github.com/fzzy/radix/redis" "net" "net/http" "html/template" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" "regexp" "strings" "crypto/rand" "time" // "reflect" ) var ( // MongoDB mongoConfig = "mongodb://***usermongo***:***passmongo***@localhost:***portmongo***/***dbmongo***" MongoSession, err = mgo.Dial(mongoConfig) MDB = MongoSession.DB("admin") MCol = MDB.C("blog") // Session store = sessions.NewCookieStore([]byte("something-very-secret")) // Tag Factory tagPattern = "#([a-z]|[A-Z])+" ) type Blog struct { Id string Things string Date string Ip string Agent string Tag []string } // type tagView struct { // tagName string // tagList []main.Blog // } func WkHomeHandler(w http.ResponseWriter, r *http.Request) { err := template.Must(template.ParseFiles("templates/webkoe-home.html")).Execute(w, nil) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } } func WkTagViewHandler(w http.ResponseWriter, r *http.Request) { tagName := mux.Vars(r)["tag"] funcMap := template.FuncMap{ "safehtml": func(text string) template.HTML { text = text + " " text = strings.Replace(text, "&&#35;60;", "<", -1) text = strings.Replace(text, ">", ">", -1) text = strings.Replace(text, "#script #go #webkoe", "", -1) regexPagar, _ := regexp.Compile(tagPattern) tags := regexPagar.FindAllString(text, -1) for _ , value := range tags { tagAscii := strings.Replace(value, "#", "#", 1) tagOnly := strings.Replace(value, "#", "", 1) text = strings.Replace(text, value, "" + tagAscii + "", 1) } return template.HTML(text) }, } templates := template.Must(template.New("").Funcs(funcMap).ParseFiles("templates/webkoe-base.html", "templates/webkoe-tagview.html")) var results []Blog err = MCol.Find(bson.M{"tag": tagName}).Sort("-date").Limit(1000000000000).All(&results) if err != nil { panic(err) } err := templates.ExecuteTemplate(w, "base", results) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } } func WkCreateHandler(w http.ResponseWriter, r *http.Request) { blog_id := randStr(7, "alphanum") session, _ := store.Get(r, "session-name") session.Values["blog_id"] = blog_id session.Save(r, w) templates := template.Must(template.New("").ParseFiles("templates/webkoe-base.html", "templates/webkoe-create.html")) err := templates.ExecuteTemplate(w, "base", blog_id) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } } func WkPostCreateHandler(w http.ResponseWriter, r *http.Request) { things := r.FormValue("things") thingsWithSpace := things + " " captcha := r.FormValue("captcha") session,_ := store.Get(r, "session-name") blog_id := fmt.Sprintf("%s", session.Values["blog_id"]) if things != "" { if captcha == blog_id { // Factory cariTag,_ := regexp.Compile(tagPattern) tagFound := cariTag.FindAllString(thingsWithSpace, -1) var tempTags []string for _, value := range tagFound { cleanRegex,_ := regexp.Compile("(#| )") cleanTag := cleanRegex.ReplaceAllString(value, "") tempTags = append(tempTags, cleanTag) } waktu := strings.Split(fmt.Sprint(time.Now()), ".")[0] ip := GetIP(r) agent := fmt.Sprint(r.Header["User-Agent"]) jsonBlog := &Blog{Id: blog_id, Things: things, Date: waktu, Ip: ip, Agent: agent, Tag: tempTags} err = MCol.Insert(jsonBlog) fmt.Println("Welcome, " + things + " " + thingsWithSpace) http.Redirect(w, r, "/#thanks", 301) }else{ fmt.Println("Robot ?") http.Redirect(w, r, "/#you_r_a_bots", 301) } }else{ http.Redirect(w, r, "/#empty", 301) } // fmt.Println("Someone POST " + things + " blog_id " + blog_id) // fmt.Println(blog_id) /* templates := template.Must(template.New("").ParseFiles("templates/webkoe-base.html", "templates/webkoe-create.html")) err := templates.ExecuteTemplate(w, "base", nil) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } */ } func WkListHandler(w http.ResponseWriter, r *http.Request) { funcMap := template.FuncMap{ "safehtml": func(text string) template.HTML { text = text + " " text = strings.Replace(text, "<", "<", -1) text = strings.Replace(text, ">", ">", -1) text = strings.Replace(text, "", -1) text = strings.Replace(text, "", "", "", -1) regexPagar, _ := regexp.Compile(tagPattern) tags := regexPagar.FindAllString(text, -1) for _ , value := range tags { tagAscii := strings.Replace(value, "#", "#", 1) tagOnly := strings.Replace(value, "#", "", 1) text = strings.Replace(text, value, "" + tagAscii + "", 1) } return template.HTML(text) }, } templates := template.Must(template.New("").Funcs(funcMap).ParseFiles("templates/webkoe-base.html", "templates/webkoe-list.html")) var results []Blog err = MCol.Find(bson.M{}).Sort("-date").Limit(1000000000000).All(&results) if err != nil { panic(err) } // var finalResult []tagView // fmt.Println(reflect.TypeOf(results)) err := templates.ExecuteTemplate(w, "base", results) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } } func CatatanHomeHandler(w http.ResponseWriter, r *http.Request) { var results []Blog err = MCol.Find(bson.M{}).Sort("-date").Limit(100).All(&results) if err != nil { panic(err) } err := template.Must(template.ParseFiles("templates/gorilla-catatanhome.html")).Execute(w, results) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } } func HomeWKSHandler(w http.ResponseWriter, r *http.Request) { err := template.Must(template.ParseFiles("templates/gorilla-home_wks.html")).Execute(w, nil) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } } func WkBlogHandler(w http.ResponseWriter, r *http.Request) { page := mux.Vars(r)["page"] err := template.Must(template.ParseFiles("templates/gorilla-blog.html")).Execute(w, map[string]string{"halaman": page}) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } } func WkRedisHandler(w http.ResponseWriter, r *http.Request) { // redis redisClient, _ := redis.Dial("tcp", "localhost:6379") news, _ := redisClient.Cmd("zrevrangebyscore", "news:republika:posttime", "+inf", "-inf", "limit", "0", "3").List() var bundleNews []string for _, elemStr := range news { bundleNews = append(bundleNews, elemStr) fmt.Println(bundleNews) } // render err := template.Must(template.ParseFiles("templates/gorilla-redis.html")).Execute(w, bundleNews) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } } func WkTestPassVarHandler(w http.ResponseWriter, r *http.Request) { err := template.Must(template.ParseFiles("templates/gorilla-blog.html")).Execute(w, map[string]string{"halaman": "2"}) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } } func randStr(strSize int, randType string) string { var dictionary string if randType == "alphanum" { dictionary = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" } if randType == "alpha" { dictionary = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" } if randType == "number" { dictionary = "0123456789" } var bytes = make([]byte, strSize) rand.Read(bytes) for k, v := range bytes { bytes[k] = dictionary[v%byte(len(dictionary))] } return string(bytes) } func GetIP(r *http.Request) string { if ipProxy := r.Header.Get("X-FORWARDED-FOR"); len(ipProxy) > 0 { return ipProxy } ip, _, _ := net.SplitHostPort(r.RemoteAddr) return ip } func main() { // MUX ROUTER mx := mux.NewRouter() // WEBKOE.NET // *** home *** mx.HandleFunc("/", WkListHandler).Host("webkoe.net") // *** tag *** mx.HandleFunc("/tag/{tag}", WkTagViewHandler).Host("webkoe.net").Methods("GET") // *** create *** mx.HandleFunc("/create", WkCreateHandler).Host("webkoe.net").Methods("GET") mx.HandleFunc("/create", WkPostCreateHandler).Host("webkoe.net").Methods("POST") // *** misc *** mx.HandleFunc("/test/pass_var", WkTestPassVarHandler).Host("webkoe.net") mx.HandleFunc("/redis", WkRedisHandler).Host("webkoe.net") mx.HandleFunc("/page/{page}", WkBlogHandler).Host("webkoe.net") mx.PathPrefix("/").Handler(http.FileServer(http.Dir("./public/"))).Host("webkoe.net") // CATATAN.WEBKOE.NET mx.HandleFunc("/", CatatanHomeHandler).Host("catatan.webkoe.net") // WEBKANSAJA.COM mx.HandleFunc("/", HomeWKSHandler).Host("webkansaja.com") http.ListenAndServe(":80", mx) }", -1) text = strings.Replace(text, "", "
hapuskan ingatan event click atas object #foo $( "#foo").unbind( "click" );#jquery #enlightenment #script #problemsolved #project
var filter = { "$and" : [ {"tag.kode_jabatan": req.session.user.kode_jabatan}, {"tag.enable": "1"} ] } if(req.session.search == undefined){ // PASS }else{ for(var a in req.session.search){ if(a !== "hal"){ var value = new RegExp(req.session.search[a], "i") var _subobj = {} _subobj[a] = value filter['$and'].push(_subobj) }else{ var kata = req.session.search[a].split(" ") for(var indexWord in kata){ var value = new RegExp(kata[indexWord], "i") var _subobj = {} _subobj[a] = value filter['$and'].push(_subobj) } } } }Hasil query mongonya ...
{ '$and': [ { 'tag.kode_jabatan': '01' }, { 'tag.enable': '1' }, { nomorAgenda: /(?:)/i }, { tglAgenda: /(?:)/i }, { asal: /(?:)/i }, { nomor: /(?:)/i }, { tanggal: /(?:)/i }, { hal: /cuti/i }, { hal: /asra/i } ] } { '$and': [ { 'tag.kode_jabatan': '01' }, { 'tag.enable': '1' }, { nomorAgenda: /(?:)/i }, { tglAgenda: /(?:)/i }, { asal: /(?:)/i }, { nomor: /(?:)/i }, { tanggal: /(?:)/i }, { hal: /cuti/i }, { hal: /asra/i } ] }#script #mongodb #project
def grab(list,label) : parameter = ["curl","-H","User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:26.0) Gecko/20100101 Firefox/26.0 FirePHP/0.7.4","--max-time", "1000", "--write-out", "%{http_code}", "--silent"] for l in list : parameter.append(l) default_code = "000" reconnect = "" proc = subprocess.Popen(parameter,stdout=subprocess.PIPE) (out, err) = proc.communicate() print label ''' while default_code != "200" : proc = subprocess.Popen(parameter,stdout=subprocess.PIPE) (out, err) = proc.communicate() if str(out) == "200" : default_code = "200" # OK info = "OK" elif str(out) == "000" : info = "FAIL" reconnect = "reconnect" elif str(out) == "302" : info = "REDIRECT" reconnect = "reconnect" else : info = "..." reconnect = "reconnect" print label + ": " + str(out) + " " + info + " " + reconnect '''#webkoe #script #python
var _date = replies[a].date var date = new Date(_date) var newdate = date.getDay() var namaBulan = {} namaBulan[0] = "Minggu" namaBulan[1] = "Senin" namaBulan[2] = "Selasa" namaBulan[3] = "Rabu" namaBulan[4] = "Kamis" namaBulan[5] = "Jumat" namaBulan[6] = "Sabtu" replies[a].date = namaBulan[newdate] + " " + _date#script #webkoe
/****************************************************************************** * * Copyright 2011 Tavendo GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package de.tavendo.autobahn.echoclient; import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.Gravity; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.telephony.TelephonyManager; //import android.util.Base64; /*import de.tavendo.autobahn.R;*/ import de.tavendo.autobahn.WebSocket; import de.tavendo.autobahn.WebSocketConnection; import de.tavendo.autobahn.WebSocketException; import de.tavendo.autobahn.WebSocketConnectionHandler; import de.tavendo.autobahn.NotifyMessage; public class EchoClientActivity extends Activity { static final String TAG = "de.tavendo.autobahn.echo"; private static final String PREFS_NAME = "AutobahnAndroidEcho"; private static int NOTIFY_ME_ID=1337; static EditText mHostname; static EditText mPort; static TextView mStatusline; static Button mStart; static EditText mMessage; static Button mSendMessage; private SharedPreferences mSettings; private void alert(String message) { Toast toast = Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT); toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0); toast.show(); } private String getMyPhoneNumber(){ TelephonyManager mTelephonyMgr; mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); return mTelephonyMgr.getSimSerialNumber(); } private void katakan(String msg){ /*********** Create notification ***********/ final NotificationManager mgr= (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE); Notification note=new Notification(R.drawable.stat_notify_chat, "Webkoe ...", System.currentTimeMillis()); // This pending intent will open after notification click PendingIntent i=PendingIntent.getActivity(this, 0, new Intent(this, NotifyMessage.class), 0); note.setLatestEventInfo(this, "Pesan :", msg, i); //After uncomment this line you will see number of notification arrived //note.number=2; NOTIFY_ME_ID = NOTIFY_ME_ID + 1; mgr.notify(NOTIFY_ME_ID, note); } private void loadPrefs() { mHostname.setText(mSettings.getString("hostname", "")); mPort.setText(mSettings.getString("port", "9000")); } private void savePrefs() { SharedPreferences.Editor editor = mSettings.edit(); editor.putString("hostname", mHostname.getText().toString()); editor.putString("port", mPort.getText().toString()); editor.commit(); } private void setButtonConnect() { mHostname.setEnabled(true); mPort.setEnabled(true); mStart.setText("Connect"); mStart.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { start(); } }); } private void setButtonDisconnect() { mHostname.setEnabled(false); mPort.setEnabled(false); mStart.setText("Disconnect"); mStart.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { mConnection.disconnect(); } }); } private final WebSocket mConnection = new WebSocketConnection(); private void start() { final String wsuri = "ws://" + mHostname.getText() + ":" + mPort.getText(); mStatusline.setText("Status: Connecting to " + wsuri + " .."); setButtonDisconnect(); try { mConnection.connect(wsuri, new WebSocketConnectionHandler() { @Override public void onOpen() { mStatusline.setText("Status: Connecteds to " + wsuri); savePrefs(); mSendMessage.setEnabled(true); mMessage.setEnabled(true); } @Override public void onTextMessage(String payload) { alert("Got echo: " + payload); katakan(payload); } @Override public void onClose(int code, String reason) { alert("Connection lost."); mStatusline.setText("Status: Ready."); setButtonConnect(); mSendMessage.setEnabled(false); mMessage.setEnabled(false); } }); } catch (WebSocketException e) { Log.d(TAG, e.toString()); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mHostname = (EditText) findViewById(R.id.hostname); mPort = (EditText) findViewById(R.id.port); mStatusline = (TextView) findViewById(R.id.statusline); mStart = (Button) findViewById(R.id.start); mMessage = (EditText) findViewById(R.id.msg); mSendMessage = (Button) findViewById(R.id.sendMsg); mSettings = getSharedPreferences(PREFS_NAME, 0); loadPrefs(); setButtonConnect(); mSendMessage.setEnabled(false); mMessage.setEnabled(false); mSendMessage.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { String nomor = getMyPhoneNumber(); mConnection.sendTextMessage("%%" + nomor + " " + mMessage.getText().toString()); //mConnection.sendTextMessage(mMessage.getText().toString()); } }); } @Override protected void onDestroy() { super.onDestroy(); if (mConnection.isConnected()) { mConnection.disconnect(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.quit: finish(); break; default: return super.onOptionsItemSelected(item); } return true; } }EchoClientActivity.java #script