<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Douglas Liu on Medium]]></title>
        <description><![CDATA[Stories by Douglas Liu on Medium]]></description>
        <link>https://medium.com/@sohoffice?source=rss-9a6805825a86------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*4P38Hoiy4kvqj2JzTm9XBg.jpeg</url>
            <title>Stories by Douglas Liu on Medium</title>
            <link>https://medium.com/@sohoffice?source=rss-9a6805825a86------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 11:49:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sohoffice/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[10 Tips when Building New Kubernetes Cluster on GCP, Part 2]]></title>
            <link>https://medium.com/sohoffice/10-tips-when-building-new-kubernetes-cluster-on-gcp-part-2-4e47ca5affe9?source=rss-9a6805825a86------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e47ca5affe9</guid>
            <category><![CDATA[k8s]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[gcp]]></category>
            <dc:creator><![CDATA[Douglas Liu]]></dc:creator>
            <pubDate>Wed, 15 May 2019 09:05:31 GMT</pubDate>
            <atom:updated>2022-11-02T00:51:22.011Z</atom:updated>
            <content:encoded><![CDATA[<pre>This article is more relevant by 2019, some of the tips are no longer valid today.</pre><p>The second part of the tips focus more on problem solving. I had run into all of them, they all took me some time to figure out. Hopefully you can stand on top of my experiences and provision faster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QVEXoUcUitpPRSTG" /><figcaption>Photo by <a href="https://unsplash.com/@kaelbloom?utm_source=medium&amp;utm_medium=referral">Kael Bloom</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>6. Be careful when deleting service</h3><p>When you’re planning your Kubernetes elements, you may think it’s a good idea to put deployments and related services together. However, I’ll advise you to separate them. It’s not about creating and updating, but more about deletion.</p><p>In GKE, <strong>the most time consuming things are those related to Load Balancer</strong>. Configuring Ingress can be even more time consuming than provision a new cluster. I guess the network inside GCP is too complex to require that amount of time to configure the load balancer. Since Ingress are connecting to your services, not your pods. <strong>If you delete your services, you’re taking the risk of confusing Ingress</strong>. If you split the services and deployments config file, you can very safely delete your applications (deployments) without touching the services. Therefore leaving Ingress intact. The above may also apply to service updates involving changed port, but deletion of service is definitely one thing to avoid.</p><p>If you run into load balancer (Ingress) problem. I’d suggest you to visit the <a href="https://console.cloud.google.com/net-services/loadbalancing/loadBalancers/list">console page</a>, go into your load balancer. Look very carefully on the backends, ex: k8s-be-30130-abcdefg12345678. The trick is to match the port with your service listed viakubectl get services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*Fwvb132NF3vQdGChaP2JfQ.png" /><figcaption>Console backend service</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*np99g7d7Dk9oeybPfkuQEA.png" /><figcaption>kubectl get services</figcaption></figure><p>If you find <strong>ingress are referring to backend services that do not exist</strong>. <strong>You’ll have to rebuild the ingress</strong>. (and wait another 20 minutes, sorry about it.) I tried monkey patching, but it doesn’t seem to work.</p><h4>Wondered why this is tip #6 ?</h4><p><a href="https://medium.com/sohoffice/10-tips-when-building-new-kubernetes-cluster-on-gcp-part-1-1a2bf15c4348">10 Tips when Building New Kubernetes Cluster on GCP, Part 1</a></p><h3>7. You can Use StatefulSet with assigned volume</h3><p>We all read the document on <a href="https://cloud.google.com/kubernetes-engine/docs/concepts/statefulset">using StatefulSet</a>, StatefulSet’s extremely suitable when dealing with service that require persistence. Services like database, redis … sort of things. The official document advises that we should use volumeClaimTemplate. But there’re times, specify the volume is easier, especially for small instances.</p><p>What StatefulSet + volumeClaimTemplate does is:</p><p>When you creates an application called app. Scale to 3 replicas. 3 instances are created using the container spec in the name app-0, app-1, app-2. VolumeClaims will be created base on the vc template and attached to the 3 instances. If you stop the application and start it again, StatefulSet will remember the correct binding between app-0 and vc-0, app-1 and vc-1 … So everything are back in order. Read the <a href="https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/">document on Kubernetes site</a> for more details.</p><p>However, you should take the following points into consideration before you start using volumeClaimTemplate.</p><ol><li><strong>Will your service scale to multiple instances</strong> ? Do you really need K8s to remember the bindings for you ?</li><li><strong>When you delete the application, the bindings are permanently lost</strong>. I can’t find a way to bind the pvc and pv back to the newly created application instance. (Any advises ?)</li><li>You actually <strong>can</strong> specify the gce disk directly.</li></ol><p>For example, I don’t intend to scale my solr server in the foreseeable future, so I chose to <strong>manage the binding on my own</strong>. It’s easier to manage, and you’re free to delete and rebuild the application at any time.</p><p>Create the app.yml as the below:</p><pre>containers:<br>  - name: foo<br>    volumeMounts:<br>      - name: foo-vol<br>        mountPath: /data<br>volumes:<br>  - name: foo-vol<br>    gcePersistentDisk:<br>      pdName: foo-disk<br>      fsType: ext4</pre><p>Before provisioning the app, run the command to create the disk first.</p><pre><em>gcloud </em>compute disks create --size=1GB foo-disk</pre><p>Think carefully before you choose between the 2 strategies. General rule of thumb:</p><blockquote><strong>If you know your application will not have multiple instances, you can specify the volume</strong>. Otherwise, use volumeClaimTemplate and try not to delete the application.</blockquote><p>If you use volumeClaimTemplate, I think it is wise to write down the Deployment → PVC → PV bindings, in case you ever needed it some day.</p><h4>Why StatefulSet over Deployment</h4><p>StatefulSet without volumeClaimTemplate looks quite similar to a Deployment. Why should we use it in favor of Deployment ?</p><p>It actually has a very important advantage over using Deployment. (using the default update strategy)</p><blockquote>StatefulSet will terminate the old application before starting the new instance.</blockquote><p>Being single instance, down time is inevitable when updating. But the nature of StatefulSet reduces the downtime to minimum. Using deployment, on the other hand, will get yourself trapped. For it will launch the new instance before removing the old one. Think about it, if your app is running on node 1, and k8s is now starting new instance on node 2. Your disk will have a hard time moving about.</p><blockquote>Again, this tip is only useful when you do not plan to scale your application beyond one instance.</blockquote><h3>8. Be careful of label and selector</h3><p>Labels can be useful when managing the Kubernetes elements, but it can also be very dangerous if we don’t use it correctly.</p><blockquote>Labels are arbitrary key value pair, where key and value do not have any special meaning to Kubernetes engine.</blockquote><p>Taken the below labels for example:</p><pre>apiVersion: apps/v1<br>kind: StatefulSet<br>metadata:<br>  name: prod-redis<br>  labels:<br>    environment: prod<br>    app: redis</pre><p>I was once convinced that <strong>app</strong> is a special label to specifically point to this application. After a few round of refactor, I lost track of the selector…</p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: prod-redis-service<br>  labels:<br>    app: redis</pre><p>My application wasn’t working properly. The redis pubsub sometimes works, sometimes not. That was a terrible period of time, until I started to run monitor on my redis and realized not all commands arrived.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*r7wt36wMjMsNnYra" /><figcaption>Photo by <a href="https://unsplash.com/@neonbrand?utm_source=medium&amp;utm_medium=referral">NeONBRAND</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I guess you know what happened, my service selector wasn’t specific enough.</p><pre># expected<br>prod app → prod redis service → prod redis pod</pre><pre># actual<br>prod app → prod redis service → prod redis pod<br>                              \ staging redis pod</pre><p>The usual NodePort type of service, also behaves like simple load balancer which works with multiple endpoints. Use kubectl get endpoints to view the list. And you will realize the relationship between service, endpoints and pods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*vpXEw2g1DaNEb8lUPZU1YA.png" /><figcaption>Endpoints example</figcaption></figure><p>All in all, don’t just copy and paste the labels. Understand they are nothing more than what they are, <strong>labels</strong>. And use them wisely. The tip may sound very stupid, but it actually cost me a few days. I hope you never will run into this, but in case you do, remember to run kubectl get endpoints.</p><h3>9. Only use error logging level when you should</h3><p>The reason is simple, GCP has a very powerful logging tool: Stackdriver. Stackdriver has an error reporting section which includes only errors. You can be notified when Stackdriver picks up new error. Or you can use Cloud Console to investigate them. I don’t know about you, but I certainly don’t want to be bothered by trivial exceptions.</p><p>I’d suggest you review your exception loggings, use warning level if the exception do not require attention immediately. Use error level for those are more time sensitive.</p><p>As a side note, I’ll use EmptyDir for my logging directories. The logs can be found on Stackdriver any way. For example:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>spec:<br>  template:<br>    spec:<br>      containers:<br>        volumeMounts:<br>          - name: log-vol<br>            mountPath: /data/logs<br>      volumes:<br>        - name: log-vol<br>          emptyDir: {}</pre><h3>10. Use GCR for private image</h3><p>This tip is not for Kubernetes user, but for anyone who is building private docker images. The docker hub provides one free repo, but anything more than that you’ll have to pay at least $7/month. As a result, I’ve struggled setting up a private docker registry. Worked on generate the certificates, built up trust network via VPN sort of things. Which in total had cost me at least a day. And I had to clean up the storage on regular basis.</p><p><strong>These can all be avoided by using Google Cloud Registry</strong>. Well … or AWS, Azure :) Just don’t build it yourself.</p><p>Judging from my Billing &gt; Transaction so far, I believe using the GCR alone would have cost me far less than $1 a month. Totally affordable.</p><p>I do have a few other tips that I wanted to list, such as session affinity and cronjob … But Kubernetes is such a big topic, you can never discuss everything in a few days. I just hope you will like Kubernetes and the articles as much as I did.</p><h4>Contact Me</h4><p><a href="https://www.linkedin.com/in/sohoffice/">LinkedIn</a>, <a href="https://github.com/sohoffice">Github</a> or <a href="https://www.facebook.com/sohoffice/">Facebook</a></p><p><strong>Did you learn something new? If so please:</strong></p><p>↓ <strong>clap 👏 button</strong> below️ so more people can see this.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e47ca5affe9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sohoffice/10-tips-when-building-new-kubernetes-cluster-on-gcp-part-2-4e47ca5affe9">10 Tips when Building New Kubernetes Cluster on GCP, Part 2</a> was originally published in <a href="https://medium.com/sohoffice">Sohoffice</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[10 Tips when Building New Kubernetes Cluster on GCP, Part 1]]></title>
            <link>https://medium.com/sohoffice/10-tips-when-building-new-kubernetes-cluster-on-gcp-part-1-1a2bf15c4348?source=rss-9a6805825a86------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a2bf15c4348</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[k8s]]></category>
            <category><![CDATA[cloud]]></category>
            <dc:creator><![CDATA[Douglas Liu]]></dc:creator>
            <pubDate>Tue, 14 May 2019 04:11:29 GMT</pubDate>
            <atom:updated>2022-11-02T00:50:56.673Z</atom:updated>
            <content:encoded><![CDATA[<pre>This article is more relevant by 2019, some of the tips are no longer valid today.</pre><p>Building on Kubernetes is not difficult, but going through wrong direction may sometimes cost you precious time. Some may even require you to scrap your existing cluster and start over.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VMKe7GtEPiNbKQOY" /><figcaption>Photo by <a href="https://unsplash.com/@larisabirta?utm_source=medium&amp;utm_medium=referral">Larisa Birta</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>1. Use private IP</h3><p>Private IP is the easiest way to connect to Cloud SQL like Postgres or MySQL. However, it’s not enabled by default, and <strong>you can not enable it after creating your cluster</strong>. So, it’s the very first tip to make sure we do the below extra steps to enable the private IP when creating the cluster.</p><p>Enable Private IP involves ticking on a toggle VPC native. Follow the 2 steps on the below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*8sluHXdWvBktMMuFWtwXeQ.png" /><figcaption>Step 1, Expand extra options</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*OFZwSDPLKVhkdEfChjYv4w.png" /><figcaption>Step 2, Tick Enable VPC-native</figcaption></figure><p>Your GKE application should now be able to connect to Cloud SQL using database url like the below</p><pre>postgres://db_user:db_pass@10.122.1.1:5432/dbname</pre><p>Actually a lot more requirements are happening under the hood, see <a href="https://cloud.google.com/sql/docs/mysql/private-ip">Private IP document</a>. But you need to tick this option to get yourself started, and the rest should not create must trouble. Luckily this VPC-native will soon become GKE default and we no longer need to recreate the cluster just to connect to the database. (happened to me ~~~)</p><p>Note, if you’re literally creating new Kubernetes cluster, make sure you also read the next tip before clicking on the Create button.</p><h3>2. Use managed certificate</h3><p>If your service need to serve http, you probably want to have https certificate. (You should, as with most other web services, https is the default now.) However, setting up certbot in GKE requires multiple steps, and Google do provide a ready-to-use solution with no additional cost, why not let Google do the heavy lifting ?</p><p><a href="https://cloud.google.com/kubernetes-engine/docs/how-to/managed-certs">Managed Certificate</a> is currently in beta, but is stable enough to get the job done. You need to upgrade your kubernetes version to at least 1.12.6-gke.7. Unlike the VPC-native, the upgrade can be performed on existing cluster. But selecting the right version upfront will save you several minutes of waiting.</p><p>Create cert.yml similar to the below:</p><pre>apiVersion: networking.gke.io/v1beta1<br>kind: ManagedCertificate<br>metadata:<br>  name: my-cert-name<br>spec:<br>  domains:<br>    - www.example.tw</pre><p>However, using managed certificate has the following prerequisites</p><ol><li>You need to own the domain name</li><li>You need to have a static IP on GCP first</li><li>You need to point your DNS to GCP static IP before provision the cert</li><li>Your DNS is better with DNSSEC</li></ol><p>The first two are <a href="https://cloud.google.com/kubernetes-engine/docs/how-to/managed-certs">documented</a>, but I find either rule 3 or 4 also play the role. When I created my certificates, some of them just refused to be created no matter how long I waited (days). In the end I migrated my DNS to Google’s Cloud DNS, <strong>delete the failed to be created certificates and recreate them</strong>. The certificate was provisioned in something like an hour.</p><p>I was very hesitated to delete the failed certificate provisioning, for I have waited a very long time. But <strong>re-creating prove to be very effective</strong>. When I was on other DNS provider, pointing to GCP static IP is helpful, eventually. But using Google’s Cloud DNS is a lot faster.</p><p>I’m not sure, are they biased? Or more likely because of the lack of DNSSEC in my previous provider.</p><h3>3. Add proper health check</h3><p>Having setting up your deployments, services and ingress. You think you’re ready to launch. But out of sudden, your web service was rejecting connection with 502 server error.</p><p>Please describe your ingress: kubectl describe ingress/network. Looking for the line under Application &gt; backends: (The describe results appear to be unordered, look carefully)</p><pre>backends:         {&quot;k8s-be-00000--12345678&quot;:&quot;HEALTHY&quot;,&quot;k8s-be-11111--12345678&quot;:&quot;<strong>UNHEALTHY</strong>&quot;}</pre><p>Note the <strong>UNHEALTHY</strong> in the above status ? Your service was not considered healthy by ingress. You should use port forward to test your service. But there are times, your service is actually serving, just it was considered unhealthy.</p><p>For example, your API service may not have responded to GET / request, which is the default place ingress will be checking for healthiness. This happens, after all the main purpose of API service is to respond to /api. You should alter your application.yml to include readiness probe and liveness probe.</p><pre>livenessProbe:<br>  httpGet:<br>    path: /ping<br>    port: 4000<br>  successThreshold: 1<br>  failureThreshold: 3<br>  initialDelaySeconds: 15<br>  periodSeconds: 60<br>readinessProbe:<br>  httpGet:<br>    path: /ping<br>    port: 4000<br>  successThreshold: 1<br>  failureThreshold: 3<br>  initialDelaySeconds: 10<br>  periodSeconds: 60</pre><p>You may have noticed, the health check doesn’t have to be GET /. So long as you provided a readiness probe, health check will perform accordingly.</p><p>PS. I’d suggest you try very hard to avoid the UNHEALTHY state, because it takes time to come back to HEALTHY.</p><h3>4. Use port forward to diagnose</h3><p>I believe this is a commonly known trick, but it’s so useful I think I should have mentioned it. We will have a whole lot of reasons wanting to diagnose our services:</p><ul><li>Use a hidden service (redis for example)</li><li>Diagnose a specific pod</li></ul><p>Port forward like the name suggest, will forward a local port to the specified remote port. It can work on service or pod, depending on your need.</p><pre>kubectl port-forward pods my-pod-name-is-here 4001:4000</pre><p>The above bind local port 4001 to port 4000 of your pod my-pod-name-is-here. You may point your browser location to <a href="http://localhost:4001/">http://localhost:4001/</a> now to give it a try.</p><p>Directly logging on to your pod is also very useful, use the below if you have bash installed on your image:</p><pre>kubectl exec -it my-pod-id bash</pre><h3>5. Plan the namespace</h3><p>K8s has a very nice feature, namespace. This allows you to segment your services very cleanly. Services with the same name do not collide with each other if they belong to different namespaces. This is useful if you have multiple projects, or different environments like staging and production.</p><p>However, <strong>namespace does not come without cost</strong>. Here, the cost literally means <strong>money</strong>.</p><p>Say you have the following typical structure:</p><pre>deployment ←→ service ←→ ingress</pre><p>By segmenting the elements into 2 namespaces, you thereafter have to <strong>pay for one ingress per namespace</strong>, because ingress can only connect to service on the same namespace. That will be, 2 ingress in total to be paid for. And ingress, in my opinion, is kind of expansive comparing with other resources on GCP. So, plan your namespace wisely.</p><p>I personally would suggest avoiding namespace on small or single project cluster. Only use namespace if you have multiple projects running.</p><h4>Contact Me</h4><p><a href="https://www.linkedin.com/in/sohoffice/">LinkedIn</a>, <a href="https://github.com/sohoffice">Github</a> or <a href="https://www.facebook.com/sohoffice/">Facebook</a></p><p><strong>Did you learn something new? If so please:</strong></p><p>↓ <strong>clap 👏 button</strong> below️ so more people can see this.</p><h4>Continue to Part 2</h4><p><a href="https://medium.com/sohoffice/10-tips-when-building-new-kubernetes-cluster-on-gcp-part-2-4e47ca5affe9">10 Tips when Building New Kubernetes Cluster on GCP, Part 2</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a2bf15c4348" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sohoffice/10-tips-when-building-new-kubernetes-cluster-on-gcp-part-1-1a2bf15c4348">10 Tips when Building New Kubernetes Cluster on GCP, Part 1</a> was originally published in <a href="https://medium.com/sohoffice">Sohoffice</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[descriptive-play-swagger now supports Play framework 2.7]]></title>
            <link>https://medium.com/sohoffice/descriptive-play-swagger-now-supports-play-framework-2-7-d9e6c22c5013?source=rss-9a6805825a86------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9e6c22c5013</guid>
            <category><![CDATA[play-swagger]]></category>
            <category><![CDATA[play-framework]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[swagger]]></category>
            <dc:creator><![CDATA[Douglas Liu]]></dc:creator>
            <pubDate>Mon, 06 May 2019 07:33:21 GMT</pubDate>
            <atom:updated>2019-05-06T07:33:21.351Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://github.com/sohoffice/descriptive-play-swagger">descriptive-play-swagger</a> is a fork of play-swagger. A SBT plugin that allows you to write comments on play framework routes file, together with the scaladoc to generate the full swagger documentation.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ChfmQhCGfNoLbN2J" /><figcaption>Photo by <a href="https://unsplash.com/@ninjason?utm_source=medium&amp;utm_medium=referral">Jason Leung</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Play-swagger rocks, a SBT plugin is probably the best way to generate documentation. Unlike other solution on the market, which normally require you to use annotation on your source files. Soon enough your import section will be polluted by import i.have.no.idea.what.these.are dependencies. Imagine all the efforts when the plugin changes the package name. Oh my…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YofqXUbnKATSKtDM" /><figcaption>Photo by <a href="https://unsplash.com/@blancotejedor?utm_source=medium&amp;utm_medium=referral">Aarón Blanco Tejedor</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Play-swagger takes a different route. <strong>No more imports, just comments</strong>. You write comments on the play framework routes file and play-swagger will use reflection to generate all the swagger document for you.</p><p>It gets the job done, and gets it done very nicely. With only one exception: <strong>You can not have description on the API parameters or model fields. </strong>This is inevitable, reflection works on generated bytecodes, not the source files. This is why I forked this project and started adding my solution.</p><p><a href="https://github.com/sohoffice/descriptive-play-swagger">sohoffice/descriptive-play-swagger</a></p><p><a href="https://github.com/sohoffice/descriptive-play-swagger">descriptive-play-swagger</a> actually consists of two parts:</p><ul><li>An extension of play-swagger that accepts one additional parameter used to supply the descriptions.</li><li>The <a href="https://github.com/sohoffice/docExtract">doc-extract</a> SBT plugin to extract scaladoc into a text file.</li></ul><h3>Installation</h3><p>The installation is straight forward, things are just happening under the hood.</p><pre>#plugins.sbt<br>addSbtPlugin(&quot;com.sohoffice&quot; %% &quot;sbt-descriptive-play-swagger&quot; % &quot;0.7.5&quot;)</pre><pre>#build.sbt<br>resolvers += Resolver.bintrayIvyRepo(&quot;sohoffice&quot;, &quot;sbt-plugins&quot;)<br><br>lazy val root = (project in file(&quot;.&quot;))<br>  .enablePlugins(PlayScala, SwaggerPlugin)</pre><h3>Demo</h3><p>The below is a very simple demonstration of how things work. Note the descriptions were generated beside model parameters, which is quite blanky using play-swagger alone. Check it out in <a href="https://github.com/sohoffice/play-docgen-seed">github</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k0T_jwphzgRVfGYOHcxz-w.png" /></figure><h3>Conclusion</h3><p>The project is still very young, with very little usage, if any. As a result I don’t maintain any kind of backward compatibility. It will only support the current play framework version used in my project, at this moment, version 2.7. But I still hope you will enjoy it.</p><h4>Other swagger articles</h4><p><a href="https://medium.com/sohoffice/upgrade-your-swagger-generated-angular-project-to-angular-7-a99ddb94f87c">Upgrade your swagger generated angular project to angular 7/8</a></p><p><strong>Did you learn something new? If so please:</strong></p><p>↓ <strong>clap 👏 button</strong> below️ so more people can see this.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9e6c22c5013" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sohoffice/descriptive-play-swagger-now-supports-play-framework-2-7-d9e6c22c5013">descriptive-play-swagger now supports Play framework 2.7</a> was originally published in <a href="https://medium.com/sohoffice">Sohoffice</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Gotchas of Upgrading to Play Framework 2.7 and Slick 3.3.0]]></title>
            <link>https://medium.com/sohoffice/upgrading-to-play-framework-2-7-673242ba0da0?source=rss-9a6805825a86------2</link>
            <guid isPermaLink="false">https://medium.com/p/673242ba0da0</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[play-framework]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[slick]]></category>
            <dc:creator><![CDATA[Douglas Liu]]></dc:creator>
            <pubDate>Thu, 02 May 2019 09:23:50 GMT</pubDate>
            <atom:updated>2019-05-06T05:33:03.144Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently I upgraded my Play Framework application from 2.6 to 2.7. Originally I wanted to avoid this upgrade, but Akka Cluster Bootstrap has a minimal requirement of Akka version at 2.5.21, which is fulfilled by play framework 2.7. So I guess I was kind of forced to upgrade my play framework application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zpdTjxdznfbibJmg" /><figcaption>Photo by <a href="https://unsplash.com/@adspedia?utm_source=medium&amp;utm_medium=referral">Val Vesa</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>According to the <a href="https://www.playframework.com/documentation/2.7.x/Migration27">documentation</a>, I believe version 2.7 mainly differs from 2.6 in Java API. I sense my scala application should be 90% fine, which it is. However, I’ve still had a few gotchas which I’m detailing in the below.</p><h3>Slick upgrade to 3.3.0</h3><p>According to the slick migration <a href="http://slick.lightbend.com/doc/3.3.0/upgrade.html#upgrade-from-3.2-to-3.3">document</a>, version 3.3.0 include native support of java.time data type. This sounds like a great news, no more MappedColumnType for these standard data type !</p><p>Unfortunately, <strong>this java.time support is creating more problem than anything else</strong>. Quite frankly, I think this has something to do with the design of slick postgres profile. The problem is:</p><p>Slick postgres profile uses PGObject to communicate with the database. This is a feature supported by postgres JDBC driver. However, <strong>it stops you from using the codes on a H2 database in Postgres mode.</strong> For an obvious reason: <strong>H2 knows nothing of PGObject</strong>.</p><p>Checking the Slick github repo, you can find people discussing to make this java.time feature optional.</p><p>Any way, if you see error like this after the upgrade, read on.</p><pre>Cannot parse <strong>&quot;TIMESTAMP&quot; constant &quot;aced0005740018323031392d30352d30325430343a35323a32382e3735315a&quot;; </strong>SQL statement:<br>update &quot;security_user_passwords&quot; set &quot;user_id&quot; = ?, &quot;hasher&quot; = ?, &quot;salt&quot; = ?, &quot;password&quot; = ?, &quot;updated_by&quot; = ?, &quot;updated_at&quot; = ? where &quot;security_user_passwords&quot;.&quot;user_id&quot; = &#39;u3&#39; [22007-199]</pre><p>In my codebase, I used Instant for all my time field. Here’s what I did in my application.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2fad1eeefa543b2da9b50024424d1b77/href">https://medium.com/media/2fad1eeefa543b2da9b50024424d1b77/href</a></iframe><p>The above codes basically create a new Profile of my own, and use the standard setTimestamp / getTimemstamp to work with the database engine, where TIMESTAMP database type is used in both postgresql and H2.</p><blockquote>You should import this, not the default profile so that your application can make use of our new profile.</blockquote><blockquote>Also be advised, the above codes will lose nanoseconds precision on H2. I’m sure there’s a way to fix this, but I’m afraid nanosecond is not very critical in my case.</blockquote><p>In my opinion, a very good practice of all slick project is:</p><blockquote>Always create and use your own slick profile. It will prove to be very handy, and the imports can also be minimized and implicits can be maintained in a single place.</blockquote><h3>Evolution become very noisy</h3><p>The second thing I noticed is Evolution scripts were printed. The evolution were executed for almost all test cases of mine. I’ve to admit it’s a bit frustrating and maybe a little irritating seeing several thousands of evolution scripts printed each time test cases were executed. This is not a bug, but can greatly distract you when trying to diagnose a unit test failure.</p><p>Add the below to your logback.xml to mute it</p><pre>&lt;!-- Hide the evolution details when testing --&gt;<br>&lt;logger name=&quot;play.api.db.evolutions&quot; level=&quot;INFO&quot; /&gt;</pre><h3>Scala-guice stop working in some complicated generic cases</h3><p>Scala-guice was upgraded to 4.2.3 to support guice 4.2.2. The following was working in 4.1.1, but fail in 4.2.3.</p><pre>bind[GenericObjectPool[StatefulRedisConnection[String, Array[Byte]]]]<br>  .toProvider[StringBytesRedisConnectionPoolProvider]<br>  .in[Singleton]</pre><p>To remedy this, I’ve to fallback to the below guice standard syntax.</p><pre>type RedisConnection = StatefulRedisConnection[String, Array[Byte]]</pre><pre>bind[RedisConnectionPool](new TypeLiteral[RedisConnectionPool](){})<br>  .toProvider(<em>classOf</em>[StringBytesRedisConnectionPoolProvider])<br>  .in(<em>classOf</em>[Singleton])</pre><p>The other scala-guice bindings were fine. I guess this is only an issue of some really complex generic types.</p><h3>Related but not necessary</h3><h4>Upgrade H2 version to 1.4.199</h4><p>I also upgraded this simply because 1.4.199 is the latest version available. However, the case sensibility, or should I say the way to specify case sensibility, has changed from 1.4.194 -&gt; 1.4.199.</p><p>DB URL Before (1.4.194)</p><pre>jdbc:h2:mem:test;DATABASE_TO_UPPER=FALSE;MODE=PostgreSQL;DB_CLOSE_DELAY=-1</pre><p>DB URL After (1.4.199)</p><pre>jdbc:h2:mem:test;<strong>DATABASE_TO_LOWER=TRUE</strong>;MODE=PostgreSQL;DB_CLOSE_DELAY=-1</pre><p>If your evolution script failed to find a column that obviously exists, check the case sensibility settings.</p><p>This H2 version also enforce some new reserved word, “interval” for example. Craft your code carefully to get around it. The simplest solution is to double quote the column identifier in any of your raw sql statement.</p><h3>Conclusion</h3><p>All in all, I’m happy with the process of this version upgrade. The documents were very clear and precise. Deprecations were declared in advance and executed gradually to make the process a very smooth one. On the other hand, I still fail to see a very good reason to perform this play framework 2.7 upgrade, especially for a scala application. Weighing your options, and the issues you’re facing before deciding to migrate.</p><p><a href="https://www.facebook.com/sohoffice">sohoffice</a>, happy coding ~</p><p><strong>Did you learn something new? If so please:</strong></p><p>↓ <strong>clap 👏 button</strong> below️ so more people can see this.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=673242ba0da0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sohoffice/upgrading-to-play-framework-2-7-673242ba0da0">The Gotchas of Upgrading to Play Framework 2.7 and Slick 3.3.0</a> was originally published in <a href="https://medium.com/sohoffice">Sohoffice</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MDBootstrap meets Material CDK]]></title>
            <link>https://medium.com/sohoffice/mdbootstrap-meets-material-cdk-9526d22e7a44?source=rss-9a6805825a86------2</link>
            <guid isPermaLink="false">https://medium.com/p/9526d22e7a44</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[bootstrap]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Douglas Liu]]></dc:creator>
            <pubDate>Tue, 19 Mar 2019 08:16:46 GMT</pubDate>
            <atom:updated>2019-03-19T08:16:46.293Z</atom:updated>
            <content:encoded><![CDATA[<p>I love bootstrap. This component and style framework offers a system to create good frontend. <a href="https://mdbootstrap.com/docs/angular/">MDBootstrap</a> is an initiative to allow us to use bootstrap in Angular. However, Bootstrap is more focused on the components and styles themself. To make use these components and use them elegantly, we need some support between the foundation and the components.</p><p><a href="https://material.angular.io/cdk/categories">Angular Material CDK</a> can be used to bridge the gap, it offers some very nice infrastructure to build comprehensive UI on Angular. Today, I’m looking at a specific issue I had: <strong>To create a confirm dialog without having to embed the mdbModal html every time a simple confirmation is needed.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gQ59foq7GXqIW9A7" /><figcaption>Photo by <a href="https://unsplash.com/@cytonn_photography?utm_source=medium&amp;utm_medium=referral">Cytonn Photography</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This is what it takes to create a mdbModal in MDBootstrap.</p><pre>&lt;div mdbModal #frame=&quot;mdbModal&quot; class=&quot;modal fade&quot; id=&quot;frameModalTop&quot; tabindex=&quot;-1&quot; role=&quot;dialog&quot;<br>  aria-labelledby=&quot;myModalLabel&quot; aria-hidden=&quot;true&quot; (open)=&quot;onOpen($event)&quot;&gt;<br>  &lt;div class=&quot;modal-dialog modal-notify modal-success&quot; role=&quot;document&quot;&gt;<br>    &lt;div class=&quot;modal-content&quot;&gt;<br>      &lt;div class=&quot;modal-header&quot;&gt;<br>        &lt;p class=&quot;heading lead&quot;&gt;Modal Success&lt;/p&gt;<br><br>        &lt;button type=&quot;button&quot; class=&quot;close&quot; data-dismiss=&quot;modal&quot; aria-label=&quot;Close&quot; (click)=&quot;frame.hide()&quot;&gt;<br>          &lt;span aria-hidden=&quot;true&quot; class=&quot;white-text&quot;&gt;&amp;times;&lt;/span&gt;<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br><br>      &lt;div class=&quot;modal-body&quot;&gt;<br>        I&#39;m the modal body<br>      &lt;/div&gt;<br><br>      &lt;!--Footer--&gt;<br>      &lt;div class=&quot;modal-footer justify-content-center&quot;&gt;<br>        &lt;a type=&quot;button&quot; mdbBtn color=&quot;primary&quot; class=&quot;waves-light&quot; mdbWavesEffect&gt;Yes<br>          &lt;i class=&quot;far fa-gem ml-1&quot;&gt;&lt;/i&gt;<br>        &lt;/a&gt;<br>        &lt;a type=&quot;button&quot; mdbBtn color=&quot;primary&quot; outline=&quot;true&quot; class=&quot;waves-effect&quot; mdbWavesEffect (click)=&quot;frame.hide()&quot;<br>          data-dismiss=&quot;modal&quot;&gt;No&lt;/a&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>    &lt;!--/.Content--&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><p><strong>What a monster</strong> ! I honestly don’t think anyone would want to use the above just to create a Yes / No dialog.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wwK3DtohMXMorNZk" /><figcaption>Photo by <a href="https://unsplash.com/@blancotejedor?utm_source=medium&amp;utm_medium=referral">Aarón Blanco Tejedor</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The expected way to do a confirm dialog is a method that returns <strong>Observable&lt;boolean&gt;</strong>. Something similar to the below.</p><pre>const obs$: Observable&lt;boolean&gt; = this.commonDialog<br>  .openConfirmDialog(&#39;Please confirm&#39;, &#39;My message&#39;);</pre><h3>Take 1, An angular component</h3><p>I started by creating a new component. The component receives a title and message as input, and emits a boolean as output.</p><pre>&lt;app-confirm-dialog #confirm title=&quot;Please confirm&quot; message=&quot;My message&quot;&gt;&lt;/app-confirm-dialog&gt;</pre><p>This can work, but not to the extent I want it to be. When I wanted a confirmation, I most likely want to behave according to the output. As a result, the code is most likely needed in Typescript method, not html template. To get the handle of this dialog, I’ll have to use a <em>@ViewChild</em> in the component class, and this is definitely not ideal.</p><h3>Take 2, A service</h3><p>I then read the <a href="https://github.com/angular/material2/blob/master/src/lib/dialog/dialog.ts">source codes of MatDialog</a>, trying to understand how these things work. It turns out we can use a service.</p><p><strong>Wait, where should we put the modal content into if we’re using a service</strong> ?</p><p>Should we create an element under document body and remove it when the dialog was closed ?</p><h3>Take 3, Overlay</h3><p>The Material Overlay does exactly this, create an element under document body and attach your component into it. We can subscribe to the close event of mdbModal and detach the component from the Overlay.</p><p>The service code looks like this.</p><pre>@Injectable({<br>  providedIn: &#39;root&#39;<br>})<br><strong>export class </strong>CommonDialog {<br><br>  <strong>constructor</strong>(<strong>private </strong>overlay: Overlay,<br>              <strong>private </strong>injector: Injector) {<br>  }<br><br>  openConfirmDialog(title: <strong>string</strong>, content: <strong>string </strong>| ComponentType&lt;<strong>any</strong>&gt; | TemplateRef&lt;<strong>any</strong>&gt;) {<br>    <strong>const </strong>overlayRef = <strong>this</strong>.overlay.create(<strong>new </strong>OverlayConfig({<br>      positionStrategy: <strong>this</strong>.overlay.position().global(),<br>      hasBackdrop: <strong>false, </strong>disposeOnNavigation: <strong>true<br>    </strong>}));<br>    <strong>const </strong>modalComponent = <strong>new </strong>ComponentPortal(ConfirmDialogComponent, <strong>null</strong>, <strong>this</strong>.injector);<br>    <strong>const </strong>ref = overlayRef.attach(modalComponent);<br>    <strong>return </strong>ref.instance.display(title, content).pipe(<br>      tap(() =&gt; {<br>        // destroy the ref and detach from the overlay<br>        ref.destroy();<br>        overlayRef.detach();<br>      })<br>    );<br>  }<br>}</pre><p>A few explanations.</p><ol><li>We don’t care the position of the overlay. The actual position is controlled by mdbModal (encapsulated in ConfirmDialogComponent). What we want from Overlay is simply a place to put the mdbModal into.</li><li>We don’t need the Overlay backdrop, mdbModal has it’s own backdrop anyway.</li><li>The ConfirmDialogComponent.display() method is where I bind the dialog title and content, and return a subject. The subject will emit when ‘Yes’ or ‘No’ button is clicked. (Or if the dialog is closed without answer) I also use Material CDK Portal in this method so that the content can accept either another component or a template fragment.</li></ol><h4>Gotchas</h4><p>A small tweak was needed for the dialog to work. The CDK Overlay has a z-index of 1000, which is very high. However, the z-index of the mdbModal backdrop is even higher with the value of 1040. You’ll have to either increase the z-index of cdk overlay or decrease the z-index of mdbModal backdrop.</p><pre>.cdk-overlay-container {<br>  z-index: 1050;<br>}</pre><h3>Final Results</h3><p>This is how I use the confirm dialog in the end.</p><pre>constructor(<strong>private </strong>commonDialog: CommonDialog) {}</pre><pre>onAction(check: TemplateRef&lt;any&gt; | string) {<br>  <strong>this.commonDialog.openConfirmDialog(&#39;Please confirm&#39;, check)</strong>.pipe(<br>    filter(identity),<br>    tap(() =&gt; do_something())<br>  ).subscribe();<br>}</pre><p>The other commonly used dialogs can be added in a similar way.</p><p><strong>Did you learn something new? If so please:</strong></p><p>↓ <strong>clap 👏 button</strong> below️ so more people can see this</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9526d22e7a44" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sohoffice/mdbootstrap-meets-material-cdk-9526d22e7a44">MDBootstrap meets Material CDK</a> was originally published in <a href="https://medium.com/sohoffice">Sohoffice</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fair Play, the RxJS Race]]></title>
            <link>https://medium.com/sohoffice/fair-play-the-rxjs-race-1b35c6160736?source=rss-9a6805825a86------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b35c6160736</guid>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Douglas Liu]]></dc:creator>
            <pubDate>Fri, 22 Feb 2019 04:55:38 GMT</pubDate>
            <atom:updated>2019-02-22T04:59:02.523Z</atom:updated>
            <content:encoded><![CDATA[<h4>The race may only have one winner, but it can be stopped by anybody.</h4><p>I was working on an issue where I was using a nested race inside a switchMap operator. One of the racer was created with interval, but it was never triggered, no matter how long I waited.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kAuV2fZ0tkBcOWb6" /><figcaption>Photo by <a href="https://unsplash.com/@pietromattia?utm_source=medium&amp;utm_medium=referral">Pietro Mattia</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Let’s say the Turtle and the Rabbit is having another legendary race. However, an alien is trying to intervene. We can’t allow the game be interrupted by extraterrestrial being, so we’ve set a filter to protect the game.</p><pre>const source = race(<br>  interval(3000).pipe(mapTo(&#39;Turtle&#39;)),<br>  interval(1000).pipe(mapTo(&#39;Rabbit&#39;)),<br>  of(&#39;Alien&#39;).pipe(<br>    <strong>filter(x =&gt; x === &#39;Earthling&#39;)</strong><br>  )<br>).pipe(first());</pre><pre><strong>// Wanted Rabbit<br>// But prints nothing</strong></pre><p><strong>This race will not have a winner</strong>. See the stackblitz below. (Click on SHOW EMBED to see the snippet runs)</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Frxjs-yturgd%3Fembed%3D1%26file%3Dindex.ts&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Frxjs-yturgd%3Fembed%3D1%26file%3Dindex.ts&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/7afce41b8b15413318d9dba914288453/href">https://medium.com/media/7afce41b8b15413318d9dba914288453/href</a></iframe><p>Check the subscribe log and you’ll find out this error Error: no elements in sequence. However, if we remove the filter from of(), Alienwill prevail.</p><pre>const source = race(<br>  interval(3000).pipe(mapTo(&#39;Turtle&#39;)),<br>  interval(1000).pipe(mapTo(&#39;Rabbit&#39;)),<br>  <strong>of(&#39;Alien&#39;)</strong><br>).pipe(first());</pre><pre>// prints &#39;Alien&#39;</pre><p><em>Looks like the game can only be won by Alien</em> !</p><p>Not true, we could have changed the of operator to a different creator. Say for example, we can use an <strong>Observable.create() </strong>to replace the of().</p><pre>const source = race(<br>  interval(3000).pipe(mapTo(&#39;Turtle&#39;)),<br>  interval(1000).pipe(mapTo(&#39;Rabbit&#39;)),<br><strong>  Observable.create(obs =&gt; obs.next(&#39;Alien&#39;)).pipe(<br>    filter(x =&gt; x === &#39;Earthling&#39;)<br>  )<br></strong>).pipe(first());</pre><pre><strong>// prints &#39;Rabbit&#39;</strong></pre><h3>Explanations</h3><p><strong>The race was simply stopped</strong>. When you used the of() operator, it will emit one value and complete immediately. It looks like the following:</p><pre>1. observer.next(&#39;Alien&#39;)<br>2. observer.complete()</pre><p>When we added the filter onto the Observable, it will successfully filter out the value emitted by of, which makes this stream empty. The following complete() call will thereafter stop the race, <strong>no winner of the game</strong>. This is the reason why you see the error Error: no elements in sequence.</p><p>When we removed the filter() from of() observable, the emitted value immediately win the race. However, if you observed the stream, you’ll find out it will only contain one element.</p><p>Using Observable.create() or other observable creator will not stop the stream, so the race continue and you can filter on it as expected.</p><p><strong>Did you learn something new? If so please:</strong></p><p>↓ <strong>clap 👏 button</strong> below️ so more people can see this</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b35c6160736" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sohoffice/fair-play-the-rxjs-race-1b35c6160736">Fair Play, the RxJS Race</a> was originally published in <a href="https://medium.com/sohoffice">Sohoffice</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Square Surround A Line]]></title>
            <link>https://medium.com/@sohoffice/square-surround-a-line-26d9a0d6d043?source=rss-9a6805825a86------2</link>
            <guid isPermaLink="false">https://medium.com/p/26d9a0d6d043</guid>
            <category><![CDATA[intellij]]></category>
            <category><![CDATA[inline-document]]></category>
            <category><![CDATA[tools]]></category>
            <category><![CDATA[code-readability]]></category>
            <dc:creator><![CDATA[Douglas Liu]]></dc:creator>
            <pubDate>Mon, 11 Feb 2019 08:59:17 GMT</pubDate>
            <atom:updated>2019-03-03T00:30:54.297Z</atom:updated>
            <content:encoded><![CDATA[<h3>Square Surround A Comment Line</h3><h4>Draw a beautiful square surrounding your comment with IntelliJ.</h4><p>I sometimes find the comments in my codes …. <strong>not significant</strong> enough.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8HWnrljNhy9ncBHkwLr3fA.png" /></figure><p>Say for example, I’ve a scalatest test case (see left image), which tests various cases of a Frontend API. The API has a handful endpoints, but each endpoint will need several different cases to cover. It’s natural to put all these test cases in a single file. But navigating in this single file has quickly become a burden.</p><p>I tell myself, yes, I can draw a nice bracket surround my comment so I can distinguish the codes a little bit easier.</p><pre>/* <br> * +----------------+<br> * | signUp section |<br> * +----------------+<br> */</pre><p>This is great. But it took 30 seconds to draw a square. That sounds like forever.</p><p>This is the solution I come up with:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*uCfDq3Fkedt04bslmJsMpQ.gif" /><figcaption>Select a line (in comment) and surround it with a square.</figcaption></figure><p>This is actually a surrounding live template. Here’s how:</p><ol><li>Go to live templates in IntelliJ settings</li><li>Create a new live template and name it as single_line_surround_square</li><li>Use the below as the template text</li></ol><pre>+$DASHES$+<br>* | $SELECTION$ |<br>* +$DASHES$+</pre><p>4. Define the Applicable Contexts</p><p>5. I chose Scala Comment and Java Comment. But you could have choose the other languages.</p><p>6. Choose Edit Variables</p><p>7. Use the below as the Expression in variable DASHES</p><pre>$groovyScript(&quot;&#39;-&#39; * (_1.length() + 2)&quot;, SELECTION)$</pre><p>8. Tick the Skip if defined check box of DASHES</p><p>9. Press OK to save it.</p><p>And voila, you’re done.</p><p>In order to use this small trick. You’ll need to surround a line in any Java / Scala comment and use Surround with editor action. It has a hot key, which you should already be aware of, because it’s very handy to add try-catch block and something the like. But in case you don’t know the hot key, please visit the top “Code” menu to find out.</p><p>If you would like to further segment your code, you may also use the Editor fold Comment. I personally like to combine both techniques. The Editor fold can collapse everything in between (but it takes a few seconds to become usable) which is useful when your class is truly big. While a square comment is very significant even though nothing was collapsed. Besides, it looks pretty :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ET8tPHym4_c61_TqZBT7tA.png" /><figcaption>Combining editor fold with square surrounded comments</figcaption></figure><p>The trick may deserve a little explanation.</p><ol><li>$SELECTION$ is a pre-defined variable. Your live template show up in Surround with only when it has this variable.</li><li>$DASHES$ is a user defined variable. It can have a wide variety range of expression, which defines the value substitution when used.</li><li>The expression of groovyScript(&quot;&#39;-&#39; * (_1.length() + 2)&quot;, SELECTION) is a snippet of groovy script. Basically _1 is the first argument, in this case the SELECTION variable. We calculated the length and make it the dashes string we want.</li><li>Skip if defined means we don’t need user to input anything to this variable.</li></ol><p>I haven’t tested but I believe the trick should also work in PyCharm, WebStorm and other JetBrain product.</p><h3>Enhanced the square</h3><p>The square can look prettier. By following the instructions on <a href="https://en.wikipedia.org/wiki/Box-drawing_character">wikipedia</a>, you can make all kind of squares you wanted. Here’s an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*feqDPVGVDq822p3ZYOz-hA.png" /></figure><p>Do the following on top of the above steps:</p><ul><li>Use the alternative template text</li></ul><pre>┌$DASHES$┐<br>* │ $SELECTION$ │<br>* └$DASHES$┘</pre><ul><li>Use the alternative expression for DASHES variable.</li></ul><pre>groovyScript(&quot;&#39;─&#39; * (_1.length() + 2)&quot;, SELECTION)</pre><p><strong>Did you learn something new? If so please:</strong></p><p>↓ <strong>clap 👏 button</strong> below️ so more people can see this</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26d9a0d6d043" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The API First Strategy — Use swagger to generate API client as an Angular library]]></title>
            <link>https://medium.com/sohoffice/the-api-first-strategy-use-swagger-to-generate-api-client-as-an-angular-library-66964ea43587?source=rss-9a6805825a86------2</link>
            <guid isPermaLink="false">https://medium.com/p/66964ea43587</guid>
            <category><![CDATA[swagger]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Douglas Liu]]></dc:creator>
            <pubDate>Fri, 01 Feb 2019 08:07:12 GMT</pubDate>
            <atom:updated>2019-05-07T03:09:57.542Z</atom:updated>
            <content:encoded><![CDATA[<h3>Use swagger to generate API client as an Angular library</h3><h4>Spend your time on things that really matter. For example, writes your API doc. Let the API client be generated with peace of mind.</h4><blockquote>Life before Death.<br>Strength before Weakness.<br>Journey before Destination. — Brandon Sanderson</blockquote><p>I love the Stormlight Archive. Although I hope Mr. Sanderson can finish it a little bit sooner. But I guess waiting is also part of the fun. Nevertheless, this quote has some similarity to what I’m going to talk about, with a minor modification.</p><blockquote>API before frontend development.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MXOe_xOPawgiuA1o" /><figcaption>Photo by <a href="https://unsplash.com/@agkdesign?utm_source=medium&amp;utm_medium=referral">Alex Knight</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I’ve been there, when the frontend have to work with the API with no documentation at all. You’ll have to code (or waste your time) on the request and response interface. And call your API endpoint with jQuery or $q. You’ll be very tempted to skip the transfer object declaration, but you’ll regret it by the time someone else in your server team changed the API definitions.</p><p>With the help of swagger, things are much simpler.</p><blockquote>All endpoints will be generated as a service and they all return an Observable with corresponding type !</blockquote><h3>1. Create an angular library</h3><p>I’ve tried the non library approach, to generate the API client in the primary src folder. I’ve to say, it’s quite messy. As the generated codes are mixed with the other, you’ll have git ignore them directory by directory. What makes it worse, you’ll have to handle deletion. As the API evolves, you’ll drop models, rename the API more often than you think. Re-generating new API may override the one with the same name, but will not automatically delete the ones with different names.</p><p>Use the angular library approach, it’s as simple as deleting the library src folder right before swagger codegen executes to get a clean build.</p><pre>ng generate library foo-swagger-client</pre><h3>2. Tidy up the angular library</h3><p>Angular CLI will generate the library project for you. You should find it in the projects/foo-swagger-client directory. It also generates a component and a service which is of little usefulness in our scenario. Let’s remove the entire src folder. In our case the projects/foo-swagger-client/src.</p><h3>3. Generate the API client</h3><p>Let’s suppose you’ve ready your API spec document. We’ll use swagger-codegen to generate the API client now. If you’re on Angular 7, read <a href="https://medium.com/@sohoffice/upgrade-your-swagger-generated-angular-project-to-angular-7-a99ddb94f87c">my other article</a> to find out how.</p><p>Here, I’ll use swagger-codegen 2.4.0 via docker.</p><pre>rm -rf projects/foo-swagger-client/src</pre><pre><em>mkdir </em>-p tmp<br>SPECFILE=tmp/spec.json<br><em>wget </em>--quiet --no-check-certificate <strong>$SPECURL</strong> -O $SPECFILE</pre><pre><em>docker </em>run --rm --net=host -u=&quot;<strong>$</strong>(id -u)&quot; -v <strong>$</strong>{PWD}:/local swaggerapi/swagger-codegen-cli:2.4.0 generate \<br>    -i /local/$SPECFILE \<br>    -l typescript-angular \<br>    -o /local/projects/<strong>foo-swagger-client</strong>/src \<br>    --additional-properties ngVersion=7.2.0</pre><p>The commands use wget to download the spec file from <strong>$SPECURL</strong>. This should point to your spec file. I use wget to get around the self-signed certificate issue, so that the script works for all environments.</p><p>Now, let’s take a look at your <strong>foo-swagger-client</strong> library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gzlZV1JQuf8e3qtQUwLikw.png" /><figcaption>Generated from <a href="https://petstore.swagger.io/v2/swagger.json">https://petstore.swagger.io/v2/swagger.json</a></figcaption></figure><p><strong>api</strong> contains all the services that you’ll be using. All endpoints have been generated as a dependency injectable service and they all return an Observable with corresponding type !</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ruREaG8HoPfhAye5WITfjg.png" /><figcaption>A method in PetService</figcaption></figure><h3>4. Update the entryFile</h3><p>The Angular library project is almost completed, with one more step to do. We need to tell Angular the entry point of this library. Swagger has generated the entry file index.ts for us, we just have to tell Angular about it. Modify it in the file projects/foo-swagger-client/ng-package.json.</p><p>We can now build the library project.</p><pre>ng build foo-swagger-client</pre><h3>5. Use the API client</h3><p>First, add it to your AppModule.</p><pre>import<strong> </strong>{ApiModule} from<strong> </strong>&#39;<strong>foo-swagger-client</strong>&#39;;</pre><pre>@NgModule({<br>  declarations: [<br>    AppComponent<br>  ],<br>  imports: [<br>    ...<br>    <strong>ApiModule.<em>forRoot</em></strong>(IdentityService.<em>getApiConfiguration</em>),<br>    ...<br>})<br>export class<strong> </strong>AppModule {<br>}</pre><p><strong>IdentityService.getApiConfiguration()</strong> is a static method where you can provide API configuration. You usually will want to populate the authentication token in this method.</p><p>Note, the import is ‘foo-swagger-client’ rather than relative path. The library is provided as if it is a npm module. This is especially true in development mode where ng serve automatically picks up the library. This is achieved by the paths config in tsconfig.json in the project root folder. Please note: <strong>the paths trick only works for typescript compiler</strong>. When I tried to use it in my Angular Universal project, the build simply fails and I have to use npm link to remedy it.</p><p>I haven’t tried it but I think importing from relative path should also work. However using the library module name gives you more flexibility in the future. You may want to publish your library to npm some day.</p><h3>Conclusion</h3><p>I recommend all of you give swagger a try, it definitely worth the time.</p><p>Type checking is a blessing of Angular (actually Typescript). Don’t be afraid to improve your API. Just use 10 seconds to re-generate the API client and see the compiler complains. You’ll soon find out where to refactor your codes!</p><p>I’ll write another article about how the spec can be created from a play framework application. It’s not related to Angular, but come back later if you’re interested.</p><h4>More on #Swagger</h4><p><a href="https://medium.com/sohoffice/descriptive-play-swagger-now-supports-play-framework-2-7-d9e6c22c5013">descriptive-play-swagger now supports Play framework 2.7</a></p><p><strong>Did you learn something new? If so please:</strong></p><p>↓ <strong>clap 👏 button</strong> below️ so more people can see this</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66964ea43587" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sohoffice/the-api-first-strategy-use-swagger-to-generate-api-client-as-an-angular-library-66964ea43587">The API First Strategy — Use swagger to generate API client as an Angular library</a> was originally published in <a href="https://medium.com/sohoffice">Sohoffice</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hi, I’ve sent you a mat-card.]]></title>
            <link>https://medium.com/sohoffice/sent-an-angular-mat-card-email-893a1adb2ceb?source=rss-9a6805825a86------2</link>
            <guid isPermaLink="false">https://medium.com/p/893a1adb2ceb</guid>
            <category><![CDATA[email]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular-universal]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Douglas Liu]]></dc:creator>
            <pubDate>Sun, 13 Jan 2019 05:19:49 GMT</pubDate>
            <atom:updated>2019-05-14T10:07:52.553Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hi, I’ve sent you a mat-card</h3><p>We may not be reading emails, but sending emails is still an essential part of an application. Angular, as a client side framework that uses a lot of Javascript, is not naturally a good fit to compose emails. However, it’s not impossible!</p><p>Read on to see how you can send a &lt;mat-card /&gt; or page made of other Angular components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_DnMMLaixymMRzhd" /><figcaption>Photo by <a href="https://unsplash.com/@alvaroserrano?utm_source=medium&amp;utm_medium=referral">Álvaro Serrano</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Use the below link to send yourself a &lt;mat-card /&gt; before jumping into the details.</p><p><a href="https://sohoffice.github.io/angular-universalize-email-demo">Send a welcome letter made of mat-card.</a></p><h3>How ?</h3><p>In your frontend project, create a page for our new welcome email. Note, you most likely will want it to be separated with your primary frontend project. Simply create a new sub project to hold all emails and install the npm module angular-universalize-email.</p><p>Check my other article for the setup steps:</p><p><a href="https://medium.com/@sohoffice/streamline-your-email-template-development-with-angular-25630a27c7dd">Create your email template with Angular</a></p><h4>Write scala template for play framework</h4><p>Now, add a new page and give it a routing, say for example, /email/welcome.</p><pre>&lt;!--<br><em># This block will be removed by the process pipeline.<br># At the moment only served as reminder to human.</em><br>Header: @(email: String, username: Option[String])<br>--&gt;<br><br>&lt;div class=&quot;container mt-1 nue-email&quot;&gt;<br>  &lt;div class=&quot;d-none&quot;&gt;<br>    Add text here, this will be used by Gmail as preview.<br>  &lt;/div&gt;<br><br>  &lt;mat-card class=&quot;fill-x fill-t&quot;&gt;<br>    &lt;mat-card-header class=&quot;mat-primary mb-5&quot;&gt;<br>      &lt;mat-card-title class=&quot;mat-display-3&quot;&gt;<br>        angular-universalize-email<br>      &lt;/mat-card-title&gt;<br>    &lt;/mat-card-header&gt;<br>    &lt;mat-card-content&gt;<br>      &lt;p&gt;<br><strong>        @if(username) &lt;nue-b&gt;<br>          Hi @username.get:<br>        &lt;/nue-b&gt; else &lt;nue-b&gt;<br>          Hi my friend:<br>        &lt;/nue-b&gt;<br></strong>      &lt;/p&gt;<br><br>      &lt;div class=&quot;mb-3&quot;&gt;<br>        &lt;b&gt;Add buttons&lt;/b&gt;<br>        &lt;br&gt;<br><br>        &lt;a href=&quot;https://github.com/sohoffice/angular-universalize-email&quot; mat-button class=&quot;mr-1&quot;&gt;Github&lt;/a&gt;<br>        &lt;a href=&quot;https://www.npmjs.com/package/angular-universalize-email&quot; mat-button class=&quot;mr-1&quot;&gt;NPM&lt;/a&gt;<br>        &lt;a href=&quot;https://sohoffice.github.io/angular-universalize-email&quot; mat-button class=&quot;mr-1&quot;&gt;Demo&lt;/a&gt;<br>      &lt;/div&gt;<br>    &lt;/mat-card-content&gt;<br>  &lt;/mat-card&gt;<br><br>&lt;/div&gt;</pre><p>As you can see, you may use some common Angular material directives, for example the mat-card, mat-button or mat-toolbar. When you have to use braces, use the nue-extension tags. See the <a href="https://github.com/sohoffice/angular-universalize-email#nue-extension-tags">project document</a> for other extension tags you may use.</p><blockquote>It should work with other server side technology. If you have the need, please contact me and we can see how to make it work.</blockquote><h4>Include styles</h4><p>Add the below to your styles.scss (of the email application)</p><pre><em>/* angular-universalize-email styles */<br></em>@import &quot;~angular-universalize-email/styles.css&quot;;</pre><p>The styles won’t do much for you, but it can get you started.</p><h4>Check your email in browser</h4><p>Just spin up your test server with ng serve --ssl --project email. Go to <a href="https://localhost:4200/email/welcome">https://localhost:4200/email/welcome</a> to see how it looks.</p><h4>Build the email application</h4><pre>ng build --extract-css --project email &amp;&amp; ng run email:server</pre><p>After this step, you should have dist/email and dist/email-server folder.</p><h4>Generate the template</h4><pre><em>./node_modules/.bin/angular-universalize-email \<br>  </em>-a ./dist/email \<br>  -A ./dist/email-server \<br>  -o ../my-server/frontend/app/views/emails \<br>  -p &#39;{camel}.scala.html&#39; \<br>  --prepend &#39;@(email: String, username: Option[String])&#39; \<br>  &quot;/email/welcome&quot;</pre><p>Invoke angular-universalize-email with these information:</p><ul><li>Browser assets: ./dist/email</li><li>Server assets: ./dist/email-server</li><li>Output path: ../my-server/frontend/app/views/emails</li><li>Output filename pattern: In this case, the output will be emailWelcome.scala.html.</li><li>Prepend a line in the beginning of the output</li><li>The URL is /email/welcome</li></ul><p>You should now have an emailWelcome.scala.html at your disposal in your play framework application.</p><h3>Best practices</h3><ul><li>Use template engine. This saves can you a lot of time. If you’re using node, you may try Mustache.</li><li>Send email through your server with data fields as parameters. <strong>Do not send the entire mail body from your Angular client</strong>. If you’re serverless, use mail provider like Amazon SES. (but you wouldn’t need this guide)</li><li>Use capitalized sender name. I find sender in all lower case letters is not clear enough to bring attention.</li><li>Use concise email subject. Put the important part in the front. Your subject may be truncated, depending on the screen size. (Think about cell phones.)</li></ul><h3>Conclusion</h3><p>The email may not look 100% the same. As a lot of CSS styles were not accepted by Gmail. For example: box-shadow, position, negative margins. I also can’t get media queries to work. But I like how it turns out. Especially when it allows me to continue to use a single frontend technology for emails.</p><p><strong>Did you learn something new? If so please:</strong></p><p>↓ <strong>clap 👏 button</strong> below️ so more people can see this</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=893a1adb2ceb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sohoffice/sent-an-angular-mat-card-email-893a1adb2ceb">Hi, I’ve sent you a mat-card.</a> was originally published in <a href="https://medium.com/sohoffice">Sohoffice</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[404 page for github pages]]></title>
            <link>https://medium.com/sohoffice/404-page-for-github-pages-923d73c9ac8?source=rss-9a6805825a86------2</link>
            <guid isPermaLink="false">https://medium.com/p/923d73c9ac8</guid>
            <category><![CDATA[github-pages]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Douglas Liu]]></dc:creator>
            <pubDate>Sat, 12 Jan 2019 02:51:44 GMT</pubDate>
            <atom:updated>2019-02-15T04:42:39.753Z</atom:updated>
            <content:encoded><![CDATA[<p>When deploying <a href="https://sohoffice.github.io/angular-universalize-email/home">my Angular project</a> on github, I realize the routing wasn’t working. Since we can’t configure github to fallback to index.html, we’ll have to use a 404.html. In the <a href="https://angular.io/guide/deployment#deploy-to-github-pages">Angular document</a>, it says make a copy of index.html and name it 404.html.</p><p>This is not working.</p><p>After some research, here’s the right way to display your 404 page on github.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gDrYqUImT1S3zg2M" /><figcaption>Photo by <a href="https://unsplash.com/@e_sykes?utm_source=medium&amp;utm_medium=referral">Ethan Sykes</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Simply put, you must add the below in the beginning of your 404.html</p><pre>---<br>permalink: /404.html<br>---</pre><pre>&lt;The rest of your 404.html&gt;</pre><p>If you’re using Angular on Mac or Unix, do the below:</p><pre><strong>GITHUB_USER</strong>=&lt;your github user&gt;<br><strong>PROJECT</strong>=&lt;your github project&gt;</pre><pre># Build the project first.<br>ng build --prod --deploy-url=https://<strong>$GITHUB_USER</strong>.github.io/<strong>$PROJECT</strong>/ --base-href=/<strong>$PROJECT</strong></pre><pre># Instead of copying index.html, echo and cat the content so that `YAML front matter` was added.<br><em>echo </em>&quot;---<br>permalink: /404.html<br>---<br>&quot; <em>&gt; &quot;./dist/</em><strong><em>$PROJECT</em></strong><em>/404.html&quot;<br>cat </em>&quot;./dist/<strong>$PROJECT</strong>/index.html&quot; <em>&gt;&gt; &quot;./dist/</em><strong><em>$PROJECT</em></strong><em>/404.html&quot;</em></pre><p>This is not just for Angular, all 404.html on github page should follow.</p><p><strong>Did you learn something new? If so please:</strong></p><p>↓ <strong>clap 👏 button</strong> below️ so more people can see this</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=923d73c9ac8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sohoffice/404-page-for-github-pages-923d73c9ac8">404 page for github pages</a> was originally published in <a href="https://medium.com/sohoffice">Sohoffice</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>