full-stack-developer
full-stack-developer
I'm a full-stack developer
18 posts
Don't wanna be here? Send us removal request.
full-stack-developer · 9 years ago
Link
0 notes
full-stack-developer · 10 years ago
Text
Fix for Slow SSH Password Prompt
It may be caused by GSSAPI authentication time out, which access external security service 
Edit /etc/ssh/sshd_config
Set GSSAPIAuthentication no
Save and restart SSH server
http://askubuntu.com/questions/246323/why-does-sshs-password-prompt-take-so-long-to-appear https://en.wikipedia.org/wiki/Generic_Security_Services_Application_Program_Interface
2 notes · View notes
full-stack-developer · 10 years ago
Link
simple guideline
2 notes · View notes
full-stack-developer · 10 years ago
Text
Proper way to clear Samba WINS cache
1. Locate browser.dat and wins.data from /var/lib/samba or /var/cache/samba or /etc/samba 2. Kill the nmbd deamon and remove the above file 3. Restart the nmbd deamon. (for Debian)
# killall nmbd # rm /var/lib/samba/wins.dat # rm /var/cache/samba/browser.dat # nmbd -D
More Reading
https://www.samba.org/samba/docs/man/Samba-Guide/upgrades.html#id2600749
https://www.samba.org/samba/docs/man/Samba-Guide/unixclients.html
2 notes · View notes
full-stack-developer · 10 years ago
Text
Create and Update Google Calendar Event using Google Form
These are the google form fields:-
1. Timestamp 2. Title 3. Venue 4. Date 5. Start Time 6. End Time 7. Participants 8. Note for this meeting 9. EventId
Reference:
https://code.google.com/p/google-apps-script-issues/issues/detail?id=574
http://blog.ouseful.info/2010/03/04/maintaining-google-calendars-from-a-google-spreadsheet/
In Script Editor:
//this is the ID of the calendar to add the event to, this is found on the calendar settings page of the calendar in question
var calendarId = "[email protected]"; var formUrl = "https://docs.google.com/forms/d/xxxxx-yyyyy/edit"; //below are the column ids of that represents the values used in the spreadsheet (these are non zero indexed) var formTimeStampId = 1; var titleId = 2; var locId = 3; var dateId = 4; var startTimeId = 5; var endTimeId = 6; var descId = 7; var calId = 9;
function getLatestAndSubmitToCalendar(e) {  Logger.log("[METHOD] onFormSubmit" + e);
 // get the correct data set  var sheet = SpreadsheetApp.getActiveSheet();  var rows = sheet.getDataRange();  var numRows = rows.getNumRows();  var values = rows.getValues();
 // get last inserted row  var lastrow = rows.getLastRow();
 Logger.log("responses: " + responses);  createCalendarEventForRow(sheet, lastRow); }
function updateAllRow() {
 // get the correct data set  var sheet = SpreadsheetApp.getActiveSheet();  var rows = sheet.getDataRange();  var numRows = rows.getNumRows();
 for (var row = 2; row < numRows; row++) {    createCalendarEventForRow(sheet, row);  }
}
function createCalendarEventForRow(sheet, row) {  var lastrow = row + "";  // get properties of events  var m_date = sheet.getRange(lastrow,dateId,1,1).getValue();  var _range = sheet.getRange(lastrow,startTimeId,1,1);  var m_starttime =  sheet.getRange(lastrow,startTimeId,1,1).getValue().toLocaleTimeString().split(" ")[0];  var m_endtime = sheet.getRange(lastrow,endTimeId,1,1).getValue().toLocaleTimeString().split(" ")[0];;
 // Get the date value in the spreadsheet's timezone.  var spreadsheetTimezone = sheet.getParent().getSpreadsheetTimeZone();  Logger.log("Script Timezone: " + Session.getScriptTimeZone());  Logger.log("SpreadSheet Timezone: " + spreadsheetTimezone);
 // get response link to include in the event description  var formTimeStamp = new Date(sheet.getRange(lastrow,formTimeStampId,1,1).getValue());  var responseUrl = getEditResponseUrl(formTimeStamp);
 var startTime  = joinDateAndTime_(m_date, m_starttime, spreadsheetTimezone);  var endTime = joinDateAndTime_(m_date, m_endtime, spreadsheetTimezone);  var location =  sheet.getRange(lastrow,locId,1,1).getValue();  var subOn = "Submitted on :"+sheet.getRange(lastrow,formTimeStampId,1,1).getValue();  var desc = "Added by :"+sheet.getRange(lastrow,descId,1,1).getValue()+"\n"+subOn + "\nEdit meeting: <a href=\"" + responseUrl + "\">"+responseUrl+"</a>";  var title = sheet.getRange(lastrow,titleId,1,1).getValue();
 // check if update  var eventId = sheet.getRange(lastrow,calId,1,1).getValue().split("@");
 if (eventId != "") {    updateEvent(calendarId,eventId[0], title, startTime, endTime, desc, location);  } else {    // create or update event    eventId = createEvent(calendarId,title, startTime, endTime, desc, location);    Logger.log("[METHOD] event created " + eventId);    sheet.getRange(lastrow,calId,1,1).setValue(eventId);  }   }
function updateEvent(calendarId, eventId, title,startTime,endTime,desc, loc) {    var existingEvent = Calendar.Events.get(calendarId, eventId);    Logger.log("[Object] eventId " + eventId);    Logger.log("[Object] event " +  existingEvent);    existingEvent.setSummary(title);    existingEvent.setLocation(loc);    existingEvent.start.dateTime = startTime.toISOString();    existingEvent.end.dateTime= endTime.toISOString();    existingEvent.description = desc;    try {      Calendar.Events.update(existingEvent, calendarId, eventId, existingEvent);    } catch (e) {      Logger.log(e);    }    Logger.log("[METHOD] event updated " + existingEvent.getId());    return existingEvent.getId(); }
function createEvent(calendarId,title,startTime,endTime,desc, loc) { var cal = CalendarApp.getCalendarById(calendarId); var start = new Date(startTime); var end = new Date(endTime); var event = cal.createEvent(title, start, end, {description : desc, location : loc});  return event.getId(); };
function getEditResponseUrl(formTimeStamp) {  var form = FormApp.openByUrl(formUrl);  var responses = form.getResponses(formTimeStamp);  Logger.log("Response length " + responses.length); //  var response = responses[responses.length-1];  var response = responses[0];  var lasturl =  response.getEditResponseUrl();  Logger.log("lasturl " + lasturl);  return lasturl; }
/** * Creates a single Date object from separate date and time cells. * * @param {Date} date A Date object from which to extract the date. * @param {Date} time A Date object from which to extract the time. * @return {Date} A Date object representing the combined date and time. */ function joinDateAndTime_(date, time, spreadsheetTimezone) {  var _time  = time.split(":"); // in HH:mm:ss format  var _date = new Date(date);  //_date.setHours(getValueAsHours(time, spreadsheetTimezone));  //_date.setMinutes(getValueAsMinutes(time, spreadsheetTimezone));  _date.setHours(_time[0]);  _date.setMinutes(_time[1]);  return _date; }
function onEdit(e){  // Set a comment on the edited cell to indicate when it was changed.  var range = e.range;  range.setNote('Last modified: ' + new Date()); }
function getValueAsSeconds(date,spreadsheetTimezone) { //  var dateString = Utilities.formatDate(value, spreadsheetTimezone, //      'EEE, d MMM yyyy HH:mm:ss'); //  var date = new Date(dateString);
 // Initialize the date of the epoch.  var epoch = new Date('Dec 30, 1899 00:00:00');
 // Calculate the number of milliseconds between the epoch and the value.  var diff = date.getTime() - epoch.getTime();
 // Convert the milliseconds to seconds and return.  return Math.round(diff / 1000); }
function getValueAsMinutes(range) {  return getValueAsSeconds(range) / 60; }
function getValueAsHours(range) {  return getValueAsMinutes(range) / 60; }
0 notes
full-stack-developer · 10 years ago
Text
Hello world spring-boot project (Part 5)
In this part, i will further extend the oath2 protocol in Part 4 to use JWT as encoded token.
We need a new library to handle JWT token. Again, we add the dependency in the build.gradle file.
   compile("org.springframework.security:spring-security-jwt")
Then, we can configure our server to use JWT token converter.
package hello;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
@Configuration @EnableAuthorizationServer public class OAuthServerConfig extends AuthorizationServerConfigurerAdapter {
     private static final String RESOURCE_ID = "oauth2_resource";
     @Bean      public JwtAccessTokenConverter accessTokenConverter() {         return new JwtAccessTokenConverter();      }
     @Autowired      private AuthenticationManager authenticationManager; // for password grant
     @Override      public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {            oauthServer.tokenKeyAccess("isAnonymous() || hasAuthority('ROLE_TRUSTED_CLIENT')").checkTokenAccess(                "hasAuthority('ROLE_TRUSTED_CLIENT')");      }
     @Override      public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {           endpoints.authenticationManager(authenticationManager).accessTokenConverter(accessTokenConverter());      }
     @Override      public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    ....
      }
}
After setting up the server, let try to get the token.
The owner performs the same GET query as in Part 4 to get the owner consent to obtain an access code. Then, the client POST the code to the server to exchange for an access token.
Tumblr media
However, the server returned a very long access token which is the JWT token.
In an access token, you can find two dot ‘.’. They are the separators of the encoded content:
 [JWT header (BASE64)].[JWT JSON CONTENT (BASE64)].[TOKEN SIGNATURE] 
In this case,
eyJhbGciOiJIUzI1NiJ9 = {"alg":"HS256"}
eyJhdWQiOlsib2F1dGgyX3Jlc291cmNlIl0sInVzZXJfbmFtZSI6InVzZXIiLCJzY29wZSI6WyJyZWFkIiwidHJ1c3QiXSwiZXhwIjoxNDQwOTg1NTYxLCJhdXRob3JpdGllcyI6WyJST0xFX1VTRVIiXSwianRpIjoiODVjMTg4OGYtNzA5Ni00YjM0LWFlYmQtMGFiOWJkNzc3MjFjIiwiY2xpZW50X2lkIjoibXktY2xpZW50LXdpdGgtcmVnaXN0ZXJlZC1yZWRpcmVjdCJ9 
= {"aud":["oauth2_resource"],"user_name":"user","scope":["read","trust"],"exp":1440985561,"authorities":["ROLE_USER"],"jti":"85c1888f-7096-4b34-aebd-0ab9bd77721c","client_id":"my-client-with-registered-redirect"}
This JWT contains most of the information needed to identify an user, its roles and its scope of access.
When the OAuth2 client present this encoded token, the resource server can decode the content and decide if the resource server should provide resource to this client based on this token alone. Therefore, it is stateless and super scalable.
0 notes
full-stack-developer · 10 years ago
Text
Hello world spring-boot project (Part 4)
After having simple username and password protection, we want to extend the system to allow more apps accessing our resources. In Part 4, we try to implement simple OAuth 2 in our system. 
When a client send a request to a resource endpoint (Resource Server), the client need to send together a HTTP Authorization header:
Authorization: Bearer $TOKEN
The $TOKEN is obtained from an Authorization Server.
Therefore, we first build the Authorization Server with spring framework first.
We first add some dependency to our build.gradle file:-
   compile("org.springframework.security.oauth:spring-security-oauth2:2.0.7.RELEASE")
Then, we add a Java class to create the Authorization Server.
package hello;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
@Configuration @EnableAuthorizationServer class OAuth2Config extends AuthorizationServerConfigurerAdapter {
 public static final String RESOURCE_ID = "hello_resource";
     @Autowired      private AuthenticationManager authenticationManager;
     @Override      public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {           endpoints.authenticationManager(authenticationManager);      }
     @Override      public void configure(ClientDetailsServiceConfigurer clients) throws Exception {           // @formatter:off           clients.inMemory()           .withClient("client-with-registered-redirect")           .authorizedGrantTypes("authorization_code")           .authorities("ROLE_CLIENT")           .scopes("read", "trust")           .resourceIds(RESOURCE_ID)           .redirectUris("http://anywhere?key=value")           .secret("secret123")           .and()           .withClient("my-client-with-secret")           .authorizedGrantTypes("client_credentials", "password")           .authorities("ROLE_CLIENT")           .scopes("read")           .resourceIds(RESOURCE_ID)           .secret("secret");           // @formatter:on      } }
The Authorization Server has the following default endpoint.
"{[/oauth/authorize]}": {    "bean": "oauth2EndpointHandlerMapping",    "method": "public org.springframework.web.servlet.ModelAndView org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint.authorize(java.util.Map<java.lang.String, java.lang.Object>,java.util.Map<java.lang.String, java.lang.String>,org.springframework.web.bind.support.SessionStatus,java.security.Principal)"  },  "{[/oauth/authorize],methods=[POST],params=[user_oauth_approval]}": {    "bean": "oauth2EndpointHandlerMapping",    "method": "public org.springframework.web.servlet.View org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint.approveOrDeny(java.util.Map<java.lang.String, java.lang.String>,java.util.Map<java.lang.String, ?>,org.springframework.web.bind.support.SessionStatus,java.security.Principal)"  },  "{[/oauth/token],methods=[GET]}": {    "bean": "oauth2EndpointHandlerMapping",    "method": "public org.springframework.http.ResponseEntity<org.springframework.security.oauth2.common.OAuth2AccessToken> org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.getAccessToken(java.security.Principal,java.util.Map<java.lang.String, java.lang.String>) throws org.springframework.web.HttpRequestMethodNotSupportedException"  },  "{[/oauth/token],methods=[POST]}": {    "bean": "oauth2EndpointHandlerMapping",    "method": "public org.springframework.http.ResponseEntity<org.springframework.security.oauth2.common.OAuth2AccessToken> org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken(java.security.Principal,java.util.Map<java.lang.String, java.lang.String>) throws org.springframework.web.HttpRequestMethodNotSupportedException"  },  "{[/oauth/check_token]}": {    "bean": "oauth2EndpointHandlerMapping",    "method": "public java.util.Map<java.lang.String, ?> org.springframework.security.oauth2.provider.endpoint.CheckTokenEndpoint.checkToken(java.lang.String)"  },  "{[/oauth/confirm_access]}": {    "bean": "oauth2EndpointHandlerMapping",    "method": "public org.springframework.web.servlet.ModelAndView org.springframework.security.oauth2.provider.endpoint.WhitelabelApprovalEndpoint.getAccessConfirmation(java.util.Map<java.lang.String, java.lang.Object>,javax.servlet.http.HttpServletRequest) throws java.lang.Exception"  },  "{[/oauth/error]}": {    "bean": "oauth2EndpointHandlerMapping",    "method": "public org.springframework.web.servlet.ModelAndView org.springframework.security.oauth2.provider.endpoint.WhitelabelErrorEndpoint.handleError(javax.servlet.http.HttpServletRequest)"  },
Authroization Code Grant Summary in our implementation
1. Authorization Server authenticates the User
The user need to login to the authorization server using the login name and password. In this case, we use HTTP Basic, so the spring default username is user and the password is generated in the boot log.
2. Client starts the authorization flow and obtain User’s approval
The owner need to authorize the 3rd party to use its resource by 
GET http://localhost:8080/oauth/authorize?response_type=code&client_id=client-with-registered-redirect&redirect_url=http://client_host?key=value&scope=read
3. Authorization Server issues an authorization code (opaque one-time token)
The authorization end point will redirect the user to the registered redirect uri with a code (authorization code) for the 3rd party to access the resource.
http://anywhere/?key=value&code=H3aJ6s
4. Client exchanges the authorization code for an access token
Then, the 3rd party can obtain an access token from the Authorization Server using the code.
We try to do this using Postman to illustrate the result.
Tumblr media Tumblr media Tumblr media
The 3rd party POST the authorization code (i.e. H3aJ6s) to the Authorization Server with a grant type authorization_code. The HTTP request need to be HTTP-Basic authenticated using the client_id (i.e. client-with-registered-redirect) as username and secret (i.e. secret123) as the password to the default OAuth2 Token end point.
POST http://localhost:8080/oauth/token
Finally, the server returns an access_token ($TOKEN) to the 3rd party for accessing the Resource Server!
O! Wait, how about the Resource Server? How to implement it using Spring?
package hello;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
@Configuration @EnableResourceServer class ResourceServer extends ResourceServerConfigurerAdapter {  public static final String RESOURCE_ID = "hello_resource";      @Override      public void configure(HttpSecurity http) throws Exception {           // @formatter:off           http .requestMatchers().antMatchers("/people").and() .authorizeRequests() .anyRequest().access("#oauth2.hasScope('read')");           // @formatter:on      }
     @Override      public void configure(ResourceServerSecurityConfigurer resources) throws Exception {           resources.resourceId(RESOURCE_ID);      } }
By substituting the $TOKEN in the introduction when accessing the /people resource, we can obtain the JSON response we get in previous parts. Cool!
Tumblr media
References:-
http://www.slideshare.net/SpringCentral/syer-microservicesecurity
https://github.com/spring-projects/spring-security-oauth/tree/master/tests/annotation
https://raymondhlee.wordpress.com/2014/12/21/implementing-oauth2-with-spring-security/
https://github.com/spring-projects/spring-security-javaconfig/tree/master/samples
0 notes
full-stack-developer · 10 years ago
Link
REST and Form spring security
0 notes
full-stack-developer · 10 years ago
Text
Hello world spring-boot project (Part 3)
We have our spring boot JPA rest project prepared in Part 2. However, it is not secure to let anyone to call the REST api. Let's secure our web service.
In our build.grade file, add a single line of config:
   compile("org.springframework.boot:spring-boot-starter-security")
After including the spring-boot-starter-security library, we re-run our application again. In the startup console, there will be a line:
Using default security password: b0bd95d0-7c62-4718-af46-380b9d05b1b7
This is the a spring-boot generated password for a default user.
If we try to call the people api defined in Part 2 without authentication, we will encounter HTTP Error 401 Unauthorized. As you can see, spring-boot automatically secure most URI for us.
Tumblr media
So, we need to configure Postman to use HTTP Basic Authentication to obtain our result. In Postman,
Go to Authorization. Select Basic Auth. Enter Username: user, Password: <the generated password>
However, you probably do not want to use the generated password and do want to define your own set of users. Let’s create our own.
Surfing all the blogs posts, this is the most simple sample for reference:
https://github.com/spring-projects/spring-data-examples/tree/master/rest/security
We create a configuration class to create our own set of security related setting.
package hello;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration @EnableGlobalMethodSecurity(prePostEnabled = true) @EnableWebSecurity public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
   @Autowired    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {            auth.inMemoryAuthentication() .withUser("user").password("password").roles("USER").and() .withUser("admin").password("password").roles("USER", "ADMIN");    }
   @Override    protected void configure(HttpSecurity http) throws Exception {
     http.httpBasic().and().csrf().disable(); }
}
To keep it short, we define two users.
1. admin:password with role user and admin
2. user:password with role user
Besides, we enabled the @PreAuthorize annotation in our repository service using @EnableGlobalMethodSecurity(prePostEnabled = true).
We also need to ask spring to use httpBasic() always and disable the CSRF security here. If you do not know what is CSRF, just disable it at this moment for development purpose.
Then, we set some permission stuff in our PersonRepository defined in Part 2.
@RepositoryRestResource(collectionResourceRel = "people", path = "people") @PreAuthorize("hasRole('ROLE_USER')") public interface PersonRepository extends PagingAndSortingRepository<Person, Long> {
       List<Person> findByLastName(@Param("name") String name);
       @PreAuthorize("hasRole('ROLE_ADMIN')")        @Override        Person save(Person p);
       @PreAuthorize("hasRole('ROLE_ADMIN')")        @Override        void delete(Long aLong);
}
We allow PersonRepository interface to be accessible by default with the role USER only. We further override permission of the method save and delete to allow the role ADMIN to modify the records in our database.
Try verifying this in Postman! Have fun!
0 notes
full-stack-developer · 10 years ago
Link
0 notes
full-stack-developer · 10 years ago
Text
Helloworld spring-boot project (Part 1.1)
On top of our first helloworld project. Let’s add some interesting spring-boot features.
           https://spring.io/guides/gs/actuator-service/
1.  Spring Boot Actuator 
This plugin can help monitoring the health status of the server status. simply include this to the dependencies part of your build.gradle file:-
   compile("org.springframework.boot:spring-boot-starter-actuator")
Then, you can find a list of URL mappings from this URL:-
    http://localhost:8080/mappings
You can find a list of end points added by the actuator service. Try it one by one yourselves. They are interesting.
 "{[/metrics/{name:.*}],methods=[GET]}": {    "bean": "endpointHandlerMapping",    "method": "public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.MetricsMvcEndpoint.value(java.lang.String)"  },  "{[/metrics],methods=[GET]}": {    "bean": "endpointHandlerMapping",    "method": "public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()"  },  "{[/autoconfig],methods=[GET]}": {    "bean": "endpointHandlerMapping",    "method": "public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()"  },  "{[/dump],methods=[GET]}": {    "bean": "endpointHandlerMapping",    "method": "public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()"  },  "{[/beans],methods=[GET]}": {    "bean": "endpointHandlerMapping",    "method": "public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()"  },  "{[/env/{name:.*}],methods=[GET]}": {    "bean": "endpointHandlerMapping",    "method": "public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EnvironmentMvcEndpoint.value(java.lang.String)"  },  "{[/env],methods=[GET]}": {    "bean": "endpointHandlerMapping",    "method": "public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()"  },  "{[/mappings],methods=[GET]}": {    "bean": "endpointHandlerMapping",    "method": "public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()"  },  "{[/info],methods=[GET]}": {    "bean": "endpointHandlerMapping",    "method": "public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()"  },  "{[/configprops],methods=[GET]}": {    "bean": "endpointHandlerMapping",    "method": "public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()"  },  "{[/trace],methods=[GET]}": {    "bean": "endpointHandlerMapping",    "method": "public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()"  },  "{[/health]}": {    "bean": "endpointHandlerMapping",    "method": "public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.HealthMvcEndpoint.invoke(java.security.Principal)"  }
2. Change server port and actuate management port.
Add a resource file src/main/resources/application.properties with the following contents:
server.port: 9000 management.port: 9001 management.address: 127.0.0.1
Then, your standalone spring-boot application will be started at the port 9000 instead of the default port 8080. The Spring Actuator management endpoints can only be find at port 9001. e.g. http://localhost:9001/mappings.
0 notes
full-stack-developer · 10 years ago
Text
Helloworld spring-boot project (Part 2)
This time, i am going to learn how to create a JPA supported rest application by following the getting started guideline - Accessing JPA Data with REST
                https://spring.io/guides/gs/accessing-data-rest/
Similar to Part 1, we quickly create our project folder and start our project using 
> gradle init --type java-library
Then, we follow the guideline to add a domain object Person and its corresponding JPA Repository Interface with some JPA syntax (@Entity, @Id and @GeneratedValue)
It is super easy that once we create the PersonRepository interface, spring-boot will automatically provide the implementation for us at runtime!
Again, we create a Application executable to kickstart our spring-boot project with command
> gradle bootRun
Once the project is started, we can navigate to our demo at 
http://localhost:8080/
Oh no! We don’t have any person added to the repository. 
Instead of using curl command. Let’s do it with a very friendly tool, Postman, which is available at the Chrome Web Store
https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en
Tumblr media
Running Postman,  we select POST method, enter our REST endpoint
http://localhost:8080/people
Go to Headers section, and add Content-Type with value application/json
Probably you can see that Postman offers lots of properties for your selection. No worry about wrong typo!
Go to Body section, choose raw, then enter the sample body into the text area.
{  "firstName" : "Frodo",  "lastName" : "Baggins" }
Once all these are completed, click the blue Send button.
After this you can see the server response with a green status
201 Created
You may further observe the server also returned the location URI link to this newly created person.
We have completed the basics of the tutorial. We can now use the Postman to test our REST api.
PUT - replace the entire record. Fields not supplied will become null. PATCH - replace only supplied fields. DELETE - delete the whole record.
Have fun!
0 notes
full-stack-developer · 10 years ago
Text
Helloworld spring-boot project (Part 1)
This is my first time to play with spring-boot and gradle. It feels like a freshman joining an University.
I follow the Getting Started tutorial provided by spring-boot
https://spring.io/guides/gs/spring-boot/#scratch
# What i need is to install the latest version of gradle at https://gradle.org/
# Setup the Path environment variable in Windows/Linux/Mac
# Update the JAVA_HOME environment variable pointing to any Java 8 JDK
# Create a new project folder (i.e. C:\Users\developer\Projects\helloworld\)
# Initialize the project folder with gradle. A directory structure will be setup automatically! It’s amazing!
> gradle init --type java-library
# Following the guildeline and update the build.gradle
# Write your code in the src\java\main folder
# Run the application
> gradle bootRun   (Reference: http://docs.spring.io/spring-boot/docs/current/reference/html/build-tool-plugins-gradle-plugin.html#build-tool-plugins-gradle-running-applications)              or > gradle run
# Start a web browser (i.e. Chrome) and enter your URL
http://localhost:8080/
“ Greetings from Spring Boot! “
The message is shown in your browser and my first part of the simple quick start tutorial completed.
0 notes
full-stack-developer · 10 years ago
Link
0 notes
full-stack-developer · 10 years ago
Text
AppDelegate.swift 2
Recently, i am migrating an existing swift project to a newer version using the XCode migration wizard.
XCode tried to convert my Swift syntax into version 2. However, the migration process is not that smooth and some generated CoreData code become really odd.
The following Swift 2 code is generated by XCode 7 when creating a new SingleView project with Core Data enabled for reference and learning purpose.
// // AppDelegate.swift // // Copyright © 2015. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "full.stack.developer.SingleView" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource(“SingleView”, withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
The syntax is much simplified using Swift 2. The managedObjectContext and persistentStoreCoordinator have been rewritten in the following ways:-
new error handling code 'do..try..catch' alike Java
using more constant type 'let' for value passing
0 notes
full-stack-developer · 10 years ago
Text
WWDC 2015 - Implementing UI Designs in Interface Builder (1)
In the demo, there is a Swift class named RTTripThumbnailView. However, the full code can hardly be seen in the video, so let's try to reimplement it here.
// // RTTripThumbnailView.swift // // Copyright © 2015. All rights reserved. // import UIKit @IBDesignable class RTTripThumbnailView: UIView { var imageView: UIImageView! var maskLayer: CAShapeLayer! var ringLayer: CAShapeLayer! @IBInspectable var image: UIImage? { didSet { if imageView != nil { imageView.image = image } } } @IBInspectable var strokeWidth: CGFloat = 1.0 @IBInspectable var strokeColor: UIColor = .lightGrayColor() { didSet (newValue) { if ringLayer != nil { ringLayer.fillColor = newValue.CGColor } } } override func layoutSubviews() { super.layoutSubviews() if ringLayer == nil { let path = UIBezierPath(ovalInRect: CGRectInset(bounds, 1.0, 1.0)) ringLayer = CAShapeLayer() ringLayer.path = path.CGPath ringLayer.fillColor = strokeColor.CGColor layer.insertSublayer(ringLayer, below: imageView.layer) } if maskLayer == nil { maskLayer = CAShapeLayer() imageView.layer.mask = maskLayer imageView.layer.masksToBounds = true } let path = UIBezierPath(ovalInRect: CGRectInset(bounds, strokeWidth + 1, strokeWidth + 1)) maskLayer.path = path.CGPath ringLayer.frame = layer.bounds imageView.frame = layer.bounds } override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.clearColor(); imageView = UIImageView() imageView.backgroundColor = UIColor.clearColor(); addSubview(imageView) } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) backgroundColor = UIColor.clearColor(); imageView = UIImageView() imageView.backgroundColor = UIColor.clearColor(); addSubview(imageView) } override func prepareForInterfaceBuilder() { backgroundColor = UIColor.clearColor() } }
Video link: https://developer.apple.com/videos/wwdc/2015/?id=407
0 notes
full-stack-developer · 10 years ago
Text
WWDC 2015 - Improving Your Existing Apps with Swift (1)
Demo - Struct Methods - With Playground Prototyping
Playground Settings: Platform = iOS
import UIKit var str = "Hello, playground" // A UIView creates a graphics context class IconView: UIView { override func drawRect(rect: CGRect) { drawRawBackgroundWithBaseColor(UIColor.orangeColor(), backgroundRectangle: self.bounds) } } func drawRawBackgroundWithBaseColor(strokeColor:UIColor, backgroundRectangle: CGRect) { let lineWidth = backgroundRectangle.width / 36.0 let cornerRadius = backgroundRectangle.width / 16.0 let tileRectangle = backgroundRectangle.rectByInsetting(dx:lineWidth/2.0, dy: lineWidth / 2.0) let strokePath = UIBezierPath(roundedRect: tileRectangle, cornerRadius: cornerRadius) strokeColor.setStroke() strokePath.lineWidth = lineWidth strokePath.stroke() } let rect = CGRect(x: 0.0, y: 0.0, width: 320.0, height:320.0) let icon = IconView(frame: rect) icon.backgroundColor = UIColor.clearColor() icon
Video link: https://developer.apple.com/videos/wwdc/2015/?id=403
0 notes