Friday, July 24, 2015

Android Studio - Displaying List View Inside AlertDialog

Android Studio - Displaying List View Inside AlertDialog


1.) Follow this code:
================
>Note: custom_dialog_layout.xml is the layout that will pop-up
>Note: row.xml is the item used for populating row
AlertDialog.Builder  builder = new AlertDialog.Builder(new ContextThemeWrapper(MainActivity.this, android.R.style.Theme_Holo));

builder.setTitle("Custom Dialog");

View customView = LayoutInflater.from(MainActivity.this).inflate(R.layout.custom_dialog_layout, null, false);

ListView listList1 = (ListView)customView.findViewById(R.id.listView1);
String[] stringArray1 = new String[] { "Bright Mode", "Normal Mode" };
ArrayAdapter adapter1 = new MyListAdapter(MainActivity.this, R.layout.row, stringArray1);
listList1.setAdapter(adapter1);

builder.setView(customView);

builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
       //Ok

    }
});

builder.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
        //Cancel
    }
});

builder.show();

Android Studio - Creating Material Design App Bar

Android Studio - Creating Material Design App Bar


1.) Set-up the color that we'll use for the app bar:
========================================
>Create a new xml inside values and name it color.xml
<resources>
    <color name="ColorPrimary">#FF5722</color>
    <color name="ColorPrimaryDark">#E64A19</color>
</resources>

2.) Using the previously declared color, change the style.xml to apply the colors:
=================================================================

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">@color/ColorPrimary</item>
        <item name="colorPrimaryDark">@color/ColorPrimaryDark</item>
        <!-- Customize your theme here. -->
    </style>
</resources>

3.) Make a tool bar:
================
>Create a new xml layout file and name it tool_bar.xml
<span style="font-size: x-small;"><?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/ColorPrimary"
    android:elevation="4dp"
 
    >
 
</android.support.v7.widget.Toolbar>
 
</span>

4.) Use the tool bar:
================
>Insert this code to wherever xml layout you want to display the tool bar
<include
        android:id="@+id/tool_bar"
        layout="@layout/tool_bar"
        ></include>

5.) Adding additional buttons inside the app bar:
=======================================
>Go to menu_main.xml and add/paste the code below
 <item
        android:id="@+id/action_user"
        android:orderInCategory="300"
        android:title="User"
        android:icon="@drawable/ic_launcher"
        app:showAsAction="ifRoom"></item>

Tuesday, July 07, 2015

How to generate jax-rs documentation using maven

To generate the jax-rs documentation automatically using maven, we need to add some plugins in the build section of the project's pom file.

To avoid running this plugin every time you invoke mvn install, you can create a separate profile for it.

Here's the plugin definition:

<build>
 <pluginManagement>
  <plugins>
   <plugin>
    <groupId>org.eclipse.m2e</groupId>
    <artifactId>lifecycle-mapping</artifactId>
    <version>1.0.0</version>
    <configuration>
     <lifecycleMappingMetadata>
      <pluginExecutions>
       <pluginExecution>
        <pluginExecutionFilter>
         <groupId>org.codehaus.enunciate</groupId>
         <artifactId>maven-enunciate-plugin</artifactId>
         <versionRange>[1.29,)</versionRange>
         <goals>
          <goal>docs</goal>
         </goals>
        </pluginExecutionFilter>
        <action>
         <ignore></ignore>
        </action>
       </pluginExecution>
      </pluginExecutions>
     </lifecycleMappingMetadata>
    </configuration>
   </plugin>
  </plugins>
 </pluginManagement>

 <plugins>
  <plugin>
   <groupId>org.codehaus.enunciate</groupId>
   <artifactId>maven-enunciate-plugin</artifactId>
   <version>1.29</version>
   <executions>
    <execution>
     <goals>
      <goal>docs</goal>
     </goals>
     <configuration>
      <docsDir>${project.build.directory}/docs</docsDir>
      <configFile>src/main/resources/enunciate.xml</configFile>
     </configuration>
    </execution>
   </executions>
  </plugin>

  <plugin>
   <artifactId>maven-resources-plugin</artifactId>
   <version>2.5</version>
   <executions>
    <execution>
     <id>copy-resources</id>
     <phase>validate</phase>
     <goals>
      <goal>copy-resources</goal>
     </goals>
     <configuration>
      <outputDirectory>${basedir}/target/generated-resources/schemagen/</outputDirectory>
      <resources>
       <resource>
        <directory>${basedir}/src/main/resources/</directory>
        <includes>
         <include>jaxb.properties</include>
        </includes>
       </resource>
      </resources>
     </configuration>
    </execution>
   </executions>
  </plugin>
 </pluginManagement>
</build>

And here's the content of enunciate.xml.
<?xml version="1.0"?>
<enunciate label="novaglobalapi" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:noNamespaceSchemaLocation="http://enunciate.codehaus.org/schemas/enunciate-1.25.xsd">

 <api-classes>
  <include pattern="org.broodcamp.api.rest.**" />
 </api-classes>

 <modules>
  <docs docsDir="restapi" title="Broodcamp REST API" />
  <c disabled="true" />
  <csharp disabled="true" />
  <obj-c disabled="true" />
 </modules>
</enunciate>

Wednesday, July 01, 2015

Swift - Displaying Actionsheet for Ipad and Iphone

Swift - Displaying Actionsheet for Ipad and Iphone

A simple tutorial on making an alert view of type action sheet that works for iphone and ipad.



1.) First you'll need a button where you can attach your pop over when you're using iPad (in iPhone it not necessary). Then you'll have to create an outlet for the button (in my example i named it "btn_button") so we can determine the pop over location based on where the button is placed inside the viewcontroller.

2.) Inside the button's action, paste the following lines of code:

 let optionMenu = UIAlertController(title: "Choose Your Option", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
        
        let option1 = UIAlertAction(title: "Option 1", style: .Default, handler: {
            
            (alert: UIAlertAction!) -> Void in
            println("Option 1")
        })
        
        let option2 = UIAlertAction(title: "Option ", style: .Default, handler: {
            
            (alert: UIAlertAction!) -> Void in
            println("Option 2")
        })
        
        let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: {
            (alert: UIAlertAction!) -> Void in
            println("Cancelled")
        })
        
        optionMenu.addAction(option1)
        optionMenu.addAction(option2)
        optionMenu.addAction(cancelAction)
        
        
        if ( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.Pad )
        {
            if let currentPopoverpresentioncontroller = optionMenu.popoverPresentationController{
                currentPopoverpresentioncontroller.sourceView = btn_button
                currentPopoverpresentioncontroller.sourceRect = btn_button.bounds;
                currentPopoverpresentioncontroller.permittedArrowDirections = UIPopoverArrowDirection.Up;
                self.presentViewController(optionMenu, animated: true, completion: nil)
            }
        }else{
            self.presentViewController(optionMenu, animated: true, completion: nil)
        }
        
      
The code is pretty straight forward:
-First we declare a UIAlertController where we can put our buttons.
-Second we created the buttons (Option1, Option2, and Cancel) and then we add the buttons inside the alert controller.
-Last we use the UI_USER_INTERFACE_IDIOM to determine if the device/emulator is an ipad or an iphone and do the necessary presentation for each particular device.

Wednesday, June 17, 2015

How to migrate your Godaddy web hosting to DigitalOcean

Lately I've been reading some good articles about DigitalOcean as a cheap VPS option in online hosting and so I decided to try and subscribe to one.

Since my wordpress website hosting is already expiring I decided to moved the hosting to DigitalOcean and renew the domain name in Godaddy.

Here's how I point my Godaddy domain to DigitalOcean VPS hosting and migrate my wordpress website:

*You must already have a DigitalOcean account with linked payment method (can be either a credit card or paypal).
*Copy all your wordpress files from Godaddy.
*Make a backup of your wordpress database.


  1. Create a droplet in digital ocean.
    1. Distribution = 15.04 x64
    2. Applications = Wordpress 14.04
    3. I chose $5 / month
  2. Follow this article to configure your server: https://www.digitalocean.com/community/tutorials/how-to-install-wordpress-on-ubuntu-14-04.
  3. Migrating your wordpress website:
    1. Using winscp, upload your files in your server's /var/www folder.
    2. Make sure that www-data user can write to the folders where it needed to, for example uploads. Note: use chmod. Note by default the uploaded files are owned by root, use chown and change the ownership to www-data.
      1. >chown www-data:www-data /var/www -R, change the owner and group of /var/www folder from root to www-data. This is done recursively.
      2. >chmod 774, means owner and group (read, write, execute) while others (read-only).
    3. Following the tutorial in #2, you should now have phpmyadmin installed. Restore your wordpress backup.
  4. We then need to point your domain name to the new ip address in digital ocean.
    1. To get your droplet's ip address, go to your digital ocean's droplet's page 
  5. Now that you have your ip address, go to DNS, and add a domain record like this: 
  6. We are done with digital ocean and we will now point godaddy's domain to digital ocean's server.
  7. In Godaddy expand Domains tab.
  8. Chose your domain then click Manage.
  9. In Settings tab, under Nameservers click Manage.
  10. Setup Type=Custom, then add the 3 nameservers below
    1. NS1.DIGITALOCEAN.COM
    2. NS2.DIGITALOCEAN.COM
    3. NS3.DIGITALOCEAN.COM 
  11. After adding hit SAVE.
  12. You should now see the 3 name servers in the next screen.
Wait for 5minutes, then try logging-in in your linux hosting, and in the terminal run:
>whois makeupchum.com

The command above should give you your digital ocean's ip address and name servers.

And that's it! Your wordpress website must now be running in digital ocean. That's in less than 30mins :-)

Common problems I've encountered:

  1. 2 widget were broken, need to set the content again
  2. some folders are not writeable when I uploaded need to execute chmod.
Want to try DigitalOcean? Register with this link.

Thursday, June 04, 2015

How to generate wadl via maven plugin

So you've written your web service and would now want to create the wadl for it.

 Assuming you have your web project in eclipse with maven integrated this is what you have to do: 1.) Add the lines below to your pom, you may want to create it's own profile. For example api.
<plugin>
 <groupId>com.sun.jersey.contribs</groupId>
 <artifactId>maven-wadl-plugin</artifactId>
 <version>1.18.3</version>
 <executions>
  <execution>
   <id>generate</id>
   <goals>
    <goal>generate</goal>
   </goals>
   <phase>compile</phase>
  </execution>
 </executions>
 <configuration>
  <wadlFile>${project.build.directory}/docs/application.wadl</wadlFile>
  <formatWadlFile>true</formatWadlFile>
  <baseUri>http://czetsuya-tech.blogspot.com/api/rest</baseUri>
  <packagesResourceConfig>
   <param>com.broodcamp.api.rest</param>
  </packagesResourceConfig>
  <wadlGenerators>
   <wadlGeneratorDescription>
    <className>com.sun.jersey.server.wadl.generators.WadlGeneratorApplicationDoc
    </className>
    <properties>
     <property>
      <name>applicationDocsFile</name>
      <value>${project.basedir}/src/main/resources/application-wadl-doc.xml</value>
     </property>
    </properties>
   </wadlGeneratorDescription>
   <wadlGeneratorDescription>
    <className>com.sun.jersey.server.wadl.generators.WadlGeneratorGrammarsSupport
    </className>
    <properties>
     <property>
      <name>grammarsFile</name>
      <value>${basedir}/src/main/resources/application-wadl-grammar.xml</value>
     </property>
    </properties>
   </wadlGeneratorDescription>
  </wadlGenerators>
 </configuration>
</plugin>

2.) Looking at the plugin configuration above, we now have 2 define 2 files:
application-wadl-doc.xml
<?xml version="1.0" encoding="UTF-8"?>
<applicationDocs targetNamespace="http://wadl.dev.java.net/2009/02">
 <doc xml:lang="en" title="czetsuya-tech api">czetsuya-tech api</doc>
</applicationDocs>

application-wadl-grammar.xml
<?xml version="1.0" encoding="UTF-8" ?>
<grammars xmlns="http://wadl.dev.java.net/2009/02" />

3.) Now all you need to do is run the command below in command prompt:
>mvn -Papi clean compile com.sun.jersey.contribs:maven-wadl-plugin:generate
// note that we use api profile as defined above.

Thursday, May 28, 2015

How to return soapFault in a jax ws web service in JavaEE

The code below is an example of how you can throw a soapFault exception when an error is encountered in your web service  call.

There are basically 2 things 2 take note, see comments in code.

//#1 - inject WebServiceContext
@Resource
private WebServiceContext webServiceContext;

//#2 get the soapMessage, add a soapFault in body and throw the soapFault exception.
SOAPMessageContext jaxwsContext = (SOAPMessageContext) webServiceContext.getMessageContext();
SOAPMessage soapMsg = jaxwsContext.getMessage();
try {
 SOAPFault soapFault = soapMsg.getSOAPBody().addFault();
 soapFault.setFaultString("ERROR");
 Name qname = soapMsg.getSOAPPart().getEnvelope().createName("Client", null, SOAPConstants.URI_NS_SOAP_ENVELOPE);
 soapFault.setFaultCode(qname);
 throw new SOAPFaultException(soapFault);
} catch (SOAPException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
}

Friday, April 17, 2015

iOS Donut Progress Bar

The iOS Donut Progress Bar is an iOS library that you can integrate in your project to present data in a graphical way. Furthermore, it will allow you to get a live preview of the design right in the Interface Builder.

Inside the Interface Builder:


iOS Simulator:





Features

  • Customizable width and color for line and border of the outer/inner circle.
  • Customizable text label.
  • Customizable color, opacity, radius, and offset for shadow of the inner and outer circle
  • Supports the iOS 8 adaptive layout
  • You can change all of this in the interface builder or in runtime.

Example Usage In Runtime

circleView.outerRadius = 20
circleView.oColor = UIColor(red: 244/255, green: 156/255, blue: 45/255, alpha: 1)
circleView.percentage  = 75
circleView.fontSize = 25
circleView.noOfDecimals = 0
circleView.animateCircle(1.0)

To get the sample code, please visit this site.

Monday, March 23, 2015

What you should know before getting your own website

So you want to get your own website? Do you know what you should take into account before agreeing to have your website created by the experts? You will be tempted by the many offers that website developers have. It is all too easy to get overwhelmed by the stuff of things to do and to put into your website that you may forget to look at the prerequisites. So what should you look into before letting the website masters do their work? Here they are:

Fees

Fees. There is an expected amount of money that you will pay when you have your website created and designed. Usually, the package is meant for a year or so with specifications like web hosting and other services tied up with getting a domain name or website. However, there are also fees that you should know, like transfer fees. Transfer fees are fees that you pay when you opted to transfer your domain. Some website designers will charge you 2 to 3 percent more than your registration fees. So make sure that you ask about all the fees, including hidden ones. (Image at text: Fees)

Pay what you consume

Pay only for the year that you consume. When you are about to pay for registering your domain, make sure you check the expiration of the website or domain that you are buying. There are tools over the Internet that you can use to check it. You can readily Google the term “how to determine expiration of a domain or website” and you’ll get numerous helpful results. On the other hand, the webmaster should show what you paid for. If you paid for one year, then it should reflect that it is registered as such. If you paid 5 years, then it should show, too. (Image at text: Pay what you consume)


Keep record private and locked

Keep your records private. Be careful with your domain or website purchase. Make sure that you learn from the experts how to hide or modify your records so that database hackers do not get a hold of your personal data. If you don’t, soon you will receive a lot of spam emails. Make sure that when you do buy a domain, it is you who own the domain and not them representing you. (Image at text: Keep record private and locked)

Keep it locked. After purchasing your domain and have it designed accordingly by the web designers, make sure that you also have it locked. This ensures that your domain is not transferred and you don’t get any surprises of another person claiming your website.

Get your domain auth code

Get the domain or website authorization code. Some websites or domain requires an authorization code, especially when they get transferred. In essence, you should also have it so that you can readily transfer it, should you want to sell the website or domain in later years. (Image at text: Get your domain auth code)

One of the best ways to avoid any problems is to take time in reading the Terms and Conditions before you purchase a website. Ensure that you read everything, even the fine print so you won’t miss anything. Ask as many questions as you can. List down questions that you have and clarify it with the domain registrar before sealing the deal.

Friday, March 20, 2015

Setup wordpress in a sub-domain in Godaddy's windows hosting

This configuration is for windows only.

Configuration:
For example you have domain anime.com that is powered by wordpress, you set up permalinks to use postname so post will be accessible at http://anime.com/postname.

The problem is when you create a sub-domain, for example shounen.anime.com and set permalinks like that of the main domain so that you can do SEO. Obviously this will not work as the main domain permalinks will interfere, so you have to set a redirect rule.

Taken into account that it's a windows hosting, therefore we need to configure Web.config rather than .htaccess.
<?xml version="1.0" encoding="UTF-8"?>

<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="wordpress" stopProcessing="true">
          <match url=".*" />
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
          </conditions>
          <action type="Rewrite" url="index.php" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>