How to differentiate between 3.5 and 4 inch iPhone

Open Xcode and create a new Single View Application. For product name, use DifferentiateIphoneSize and then fill out the Organization Name and Company Identifier with your customary values. Select iPhone for Devices.



For demonstration purposes, add a label inside the view controller and change the text to "3.5-inch or 4-inch".

We will need to connect the label to the view controller. Select the assistant editor and open the ViewController.m file. Ctrl and drag from the label to the class section and create the following outlet.



Inside the viewDidLoad, add the following lines of code:
 
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
if ([[UIScreen mainScreen] scale] == 2.0) {
if([UIScreen mainScreen].bounds.size.height == 568){
// iPhone retina-4 inch
self.lbl_textOutput.text = @"iPhone retina-4 inch";
} else{
// iPhone retina-3.5 inch
self.lbl_textOutput.text = @"iPhone retina-3.5 inch";
}
}
else {
// not retina display
self.lbl_textOutput.text = @"iPhone that's not retina display";
}
}

Build and Run, a label can be seen with text "iPhone retina-4 inch" if the app is run in with 4-inch size, otherwise "iPhone retina-3.5 inch".


You can download the source code of the DifferentiateIphoneSize at my repository on bitbucket.

Display Time Picker On Textfield Click in Xcode

Open Xcode and create a new Single View Application. For product name, use TextFieldTimePicker and then fill out the Organization Name and Company Identifier with your customary values. Select iPhone for Devices.


For setting up the user interface, first, I embed the view controller inside a navigation controller. Go to Interface Builder, and then click the View Controller. Once the View Controller has been clicked, select the "Editor" -> "Embed in" -> "Navigation Controller".

Next, let's add a bar button item, a label, and a text field. I configured the bar button item to have a title of "Done". I also changed the label text to "00:00" and textfield's placeholder to "Input Time Here".

We will need to connect the user interface's to the view controller. Select the assistant editor and open the ViewController.m file. Ctrl and drag from the "Done" button to the class section and create the following action.


Repeat the same process for label and textfield, except that they should be an outlet and not an action.
 

Inside the ViewController.m, add the following lines of code to set-up the date picker and make it the input view of the text field:

-(void)setUpTextFieldDatePicker
{
UIDatePicker *datePicker = [[UIDatePicker alloc]init];
datePicker.datePickerMode = UIDatePickerModeTime;
[datePicker setDate:[NSDate date]];
[datePicker addTarget:self action:@selector(updateTextField:) forControlEvents:UIControlEventValueChanged];
[self.txtField_timeTextField setInputView:datePicker];
}

-(void)updateTextField:(id)sender
{
UIDatePicker *picker = (UIDatePicker*)self.self.txtField_timeTextField.inputView;
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setDateFormat:@"HH:mm"]; //24hr time format
NSString *dateString = [outputFormatter stringFromDate:picker.date];

self.self.txtField_timeTextField.text = [NSString stringWithFormat:@"%@",dateString];
}

Then, we'll have to set up the date picker once the view controller is loaded. Call the setUpTextFIeldDatPicker inside the viewDidLoad
[self setUpTextFieldDatePicker];

Inside the btn_showTime, add the following lines of code to update the label and hide the date picker once the button is cliced.
 
self.lbl_timeLabel.text = self.txtField_inputTextfield.text;
[self.txtField_inputTextfield resignFirstResponder];
Build and Run, a date picker should now appear when the text field is clicked.

You can download the source code of the TimeTextField at my repository on bitbucket.


How to detect first time app launch on iPhone in Xcode

Inside the "AppDelegate.m", change

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
return YES;
}

to

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
if ([[NSUserDefaults standardUserDefaults] boolForKey:@"HasLaunchedOnce"])
{
// app already launched
}
else
{
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"HasLaunchedOnce"];
[[NSUserDefaults standardUserDefaults] synchronize];
// This is the first launch ever
}
}

Debt: The First 5000 Years

Ah, the airport bookstore. As monetary theorist and history buff, I could not resist this tantalizing title: Debt: The First 5000 Years. The book is authored by anthropologist David Graeber, a leading figure in the Occupy Wall Street movement. But what grabbed me was the summary on the back cover, which states (among other things) that every economics textbook is wrong in the way it explains the emergence of money, which goes something like this: "Once upon a time, there was barter. It was difficult. So people invented money." [p28].

I think we (economists) have to score one for the anthropologists here. I remember being taught that story and it took me some time to figure out it was wrong. What makes barter difficult? We are taught that the difficulty stems from a "lack of coincidence of wants." Consider, for example, an island populated by three people, Adam, Betty and Charlie. Adam wants breakfast, Betty wants lunch, Charlie wants dinner. Adam can deliver dinner, Betty can deliver breakfast, and Charlie can deliver lunch. There are no bilateral gains to trade (no voluntary trade would occur between any arbitrary pairing of individuals). And yet, there are clearly multilateral gains to trade.


The solution, we are told, is to introduce a monetary object and endow it to Adam, who may then purchase his breakfast from Betty with cash. Betty then uses her money to buy lunch from Charlie. Charlie then uses his money to buy dinner from Adam, and so on.

As anthropologists have pointed out for a long time, there is really little evidence of trade taking this form in primitive communities (see: Famous Myths of Fiat Money, by Dror Goldberg). Instead, these societies operated as "gift giving" economies, or informal credit systems. The principle should be familiar to all of us: it is reflected in the way we trade favors with friends, family, and other members of social networks to which we belong.

What then, explains monetary exchange (really, the coexistence of money and credit)? According to Kiyotaki and Moore, Evil is the Root of All Money. "Evil" here is interpreted as the existence of untrustworthy (noncooperative) people. Untrustworthy individuals readily accept gifts from the community, but cannot be trusted to fulfill their implicit obligation to reciprocate in-kind when an opportunity to do so arises. However, we know from game theory that a system of "cooperative" exchange might still be sustained if untrustworthy people can be compelled to behave properly, say, by the threat of punishment for noncompliant behavior (e.g., ostracism from the community).

The punishment/reward system that implicitly exists in gift-giving societies requires (to the extent that some community members are untrustworthy) a communal monitoring of individual behavior. In small communities, "everybody knows everything about everyone" and so this is arguably why "communistic" societies can be sustained in small groups. It also suggests why the arrangement breaks down for larger groups. The virtual communal data bank -- a distributed network of computer brains -- is simply not capable of recording all the information necessary to support an informal credit system in a large population. In a large population, people can remain anonymous. We necessarily become strangers to most people. And its tough to trust a stranger (a person you are not likely ever to meet again).

Nevertheless, multilateral gains to trade may still exist even among strangers. And if credit is difficult, or impossible, then the solution is money (see: The Technological Role of Fiat Money, by Narayana Kocherlakota). According to this theory, money serves as a substitute for the missing communal memory. Contributions to society are now measured not by virtual credits in the collective mind of the community; instead, they are recorded by money balances (this assumes, of course, that money, like virtual credit, is difficult to counterfeit/steal).

So, in a nutshell, economic theory suggests that we use informal credit arrangements to govern exchange among people we know (family, friends, colleagues, etc.) and we use money to facilitate exchange with "strangers." The emergence of money then seems tied to the emergence of strangers. An obvious explanation for this is population growth (and the associated rise of large urban areas).

One thing I learned from Graeber is that the relative importance of money and credit seems to have waxed and waned over time. Money (in particular, coinage) emerged around 800BC and remained significant until about 600AD, an era associated with many great empires, and the associated need to pay transient professional armies. With the collapse of the great empires, new states emerged, increasingly under the regulation of religious authorities. Coinage declined in importance, with credit systems taking over (600AD-1450AD). This latter observation is consistent with the general decline of urban areas in western Europe, but Graeber points to many other factors as well. Monetary exchange waxes once again with the age of the "great capitalist empires" (1450-1971AD).

My comments above only scratch the surface of the book's much broader thesis concerning the moral nature of debt. The presentation is not as clean as it could be, the analysis is sloppy in several places, and the conclusion is rather weak but, heck, it's still a very interesting read. If nothing else, it encouraged me to interpret various aspects of history in ways that I am not accustomed to.

Alas, every gain comes at a price (beyond the $22 cash I paid for his book). His opening chapter, in particular, is so annoying that it almost led me to abort the enterprise. In the book, and in the many interviews he gives, he relays the following story (source):
And one of the things that really fascinated me was the moral power of the idea of debt. I would tell stories to people, very sympathetic people, liberal lawyers, well-meaning do-gooder types, and you’d tell these stories about horrible things. You know, in Madagascar, for example, the IMF came in with these policies, you have to cut the budgets because, god knows, we can’t reduce the interest payments you owe to Citibank, they owed all this money. And they had to do things like get rid of mosquito eradication programs, as a result that malaria returned to parts of the country where it had been wiped out for a hundred years and tens of thousands of people died and you had dead babies being buried and weeping mothers. I was there, I saw this sort of thing. You described this to people and the reaction would be, well, that’s terrible, but surely people have to pay their debts. You’re not suggesting they cancel it or default, that would be outrageous. And one of the things that really fascinated me was the moral power of the idea of debt.
I'm not completely sure, but if I was to relay this story to the average person I know, I would hardly expect them to say "well, that's terrible, but surely people have to pay their debts!" I'm pretty sure that most of the people I know would have replied "that's $^%& outrageous!" But then, maybe I don't know too many "sympathetic" people, liberal lawyers and well-meaning do-gooder types.

Moreover, I'm pretty sure that a significant majority of the people I know would have questioned the claim that the IMF kills African babies. After all, we are not speaking here of a paragon of good government.
Since Madagascar gained independence from France in 1960, the island's political transitions have been marked by numerous popular protests, several disputed elections, an impeachment, two military coups and one assassination. The island's recurrent political crises are often prolonged, with detrimental effects on the local economy, international relations and Malagasy living standards. (source)
Of course, malaria was for a long time a big problem on the African continent (see here) and elsewhere. But the disease was practically wiped out with the use of the pesticide DDT (see here). The use of DDT was then banned, owing to pressure from "well-meaning do-gooder" environmental groups. [Evidently, the ban was primarily for agricultural use, and only sometimes in vector control]. Now, according to this source:
In the 1980’s Madagascar stopped using DDT and immediately had an epidemic of malaria, resulting in the death of more than 100,000 people.
Hmm. And according to this source:
A strong malaria epidemic with a high mortality rate occurred on the Madagascar Highlands in 1986-88. Vector control and free access to antimalaria drugs controlled the disease.
This latter source also mentions the lack of immunity and a shortage of medicaments as factors contributing to the mortality rate. Is Graeber suggesting that the shortage of medicaments was the consequence of IMF imposed austerity measures on Madagascar's government and the desire to service Citibank debt? It seems an unlikely story (although, it's not easy to find details). According to this data from the World Malaria Report, almost all the resources for fighting malaria in Madagascar originates from international aid organizations, like USAID and The Global Fund. Did the IMF prevent these agencies from doing their good work?

Finally, let me point readers to Ken Rogoff's defense of IMF policies here. See also the article here, by Masood Ahmed.

Make no mistake, the malaria episode described by Graeber is a tragic story. People were dying and somewhere the resources existed that could have mitigated the losses (a continued program of DDT spraying would have prevented it altogether). Among other things, the government of Madagascar could have reallocated resources away from some expenditure (say, military, which is 1% of GDP according to CIA Factbook) toward medicaments. That it evidently chose not to is revealing. Does Graeber truly believe that a "debt jubilee" for governments of this nature would have prevented the episode in question? (Note: I am not against debt jubilees.)

Graeber has many useful and interesting things to say in his book. I personally find it annoying that a scholar and writer of such high caliber has to resort to stories like this to sell his ideas. But maybe that's just me. In any case, my recommendation is to read the book and filter out as much of the noise as you can. 

Samme avkastning for statlige selskaper og indeks

De statlig børsnoterte selskapene har verken vært spesielt lønnsomme eller ulønnsomme sammenlignet med andre selskaper notert på Oslo Børs.

I debatten om statlig nedsalg har det blant annet vært pekt på at de statseide selskapene er spesielt lønnsomme og at staten derfor ikke bør selge seg ned. Motstandere av nedsalg har gjerne vist til avkastning, uten å sammenligne med alternative investeringer. Den type overforenklet analyse gir ikke mening, noe enhver innføringsbok i finans vil forklare.

På den annen side, det ser ikke ut til at det finnes analyse på hvordan den statlige porteføljen presterer i forhold til børsen. I alle fall fant ikke jeg noen. Jeg har derfor gjort en slik prestasjonsanalyse, til glede for alle som deltar i debatten.

Analysen er gjort spesielt for denne kronikken. Med begrenset tid og ressurser har jeg gjort den forenklende antakelsen at andelene av hvert børsnoterte selskap i statens portefølje er konstant lik andelene i 2011.

Som vi ser av figuren er det svært liten forskjell mellom statens selskaper og børsindeksen (OSEBX). Dette er i og for seg ikke så overraskende, siden de statlige selskapenes markedsverdi utgjør nesten halvparten av børsen.

Dersom det var slik at de statlige selskapene var klart bedre eller dårligere drevet enn resten av børsen, burde imidlertid avkastningen være forskjellig fra de resterende 55 % av kapitalen. Selv om porteføljene til staten og børsen er ganske like, er de forskjellig nok til at det bør være mulig å avdekke større systematiske forskjeller.

Analysen viser altså at det er liten forskjell på statens selskaper og børsindeksen generelt. Det er derfor ikke dekning for verken å påstå at de statlige selskapene er spesielt godt eller dårlig drevet.

De statlige selskapene er litt mindre risikable enn børsindeksen generelt, med en “beta” på 0.68 (markedsindeksen har beta på 1
). Selv om gjennomsnittsavkastningen er litt lavere enn indeksen, gjør den lave risikoen at de statlige selskapene overpresterer litt mot indeksen. Forskjellen mellom indeksen og statens selskaper er imidlertid så liten at det like gjerne kan skyldes tilfeldigheter.

I mer autoritære stater er det ikke uvanlig at statlige selskaper er ineffektive, dårlig drevet og brukes gjerne som politiske verktøy for å tilfredsstille særinteresser. Figuren bekrefter at dette ikke er et stort problem i Norge. De statlige selskapene drives profesjonelt, og gir omtrent samme avkastning som andre selskaper.

Det har vært hevdet at staten kan tjene på egne selskaper ved å gi dem særfordeler. Både genuint god eierstyring og særbehandling burde gitt meravkastning, sammenlignet med andre selskaper. Vi kan ikke skille mellom disse årsakene her. Siden vi uansett ikke ser noe meravkastning av betydning, ser det imidlertid ikke ut til at statlige selskaper preges spesielt av verken unik eierstyring eller særbehandling. Sistnevnte skal vi kanskje være glade for.

Men når selskapene konkurrerer i helt ordinære markeder på kommersielle vilkår og leverer avkastning helt på linje med alle andre selskaper, hva er egentlig vitsen med eierskapet?

Risikomessig gir det lite mening for Den Norske Stat å eie direkte i det norske næringslivet. Den største inntektskilden til staten er skatter og avgifter. Når vi eventuelt får en nedtur i den norske økonomien, vil både skatter og utbytter fra statens selskaper svikte samtidig. Vi kan kostnadsfritt unngå dette problemet ved at kapitalen heller plasseres i oljefondet.


Statens børsnoterte selskaper er Cermaq DNB, Kongsberg Gruppen, Norsk Hydro, SAS, Statoil, Telenor og Yara. Kursene er utbyttejustert.

Fortsatt ikke tap ved statlig nedsalg

Rasmus Hansson fra Miljøpartiet de grønne mener at et selskap kan ha større verdi for staten fordi statlig eierskap reduserer politisk risiko, og nevner Gassled som eksempel.

Prisen på alt Gassled selger bestemmes av den norske regjeringen. Eksemplet er derfor i de fleste tilfeller ikke så veldig relevant.

Hansson har imidlertid et poeng. Det er ikke unaturlig at staten jobber for å beskytte egne interesser, for eksempel ved å skreddersy rammebetingelser til de virksomhetene som er så heldig å ha statlig eier. Men det er vel ikke noe godt argument for statlig eierskap at myndigheten skal ha anledning til å sy puter under armene på enkelte selskaper.

Internasjonalt er det sannsynligvis mer vanlig at statlige selskaper overstyres for å tilfredsstille snevre særinteresser. I så fall blir effekten nøyaktig den motsatte; aksjene har større verdi på privat hånd enn på statens.

I Norge er det imidlertid normalt lite politisk innblanding og risiko. Da blir det heller ikke noe nevneverdig tap ved salg av statlige virksomhet. Snarere vil risikospredningen medføre en gevinst.

Hansson mener også at statlig eierskap kan redusere problemet med skatteplanlegging, men det kan vel neppe fungere som en generell løsning. På meg virker det uhensiktsmessig dersom staten skulle gå inn som dominerende eier i alle selskaper i Norge som kan tenkes å drive med skatteplanlegging. Det er sannsynligvis mer effektivt å fortsette og jobbe med bedre regelverk og internasjonalt samarbeid for å løse problemet.

How to restore an oracle dump using imp command

The following steps will guide us in the restoration of an oracle dump file.
  1. connect as system and enter your password
  2. sqplus system@xe
  3. create user
  4. create user TEST_USER identified by password;
  5. grant roles
  6. grant CREATE SESSION, ALTER SESSION, CREATE DATABASE LINK, -
    CREATE MATERIALIZED VIEW, CREATE PROCEDURE, CREATE PUBLIC SYNONYM, -
    CREATE ROLE, CREATE SEQUENCE, CREATE SYNONYM, CREATE TABLE, -
    CREATE TRIGGER, CREATE TYPE, CREATE VIEW, UNLIMITED TABLESPACE -
    to TEST_USER;
  7. create permanent table space
  8. CREATE TABLESPACE testuser DATAFILE 'testuser.dat' SIZE 20M AUTOEXTEND ON;
  9. import the dump file
  10. imp system/password@xe file=d:\testuser.dmp fromuser=TEST_USER touser=TEST_USER log=d:\test_user_import.log
The above steps is with the assumption that we've created an oracle database backup using exp tool.

How to initialize a git repository and linked it to a remote repository provider

For example we've just created a new project and want to push it to a remote repository. Here's what we need to do.

  1. Find out what is the repository url, you can see it at github. For example: https://github.com/czetsuya/JAX-RS-REST-Security.git
  2. Open command prompt
  3. Change directory to where your project is.
  4. In the command promp execute:
    1. >git init
    2. >git add .
    3. >git commit -m "Initial commit"
    4. >git remote add origin https://github.com/czetsuya/JAX-RS-REST-Security.git
    5. >git push -u origin master
What if we already initialized our repository? Then we can already skip steps 4.1-4.3 and just execute:
  1. >git remote add origin https://github.com/czetsuya/JAX-RS-REST-Security.git
  2. >git push -u origin master

JAX-RS 2.0 Security Tutorial in JavaEE and JBoss

This tutorial will summarize how the author was able to call a secured rest webservice using resteasy. We will not go into detail on how we build the entire project since the code is already pushed at github. Basically we will just note down the most important part of the process:

Note that our project was based on the linked in the reference below, we just made some modifications so that it will work on a newer version of jboss.

Tech Stack

  1. JavaEE6 / 7
  2. JBoss EAP 6.2

Things to remember

  1. Download resteasy-jaxrs-3.0.6.Final-all.zip
    1. Extract the zipped file and inside it find the folder: resteasy-jboss-modules-3.0.6.Final
    2. Copy all the folders inside it and paste into JBOSS_HOME/modules.
  2. In web.xml, we don't add any resteasy related parameters, instead it should look like this.
  3. <?xml version="1.0" encoding="UTF-8"?>

    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">

    <display-name>JAX-RS 2.0 Security Demo</display-name>

    </web-app>
  4. Create a web service activator.
  5. package com.kalidadbiz;

    import javax.ws.rs.ApplicationPath;
    import javax.ws.rs.core.Application;

    /**
    * @author Edward P. Legaspi
    **/
    @ApplicationPath("/api/rest")
    public class JaxRsActivator extends Application {

    }
  6. And finally the rest request interceptor:
  7. package com.kalidadbiz;

    import java.io.IOException;
    import java.lang.reflect.Method;
    import java.util.Arrays;
    import java.util.HashSet;
    import java.util.List;
    import java.util.Set;
    import java.util.StringTokenizer;

    import javax.annotation.security.DenyAll;
    import javax.annotation.security.PermitAll;
    import javax.annotation.security.RolesAllowed;
    import javax.ws.rs.container.ContainerRequestContext;
    import javax.ws.rs.core.MultivaluedMap;
    import javax.ws.rs.core.Response;
    import javax.ws.rs.ext.ExceptionMapper;
    import javax.ws.rs.ext.Provider;

    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.jboss.resteasy.core.Headers;
    import org.jboss.resteasy.core.ResourceMethodInvoker;
    import org.jboss.resteasy.core.ServerResponse;
    import org.jboss.resteasy.util.Base64;

    /**
    * @author Edward P. Legaspi
    *
    * http://java.dzone.com/articles/java-ee-7-and-jax-rs-20
    **/
    @Provider
    public class RESTSecurityInterceptor implements
    javax.ws.rs.container.ContainerRequestFilter,
    ExceptionMapper<Exception> {

    private Log log = LogFactory.getLog(RESTSecurityInterceptor.class);

    private static final String AUTHORIZATION_PROPERTY = "Authorization";
    private static final String AUTHENTICATION_SCHEME = "Basic";
    private static final ServerResponse ACCESS_DENIED = new ServerResponse(
    "Access denied for this resource", 401, new Headers<Object>());;
    private static final ServerResponse ACCESS_FORBIDDEN = new ServerResponse(
    "Nobody can access this resource", 403, new Headers<Object>());;
    private static final ServerResponse SERVER_ERROR = new ServerResponse(
    "INTERNAL SERVER ERROR", 500, new Headers<Object>());

    @Override
    public void filter(ContainerRequestContext requestContext) {
    log.info("filter");

    ResourceMethodInvoker methodInvoker = (ResourceMethodInvoker) requestContext
    .getProperty("org.jboss.resteasy.core.ResourceMethodInvoker");
    Method method = methodInvoker.getMethod();
    // Access allowed for all
    if (!method.isAnnotationPresent(PermitAll.class)) {
    // Access denied for all
    if (method.isAnnotationPresent(DenyAll.class)) {
    requestContext.abortWith(ACCESS_FORBIDDEN);
    return;
    }

    // Get request headers
    final MultivaluedMap<String, String> headers = requestContext
    .getHeaders();

    // Fetch authorization header
    final List<String> authorization = headers
    .get(AUTHORIZATION_PROPERTY);

    // If no authorization information present; block access
    if (authorization == null || authorization.isEmpty()) {
    requestContext.abortWith(ACCESS_DENIED);
    return;
    }

    // Get encoded username and password
    final String encodedUserPassword = authorization.get(0)
    .replaceFirst(AUTHENTICATION_SCHEME + " ", "");

    // Decode username and password
    String usernameAndPassword = null;
    try {
    usernameAndPassword = new String(
    Base64.decode(encodedUserPassword));
    } catch (IOException e) {
    requestContext.abortWith(SERVER_ERROR);
    return;
    }

    // Split username and password tokens
    final StringTokenizer tokenizer = new StringTokenizer(
    usernameAndPassword, ":");
    final String username = tokenizer.nextToken();
    final String password = tokenizer.nextToken();

    // Verifying Username and password
    log.info(username);
    log.info(password);

    // Verify user access
    if (method.isAnnotationPresent(RolesAllowed.class)) {
    RolesAllowed rolesAnnotation = method
    .getAnnotation(RolesAllowed.class);
    Set<String> rolesSet = new HashSet<String>(
    Arrays.asList(rolesAnnotation.value()));

    // Is user valid?
    if (!isUserAllowed(username, password, rolesSet)) {
    requestContext.abortWith(ACCESS_DENIED);
    return;
    }
    }
    }
    }

    private boolean isUserAllowed(final String username, final String password,
    final Set<String> rolesSet) {
    boolean isAllowed = false;

    // Step 1. Fetch password from database and match with password in
    // argument
    // If both match then get the defined role for user from database and
    // continue; else return isAllowed [false]
    // Access the database and do this part yourself
    // String userRole = userMgr.getUserRole(username);
    String userRole = "ADMIN";

    // Step 2. Verify user role
    if (rolesSet.contains(userRole)) {
    isAllowed = true;
    }
    return isAllowed;
    }

    @Override
    public Response toResponse(Exception exception) {
    // TODO Auto-generated method stub
    return null;
    }

    }
  8. To test if the filter will really be triggered when there is a rest web service request, I've provided an action bean and a jersey client that sends a request with username and password
package com.kalidadbiz;

import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;

/**
* @author Edward P. Legaspi
**/
public class RestClient {
private Log log = LogFactory.getLog(RestClient.class);

private String host;
private String api;
private Properties properties = new Properties();

public RestClient() {

}

public RestClient(String host, String api) {
this.host = host;
this.api = api;
}

public void addParam(String key, String value) {
properties.put(key, value);
}

public String execute() {
try {
Client client = Client.create();
client.addFilter(new HTTPBasicAuthFilter("edward", "edward"));

String params = "";
if (properties != null) {
for (String key : properties.stringPropertyNames()) {
String value = properties.getProperty(key);
if (params != null) {
params += "&";
}
params += key + "=" + value;
}
}

String apiUrl = host + "/" + api;
if (params != null && params.length() > 0) {
apiUrl = apiUrl + "?" + params;
}
WebResource webResource = client.resource(apiUrl);

ClientResponse response = webResource.accept("application/json")
.get(ClientResponse.class);

if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}

return response.getEntity(String.class);
} catch (Exception e) {
log.error(e.getMessage());
return "";
}
}

public String getHost() {
return host;
}

public void setHost(String host) {
this.host = host;
}

public String getApi() {
return api;
}

public void setApi(String api) {
this.api = api;
}
}

And lastly, don't forget to encrypt your password :-).

Github Repository

References:

http://howtodoinjava.com/2013/07/25/jax-rs-2-0-resteasy-3-0-2-final-security-tutorial/

How to import and export a database dump in oracle


The following instruction will help us in importing and exporting our oracle database.

  1. Create and restore dump file (http://www.database.fi/2011/05/using-expdp-and-impdp-export-and-import-in-10g-11g/)
    1. Create dump file
      1. sqlplus system/oracle
      2. SQL> create directory dmpdir AS 'c:\temp';
      3. select directory_name, directory_path from dba_directories;
      4. expdp system/password version=’10.2.0.1’ dumpfile=czetsuya.dmp directory=dmpdir schemas=czetsuya
    2. Restore a dump file
      1. For import we can use the DATA_PUMP_DIR setting:
        1. ORACLE_XE\app\oracle\admin\XE\dpdump
      2. Copy dump file to folder above
      3. impdp system/password dumpfile=czetsuya.dmp directory=DATA_PUMP_DIR full=y logfile=czetsuya.log

WebView Tutorial in iOS 8 With Swift

The UIWebView class is use to embed web content in an application. It can be done by simply creating a UIWebView object and attaching it to a window and then sending it a request to load web content.

Open Xcode and create a new Single View Application. Fill out the Product Name, Organization Name and Organization Identifier with your customary values. Enter Swift as Language and make sure only iPhone is selected in Devices.




Go to the Storyboard and On the bottom of the Interface Builder you’ll see something that says “w Any”, “h Any”.  Change the width to compact and height to regular to change the view to an iPhone in portrait mode.



 Add a Web View to the main view. The ViewController should look like this.


 Select the assistant editor and open the ViewController.swift file. Ctrl and drag from the button to the class section and create the following outlet.



We will be needing a property to hold the url of the web view we want to show, so add a constant property. 

let url = "https://developer.apple.com/swift/"


Next, change the viewDidLoad to


    override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

let requestURL = NSURL(string:url)
let request = NSURLRequest(URL: requestURL)
webView.loadRequest(request)
}


And that's it. Build and Run the project and wait for a couples of second and you should be able to view the website displayed into the web view.

Using Background Image in Navigation Bar in ios in XCode

You can still use the setBackgroundImage: method to assign a custom image for the navigation bar. Here is the line of code for setting the background image. Insert it inside AppDelegate didFinishLaunchingWithoptions... method: 

UINavigationBar.appearance().setBackgroundImage(UIImage(named: "nav_bg.png"), forBarMetrics: UIBarMetrics.Default)

Feil om avkastning

Arbeiderpartiets Marianne Martinsen tar feil om statlig nedsalg når hun i DN 27. juni hevder at “Det er heller ikke irrelevant å sette spørsmålstegn ved om det er klokt å selge seg ned i veldrevne norske selskaper som gir gode løpende inntekter, for å frigjøre noen titall milliarder som kan investeres i aksjeposter i utlandet.”

Poenget kan best illustreres ved å anvende utsagnet på noe som er enklere å sjekke empirisk: “Det er heller ikke irrelevant å sette spørsmålstegn ved om Slottet er gult”. Det er selvsagt en ørliten mulighet for at Slottet har blitt malt i ny farge, men det er i utgangspunktet liten grunn til å tro at det har skjedd.

Aksjene som Staten selger vil ha akkurat samme forventede avkastning som Oljefondet. Markedet vil prise aksjene likt enten de kjøpes av Oljefondet eller selges av Staten. Og tro det eller ei, Oljefondets selskaper deler også ut utbytte.

Avkastningsmessig er det altså ikke uklokt å selge statlige selskaper. Risikoen blir tvert i mot mindre når investeringene spres.

I DN. 21. juni uttaler Martinsen også at “Jeg vil bli overrasket om avkastningen [til Oljefondet] blir større enn i Telenor og Kongsberggruppen”. Med salgspris lik markedets forventning blir sjansen for tap/gevinst 50/50. Er det slik at Marthinsen blir overrasket om en mynt lander med kronesiden opp?

Det går utover troverdigheten til avsenderen når argumenter tas ut av løse lufta. Arbeiderpartiet bør satse på argumenter de vet er korrekte.

Application's First Launch XCode

Open AppDelegate.swift and modify this line:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
return true
}
to
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {

if (NSUserDefaults.standardUserDefaults().boolForKey("HasLaunchedOnce")){
//app already launched
println("app already launched")
}else{
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "HasLaunchedOnce")
NSUserDefaults.standardUserDefaults().synchronize()
//This is the first launch ever

println("this is the first launch ever")
}

return true
}

CSharp Development

Operating Systems

Database

Web Development

JavaEE Development

JavaEE6

JAX RS

JSF

Primefaces

Hibernate

Messaging / Stomp / JMS

Application Servers

Wildfly / Jboss

Java Code / Coding / Debugging

Common Problems

Mobile Development


iPhone / XCode Development

  • How Tos
  • Stanford Exercises

Swift

Android