星期三, 7月 30, 2014

[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.

[AngularJS] angular-breadcurumb 模組

UI-Bootstrap竟然沒含breadcrumb模組,
有需要可以參考這個Angular-breadcrumb/ ng-breadcrumbs


https://github.com/ianwalter/ng-breadcrumbs
http://ncuillery.github.io/angular-breadcrumb/#/home

星期一, 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