Generate client side code using Swagger Codegen

Overview

  • Swagger provides a simple, powerful representation for you APIs.
  • After creating an API what you need is a client side code to access the API.
  • Swagger provides an open source product to do that.

Swagger Codegen

  • Swagger codegen is the tool that we are going to use for generating client side code.
  • You can simple download swagger codegen from here.

Building Swagger Codegen

  • After downloading the source code from github, you need to build the product.
  • Since it’s maven project what you need to open the terminal there and build the product using the following command.
                     mvn package

Generating client side code

  • There are plenty of supported languages for swagger and i’ll go with JAVA.
  • Swagger needs YAML or JSON swagger file as the input.( The file that is used to represent the API using swagger.)
  • You can find a lot of sample json files from swagger and I’ll go with petstoreexample.
  • Writing JSON or YAML for swagger is tricky. You need to have clear idea about that. So please refer swagger  specification to get an idea.
  • You can use swagger editor to write your own swagger files using YAML or json.
  • Use the bellow command to generate the java client side code.
java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate 
  -i http://petstore.swagger.io/v2/swagger.json 
  -l java 
  -o samples/client/petstore/java

How to use the generated client side code

  • Now all the hard part is done. Simply import the generated client side code into your preferred IDE.
  • You can find a package called io.swagger.client.api and there should be three classes.
  • Using these three classes you can do anything you want.
  • For and example let’s say that you need to update a pet and display his name. You can don that using the following lines.
package io.swagger.test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.w3c.dom.ls.LSException;

import io.swagger.client.ApiException;
import io.swagger.client.api.*;

public class test {

	public static void main(String[] args) throws IOException {
		List status = new ArrayList();
		status.add("sold");
		PetApi pet = new PetApi();

		try {
			pet.updatePetWithForm("1", "nicky", "available");
			System.out.println(pet.getPetById((long) 1).getName());
		} catch (ApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}

Important

  • If your preferred language is not in the list you can simply create a new module by using the bellow command.

java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar meta -o output/myLibrary -n myClientCodegen -p com.my.company.codegen

  • Read this to get a more clear idea on swagger codegen.

Using Data Annotations to validate models

You can validate action results too and MVC methods by passing in the model which has the data annotations as part of the parameter list

Coding Wise

The .NET Framework provides us a set of attributes that we can use to validate objects. By using the namespace System.ComponentModel.DataAnnotations we can annotate our model’s properties with validation attributes.

View original post 181 more words

OWIN Classes with Access-Control-Allow-Origin Header: *

XMLHttpRequest cannot load http://localhost:7802/token. No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
Origin ‘http://localhost:7812’ is therefore not allowed access

This error means that there is an attempt to access a resource from a different domain by a web app, and the requested resource does not have any policies that would allow the apps from the origin domain to consume it. This error can be reproduced by loading a web app on a different domain (or port) and making an AJAX call to an API. The code would be
something similar to the following:
Client App
API App
$.ajax({
type: “POST”,
7/api/contact”,
contentType: ‘application/json’,
data: JSON.stringify(contact),
headers: {
‘Authorization’: ‘Bearer ‘ + tokenProvider.token,
},
success: function (res) {

callback();
},
error: function (req, status, error) {

callbackError();
}
});
[HttpPost]
[ResponseType(typeof(Contact))]
[Route(“~/api/contact”)]
public IHttpActionResult PostContact
        ([FromBody]Contact contact)
{
    IHttpActionResult result = null;
    if (!ModelState.IsValid)
    {
          result=BadRequest(ModelState);
    }
    else
     {
          //handle request
     }
     return result;
}

When making a CORS request, we need to understand that for every request that we send to a different domain, there may be two requests made to the server, preflight and actual requests. For each of these requests, the server must respond with the Access-Control-Allow-Origin header set with the name of the origin domain.

Preflight Request
 
A preflight or OPTIONS (HTTP verb) request is created by the
browser before the actual request (PUT,POST) is sent for a resource in
another domain. The goal is to have the browser and server validate that the other
domain has access to that particular resource. This is done by setting the Access-Control-Allow-Origin
header with the host or origin domain.
Actual Request
 
Once the preflight request has a response with the
corresponding headers, the browser sends the actual request. For this request,
the server also checks the CORS policies and adds the Access-Control-Allow-Origin
header with the host domain.
OWINS CORS
 
The way to implement CORS using OWIN and MVC Web API is by first configuring the oAuth server options with an implementation of OAuthAtuhorizationServerProvider on the Startup class.
[assembly: OwinStartup(typeof(ozkary.Startup))]
namespace ozkary
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {

ConfigureAuth(app);
        }
        private void ConfigureAuth(IAppBuilder app)
        {
            // Configure the application for OAuth based flow
            var oAuthOptions = new OAuthAuthorizationServerOptions
            {
                Provider =
new AuthorizationServerProvider(),
                                
            };
            // Enable the application to use bearer tokens to authenticate
users

app.UseOAuthAuthorizationServer(oAuthOptions);
           
        }  
    }
}
The OwinStartup directive allows OWIN to run the StartUp class and inject the AppBuilder instance in the Configuration method. This is what we need in order to configure the custom provider that can handle our token management, user validation and CORS headers. (token and user validation is not in the scope of this article). The implementation of
AuthorizationServerProvider is listed below: (listing only the areas that are relevant to support CORS)
public class AuthorizationServerProvider : OAuthAuthorizationServerProvider
    {                      
        /// <summary>
        /// match endpoint is called before Validate
Client Authentication. we need
        /// to allow the clients based on
domain to enable requests
        /// the header
        /// </summary>
        /// <param
name=”context”></param>
        /// <returns></returns>
        public override Task MatchEndpoint(OAuthMatchEndpointContext context)
        {

SetCORSPolicy(context.OwinContext);
            if (context.Request.Method == “OPTIONS”)   
            {               

context.RequestCompleted();
                return Task.FromResult(0);
            }
            return base.MatchEndpoint(context);
        }
       
      
        /// <summary>
        /// add the allow-origin header only
if the origin domain is found on the     
        /// allowedOrigin
list
        /// </summary>
        /// <param
name=”context”></param>
        private void SetCORSPolicy(IOwinContext context)
        {
            string allowedUrls = ConfigurationManager.AppSettings[“allowedOrigins”];
            if (!String.IsNullOrWhiteSpace(allowedUrls))
            {
                var list = allowedUrls.Split(‘,’);
                if (list.Length > 0)
                {
                    string origin =
context.Request.Headers.Get(
“Origin”);
                    var found = list.Where(item =>
item == origin).Any();
                    if (found){

context.Response.Headers.Add(
“Access-Control-Allow-Origin”,

new string[] { origin });
                    }                   
                }
                
            }

context.Response.Headers.Add(
“Access-Control-Allow-Headers”
                                   new string[] {“Authorization”, “Content-Type” });

context.Response.Headers.Add(
“Access-Control-Allow-Methods”
                                   new string[] {“OPTIONS”, “POST” });
        }                
    }
The code above overrides the MatchEndpoint handler. This area of the code is called for every request including the preflight request (OPTIONS). Note that this handler is called before a call is made to Validate Client Authentication. This is where we need to manage the logic of adding the headers using OWIN.  We do this by calling
the SetCORSPolicy method.
The SetCORSPolicy method looks for a configuration setting (allowedOrigins) that contains the whitelist of domains that can consume the resources from our API. It then reads the Origin header to get the domain name (including scheme and port i.e. http://mydomain.com:80). If the origin domain is found in the configuration, the Access-Control-Allow-Origin response header is set to the origin domain value.
This is what helps us resolve the “No ‘Access-Control-Allow-Origin’ header is present on the requested resource”.
The SetCORSPolicy method is also a good place to add other response headers that may be required for accessing our API. For example, we may need to add the Access-Control-Allow-(Header and Methods) for additional access. (Not CORS related)
We can use the browser developer tools to take a look at the network request and response headers. When CORS is configured properly, the response headers should look similar to this:
What to Avoid
 
When using the OWIN middleware to handle our CORS calls, we want to stay away from adding these headers in other areas of the application as this causes a duplicate header exception. Some of the things to avoid include:
  • Do not add these headers on the web.config file
  • Do not use app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll) as this allows all origin domains to have access. We could use this option for public APIs with no restrictions.
  • Do not use the config.EnableCors from WebApiConfig (HttpConfiguration) as we are already using a middleware to handle this concern. This option can be used when OWIN is not being used and we need to allow CORS
  • When configuring the whitelist for CORS, we need to make sure to include the scheme, domain and port number  (especially when testing with Visual Studio).   http://localhost is not the same as http://localhost:5733 and  http://www.ozkary .com is not the same as http://ozkary.com. We need to match the Origin header value

 

Conclusion

 

We need to keep in mind that once we start using OWIN, we are essentially passing the CORS concern to the middleware. We do not want to start making changes in different areas of the application as that just makes thing confusing. We just need to focus on the AuthorizationServerProvider and add the necessary implementation to enable CORS in our apps.

A lottery industry insider installs undetectable software giving him advance knowledge of winning numbers, then enlists accomplices to play those numbers and collect the jackpots.

Eddie Tipton, the former security director of the Multi-State Lottery Association, reportedly installed software code to be able to know winning numbers.

playhugelottos.com 390-lottery-0415Eddie was convicted of rigging the $16.5m jackpot in Iowa in 2015. At the moment, he is awaiting trial in four other states. The lottery security director was charged after being identified on the surveillance footage of a person buying the winning ticket for a $16.5m jackpot in 2010. Tipton, who had unparalleled access to lottery software, was identified on the footage by his colleagues.

Prosecutors say Tipton installed software known as a root kit that enabled him to manipulate numbers without a trace. What tripped him up, investigators say, was his decision to buy the winning ticket himself at a service station near the headquarters of the association, whose workers are prohibited from trying their luck.

Continue reading “A lottery industry insider installs undetectable software giving him advance knowledge of winning numbers, then enlists accomplices to play those numbers and collect the jackpots.”

Technology Bites Man Again

 

If entrepreneurs didn’t know by now that Technology was taking over the business world, now it’s encroaching on the gambling casinos.  We can’t even escape it on our trips to Las Vegas.

RADIO-FREQUENCY IDENTIFICATION is headed for Vegas.  Casino chips  embedded with RFID tags and are being tested at the Hard Rock Hotel & Casino and will be displayed this month at the new $2.7 billion Wynn Las Vegas hotel and casino.

The chips will each be given a unique player code to track behavior and possibly get more revenue out of high rollers.  It’s estimated that this could be a $100 million business by the year 2010.

There are two Vegas based companies that own the casino-RFID game: Progressive Gaming International and Shuffle Master.

Progressive’s TableLink, which reads RFID chips using table-embedded antennas and records the wagers on a dealer’s PC, is the system of choice at the two casinos.  Progressive and Shuffle Master have also developed optical card shoes, which holds decks and scan cards as they’re dealt.  Shuffle Master’s Intelligent Shoe is already getting rave reviews in Australia and Asia.

The cost of outfitting a table with the chips and antennas costs a casino about $8,000, but analysts predict that Progressive will score bigger bucks from the $6 per day per table it charges for its system.

One RFID chip costs a casino 40 cents more than a standard chip, but that margin will drop to about 10 cents in the coming months. This is certainly a “technology leap” from the “eye in the sky” that we all knew about in the casinos, but I don’t think that even George Orwell would have thought of these chips.

Those of us who used the games in Vegas casinos to escape our computers and software programs, seem destined to be followed by technology no matter where we go. Somehow Radio-Frequency Identification in poker/gaming chips just doesn’t seem to be what a good poker player expects.  Oh well, technology marches on…and on….and on.

You’re really getting tired of the 9 to 5 “rat race” and are thinking about chucking it for your own business.   All your friends keep telling you that you could do for yourself just what you’re doing now for your boss. Why shouldn’t you profit from your ideas instead of him?

You keep thinking about it because you know that you’ll never be financially where you want to be with a weekly paycheck, but what business would you start?

Before you pack in that weekly paycheck, this is the time to evaluate yourself and your future and it takes some real, down to heart honesty.  You want to change your life for the better, so let’s start. Did you know that you have the potential to do and be anything you want?  People have different perceptions of the ideal life, and it ranges from obtaining financial freedom to as simple as owning a new pair of sneakers. Unfortunately, many fail to reach their aspirations because they can’t get a solid, clear picture in their mind of what they want.

Take the next few days and embark on a fact-finding journey that will be a life-changing experience.  Get a pad and pencil and start with this first step:

STEP 1 – KNOW EXACTLY WHAT YOU WANT – Be specific in your passions, then focus all your efforts on that particular desire.

Those who always change their minds and those who give up easily when the going gets tough will never get anywhere.  If you’re a bit confused and aren’t sure what you really want in life answer these questions:

  1. What makes your heart beat with excitement?
  2. What makes you happy?
  3. What are you constantly thinking of day and night?
  4. What do you want to do with the rest of your life?
  5. What do you enjoy doing?
  6. What are your obsessions?
  7. What things make you jump for joy?

 

Write down all your possible answers to the above questions.  Write down everything, no matter how silly or unimportant it seems. Put all your desires on paper that answers any of the above questions.

When that’s done, go back and circle five to seven items that interest you the most.  Then evaluate and choose with your heart, not your mind, the one and only thing worthy to spend all your time and resources on and that brings out the best in you.

Now you may wind up with something like, “I want to play quarterback for the RAMS.”  If you’re over 20 I’d say that isn’t too viable a choice, but you could do something related to football or sports.  How about starting a sports publication?  Or perhaps a sporting goods retail business, sports memorabilia business, or even a gym could be the answer.  You can always read books and surf the net to help you in your search.

The most important thing to remember, no matter how “pie in the sky” it seems, is to USE YOUR HEART.  Others may disagree with you, but you should be firm with what you really want.  Others may offer comments or advice, but the final decision is always yours to make.  You should concentrate on what you want, not what others want.

Remember you only get one shot at living your life.   There are no replays and you don’t get to do it over.  You may not do it right, but at least you’re doing it.  Too many lives have been lived in quiet desperation waiting until – until they had saved a nest egg, until the children are out of school, until I retire, and they depart this life before “until” ever arrives.

Don’t go to sleep tonight without making a decision on WHAT YOU REALLY WANT IN LIFE MORE THAN ANYTHING ELSE.

Then spend a few days evaluating how to make it possible and make a living at it.  Begin living every day as if it were the last day you had – never leaving anything to be done next week, next month, or next year.  There will always be bills, things will always break down eventually and need replacing, there may be storms and earthquakes and repairs – but there will only be one life for you to live. It can’t be put on “hold”!

The final outcome of your efforts may be in the future, but you’re living each day by taking steps toward that outcome.

Safe Way to Start Your Own Business

Hopefully, you took my advice last week and you have a handy-dandy list now of what you want to do.  We know you want to start your own business; hopefully you now know what it will be.

Being used to a steady paycheck from a regular job, with a family or other financial obligations, makes stepping out of your comfort zone a little risky.  It doesn’t seem to matter how miserable you are in that job, the alternative scares the pants off many of us.  There is a safer way of jumping off that cliff and it entails your current boss.

Your employer could be your ticket to a successful freelance business, if his business doesn’t conflict with your dreams.  If you were thinking of starting a freelance copywriting business, you could negotiate a contract with your current employer for 50% of your time for the first year after you leave.  This would give you a springboard for finding other clients while still covering your monthly expenses.

You’re probably wondering about now, why your employer would agree to sign a contract for half of your time?  There are a number of reasons, and they can result in a “win-win” situation for both of you.

If you’re on good terms with your employer, chances are he doesn’t want to lose you.  It takes time to train someone to fill your job and train them to the company’s way of being productive.

Even if he decides to replace you, it can take months to gather resumes, interview candidates, and hire the right person.  During that time you can be performing job functions from your home office, perhaps even training your replacement and providing your boss with a smoother transition by minimizing the disruption to his business.

If you’re not on good terms with your boss and the company is downsizing, merging, or being bought out, you can help them avoid the unpleasantness and cost of firing you.  You are actually doing them a favor by restructuring this in the form of a contract for services that can be “stretched out” for a period of time if needed.

Frankly, if an employer has to choose between letting you go and paying severance and benefits versus signing a contract for a time period, which do you think they’d prefer?  Signing and getting tangible work and services in return without the costs associated with terminating you is a much better deal for him.  The contract may even be allocated from a different budget category, making it more affordable for the company.

There’s another reason your boss may opt for a contract, and that is your knowledge.  You are already familiar with the company, its clients and services.  You’re able to provide the services they need and you understand what has to be done. Many creative people have used this logic in approaching their bosses to negotiate their first contract and go out on their own.

If you’re interested in starting your own business your current job can provide the security you need in your first year.  What better way to get started on your dream?

Getting In On The Ground Floor

Tractors that steer themselves, property that knows it’s been stolen, airplanes that land without pilots – that sounds like science fiction.  It’s all a result of the global positioning system which is mind-boggling.   The industry is set to skyrocket and opportunities for the entrepreneur are there.

This spring the U.S. government will launch its first next generation GPS satellite to complement the 30 older models already in use.  The aim is to create stronger signals, increased bandwidth, and lots of potential for smart entrepreneurs.

Though startups are springing up all over the place, plenty of technologies remain untapped.  One of the untapped areas are automated navigation systems in family cars that keep drivers a safe distance from other vehicles.

Huge companies such as UPS plan to outfit 75,000 drivers with GPS-enabled handhelds this year to help them reach destinations more efficiently.  Some savvy entrepreneur who offered similar navigation and tracking services could also make out nicely.

There are companies that are using this technology to guide and navigate giant trucks around cliffs and mine shafts.  The maritime industry is predicted to invest hundreds of millions in coming years to outfit cargo containers and ships with GPS receivers.

Chipmakers already cashing in are charging about $13 per device to put GPS chipsets in phones, electronics, and car navigation systems.  And with a new federal regulation that is forcing wireless operators to include GPS in their phones and networking equipment, chip demand is sure to explode.

Remember the day when we said that expecting to buy drinking water in bottles was something the American consumer would never do.  Pay for water that comes out of the kitchen sink faucet?  How silly!  Look at the industry that’s grown up in that area!

Entrepreneurs – the GPS opportunity is out there, if only you know where to look.  Remember, you heard it here first!