星期三, 7月 30, 2014

[Java] iterate map的範例集

今天為了某個需求用了MultivaluedMap,怎麼iterate找到了以下的參考範例。
請服用

http://www.sergiy.ca/how-to-iterate-over-a-map-in-java

[Alfresco] impersonate 登入用戶

alfresco提供以下方法讓你可以模仿別的用戶登入的授權。


//get current user
  String currentUser = AuthenticationUtil.getFullyAuthenticatedUser();
  String fakeUser = "IAMBIGD";
  LOGGER.debug("currentUser:" + currentUser);
  if (currentUser == null || !currentUser.equals(fakeUser)) {
            // AuthenticationUtil.setCurrentUser(username);
   //set impersonate 
   AuthenticationUtil.setFullyAuthenticatedUser(fakeUser);
  }

星期二, 7月 22, 2014

[AngularJS] 如何使用form validation驗證input=file

原生的ng並不支援file element的validation,可透過自已新增directive來達到這個功能。

directive

app.directive('validFile',function(){
  return {
    require:'ngModel',
    link:function(scope,el,attrs,ngModel){
      //change event is fired when file is selected
      el.bind('change',function(){
        scope.$apply(function(){
          ngModel.$setViewValue(el.val());
          ngModel.$render();
        });
      });
    }
  }
});

HTML


Input is valid: {{myForm.userUpload.$valid}} Selected file: {{filename}}

[AngularJS] 初學者的angular常用語法筆記

最近重回NG的懷抱,
從邊做專案的過程中,
記錄一些常用的手法。避免會忘記XD

ng-class

//設定某個物件被選擇
 ng-class="{true: 'table-row-selected', false: ''}[product.selected]"

Filter

//取得被選擇的使用者數量
  $scope.getSelectedUsers = function() {
   var selectedObjs = $filter("filter")($scope.userList, {
    selected: true
   })
   return selectedObjs;
  };

陣列反轉

//html 
ng-repeat="folder in parentFolders.slice().reverse()


改變url上面的參數

$location.path('/login');

轉頁

$window.open('http://www.yahoo.com.tw');

如果從已知的array移除指定的item

$scope.userList.splice($index, 1);//移除使用者清單內的某一用戶

事件處理$broadcast, $emit, $on


$broadcast:
發送事件的方法,向下分派事件到所有的子scope範圍。此外也可以由$rootScope發送事件,但要慎用。

$emit:
發送事件的方法,向上分派事件到scope階層範圍。

$on 接受事件的方法,發送端可帶入參數至接收端


將$http request加入common的header

由於REST API很流行,大家都會定義呼叫時要帶入application/json,做法如下。
app.run(['$http', function($http) {

// The $http service will automatically add certain HTTP headers to all requests. These defaults can be fully configured by accessing the $httpProvider.defaults.headers configuration object, which currently contains this default configuration:

// $httpProvider.defaults.headers.common (headers that are common for all requests):
// Accept: application/json, text/plain, * / *
// $httpProvider.defaults.headers.post: (header defaults for POST requests)
// Content-Type: application/json
// $httpProvider.defaults.headers.put (header defaults for PUT requests)
// Content-Type: application/json


 $http.defaults.headers.common['Content-Type'] = 'application/json';
}])


$http GET content-type header無法正確送出的解決方法

[AngularJS] $http無法送出 content-type header

如何使用$watch監控JSON 物件

Call $watch with true as the third argument:
 
$scope.$watch('form', function(newVal, oldVal){
    console.log('changed');
}, true);

By default when comparing two complex objects in JavaScript, they will be checked for "reference" equality, which asks if the two objects refer to the same thing, rather than "value" equality, which checks if the values of all the properties of those objects are equal. Per the Angular documentation, the third parameter is for objectEquality: When objectEquality == true, inequality of the watchExpression is determined according to the angular.equals function. To save the value of the object for later comparison, the angular.copy function is used. This therefore means that watching complex objects will have adverse memory and performance implications.

星期日, 7月 20, 2014

[AngularJS] 使用angular ui-bootstrap 發生tooltip 404

今天開另一個專案載入UI-bootstrap使用tooltip時,發生找不到相關的樣版 *.tpls.html 可以透過$templateCache.removeAll();清除後就正常, 之後再把這個註解就沒問題了。
 app.run(['$templateCache',function($templateCache){
  $templateCache.removeAll();
 }]);

星期四, 7月 17, 2014

[Sublime Text] 寫網站的神級編輯器 筆記



剛好趁換新的Mac pro記錄一下安裝Sublime的過程,
目前已用了一年多了,細節大家看網路應該就一堆介紹啦,
所以不再多對它介紹了XD

使用版本:

Sublime Text 3

安裝第一個pluging "Page Control"


View->Show Console

將以下的install code貼到Console

import urllib.request,os,hashlib; h = '7183a2d3e96f11eeadd761d777e62404' + 'e330c659d4bb41d3bdf022e94cab3cd0'; pf = 'Package Control.sublime-package'; ipp = sublime.installed_packages_path(); urllib.request.install_opener( urllib.request.build_opener( urllib.request.ProxyHandler()) ); by = urllib.request.urlopen( 'http://sublime.wbond.net/' + pf.replace(' ', '%20')).read(); dh = hashlib.sha256(by).hexdigest(); print('Error validating download (got %s instead of %s), please try manual install' % (dh, h)) if dh != h else open(os.path.join( ipp, pf), 'wb' ).write(by)

星期三, 7月 16, 2014

[Java] 簡單的User authorization機制

常用到的使用者是否有正確的權限存取當前頁面的機制,Java可以透過Filter來達到。
可依個人需求再強化嚕。

This can be handled in a Filter and there are great explanation and example in StackOverflow Servlet-Filter wiki.
Adapting the code there for your problem (note the addition and usage of the needsAuthenticationmethod):
@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig config)
        throws ServletException {
        // If you have any  in web.xml, then you could get them
        // here by config.getInitParameter("name") and assign it as field.
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        HttpSession session = request.getSession(false);

        String requestPath = httpServletRequest.getRequestURI();

        if (needsAuthentication(requestPath) ||
            session == null ||
            session.getAttribute("user") == null) { // change "user" for the session attribute you have defined

            response.sendRedirect(request.getContextPath() + "/login"); // No logged-in user found, so redirect to login page.
        } else {
            chain.doFilter(req, res); // Logged-in user found, so just continue request.
        }
    }

    @Override
    public void destroy() {
        // If you have assigned any expensive resources as field of
        // this Filter class, then you could clean/close them here.
    }

    //basic validation of pages that do not require authentication
    private boolean needsAuthentication(String url) {
        String[] validNonAuthenticationUrls =
            { "Login.jsp", "Register.jsp" };
        for(String validUrl : validNonAuthenticationUrls) {
            if (url.endsWith(validUrl)) {
                return false;
            }
        }
        return true;
    }
}
I would recommend to move all the pages that require authentication inside a folder like app and then change the web filter to
@WebFilter("/app/*")
In this way, you can remove the needsAuthentication method from the filter.

星期一, 7月 07, 2014

[AngularJS] 實作自動選取的directive

實作自動選取的directive範例

HTML

 <input type="text" value="test" select-on-click />

JS

module.directive('selectOnClick', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            element.on('click', function () {
                this.select();
            });
        }
    };
});

http://stackoverflow.com/questions/14995884/select-text-on-input-focus-in-angular-js

[AngularJS] angular-xeditable 讓元素變可以編輯的

angular-xeditable 提供元素可編輯的效果,
如果常用的個人資訊編輯頁面就非常試用。

https://github.com/vitalets/angular-xeditable

星期日, 6月 29, 2014

[AngularJS] angular dialog service v5.0.0 試用

透過angular dialog service這個第三方套件,
可以輕鬆使用modal來產生alert, confirm, custom 等效果。

測試版本: v 5.0.0

需求的套件: ngSanitize, bootstrap.ui, ngTranslate
https://github.com/m-e-conroy/angular-dialog-service

sample
http://codepen.io/m-e-conroy/pen/ALsdF


[AngularJS] Pagination 0.10.0 切換事件的event

由於目前使用NG UI-Bootstrap 0.10.0的版本,要注意頁面切換要使用on-select-page這個屬性,才有辦法正確的接收到事件的方法。

The ability to use ng-model was introduced in ui-bootstrap-tpls-0.11.0.js, as explained in thechangelog:
Both pagination and pager are now integrated with ngModelController.
page is replaced from ng-model.
on-select-page is removed since ng-change can now be used.

星期一, 6月 23, 2014

星期日, 6月 22, 2014

[Javascript] 前端工具好用工具清單

為了提升前端程式品質與工作效率,發展了許多好用的工具,在此記錄一下

PMD 

可支援javascript原始碼檢測工具,找出重覆的原始碼

JSHIT 

javascript程式碼品質檢測工具

RequireJS

javascript 模組管理工具(可配合r.js進行壓縮)

GruntJS 

可以把一些任務,透過Grunt來自動化執行,例如測試、JSLint檢查、JS壓縮、less、coffee的編譯等等,可以透過一個指令,就把所有的事情做好。 

SCSS/SASS


LiveReload 

自動刷新頁面的工具

Gulp.js

Speed. Efficiency. Simplicity.
gulp's use of streams and code-over-configuration makes for a simpler and more intuitive build.

[AngularJS] 初學簡報大雜繪

記錄一下學習AngularJS找到的簡報檔。

[AngularJS] 常用的全選/取消全選的介面需求- checklist-model diretive

做表格列表常用到的元件:D

http://vitalets.github.io/checklist-model/

星期六, 6月 21, 2014

[AngularJS] 整合UI-bootstrap alert diretive

將原本的UI-Bootstrap再使用一層AlterService來包裝,使用起來更方便:D

此外也可利用$rootScope.$broadcast事件的方法來統一處理全域的訊息

Directive

<alert ng-repeat="alert in alerts"
	type="alert.type"
	close="alert.close($index)">{{alert.msg}}</alert>


AlertService Factory


支援timeout自動關閉訊息

app.factory('AlertService', ['$rootScope', '$timeout', '$log',
	function($rootScope, $timeout, $log) {
		var alertService = this;

		$rootScope.alerts = [];
		return alertService = {

			add: function(type, msg, timeout) {

				$rootScope.alerts.push({
					type: type,
					msg: msg,
					close: function() {
						return alertService.closeAlert(this);
					}
				});

				if(typeof(timeout) == 'undefined'){
					timeout = 5000;
				}
				if (timeout) {
					$timeout(function() {
						alertService.closeAlert(this);
					}, timeout);
				}
			},
			closeAlert: function(alert) {
				$log.log(alert);
				return this.closeAlertIdx($rootScope.alerts.indexOf(alert));
			},
			closeAlertIdx: function(index) {
				return $rootScope.alerts.splice(index, 1);
			},
			clear: function(){
            	$rootScope.alerts = [];
          	}

		};

	}
])

Controller

angular.module('myApp.controllers').controller('LoginCtrl', ['$rootScope','$scope', '$log', 'AuthService', 'AlertService','$location',
  function($rootScope, $scope, $log, AuthService, AlertService, $location) {
    $log.log('load login page');

    $scope.login = function(credentials) {
      $log.log('press login button');
      $log.log(credentials);

      AuthService.login(
        credentials, function(data, status, headers, config) {
          $log.log('success to call login');
          $log.log(data);
          if (data.status == 200) {

            $log.log('go to default users page');
            //go to home
            $location.path('/users');

          }else if (data.status == 500){

            AlertService.add('danger','不正確的帳號或密碼');
          
          }

        }, function(data, status, headers, config) {
            $log.log('fail to call login');
            AlertService.add('danger','伺服器發生錯誤,請重新再試');
        });
    };

  }
]);


https://coderwall.com/p/r_bvhg

[AngularJS] 事件處理機制 $broadcast , $emit , $on 的運作

筆記一下Angularjs的事件處理機制的運作方法:

First of all, parent-child scope relation does matter. You have two possibilities to emit some event:
  • $broadcast -- dispatches the event downwards to all child scopes,
  • $emit -- dispatches the event upwards through the scope hierarchy.
I don't know anything about your controllers (scopes) relation, but there are several options:
  1. If scope of firstCtrl is parent of the secondCtrl scope, your code should work by replacing $emit by $broadcast in firstCtrl:
    function firstCtrl($scope){
        $scope.$broadcast('someEvent', [1,2,3]);
    }
    
    function secondCtrl($scope){
        $scope.$on('someEvent', function(event, mass) {console.log(mass)});
    }
  2. In case there is no parent-child relation between your scopes you can inject $rootScope into the controller and broadcast the event to all child scopes (i.e. also secondCtrl).
    function firstCtrl($rootScope){
        $rootScope.$broadcast('someEvent', [1,2,3]);
    }
  3. Finally, when you need to dispatch the event from child controller to scopes upwards you can use $scope.$emit. If scope of firstCtrl is parent of the secondCtrl scope:
    function firstCtrl($scope){
        $scope.$on('someEvent', function(event, data) { console.log(data); });
    }
    
    function secondCtrl($scope){
        $scope.$emit('someEvent', [1,2,3]);
    }

其他你感興趣的文章

Related Posts with Thumbnails