Summary of Josh Long Youtube video about Security OAuth and other resources for OAuth in Spring

About the video in: https://www.youtube.com/watch?v=EoK5a99Bmjc&list=WL&index=12

After the description of the video I specify on how to use a separate Resource server that “authenticates” against the Authorization server, also specify about the token store usage and an Example on how to do a @Query using the Authenticated user has a filter.

First go to spring Initializr

In the dependencies you will place “Cloud OAuth2”, “Web”, “JPA”, “H2”, “Lombok”

Artifact has “auth-service”

Hit(click) Generate

Download and Extract the file into a directory.

Open your editor (idea will point to pom.xml )

In file resources/application.properties he setup the service name

spring.application.name=auth-service

# Ideally you use a config server in a micro service architecture

# Set the server port to 9191

server.port=9091

# Set the contextPath from where all the oauth requests will be served

server.contextPath=/waa

# No explanation for the bellow see the following Url http://www.baeldung.com/spring-security-session

security.sessions=if-required

Will now create on the AuthServiceApplication a Entity Account

@Data
@Entity
@NoArgsConstructor
@AllArgsConstructor
class Account {
   @Id @GeneratedValue
   private Long id;

   private String username;

   private String password;

   private boolean active;
public Account(String username, String password, boolean active) {
   this.username = username;
   this.password = password;
   this.active = active;
}
}

Now he creates a Interface to Manage the Repository interface AccountRepository extends JpaRepository<Account, Long>

interface AccountRepository extends JpaRepository<Account, Long> {
   
}

Now he will persist some usernames to the database so he will create a CommandLineRunner

@SpringBootApplication
public class AuthServiceApplication {
   @Bean
   CommandLineRunner demo (AccountRepository accountRepository){
      return args-> Stream.of("jlong,spring", "dsier,cloud").map(tpl -> tpl.split(","))
            .forEach(tpl -> accountRepository.save(new Account(tpl[0], tpl[1], true)));
   }

   public static void main(String[] args) {
      SpringApplication.run(AuthServiceApplication.class, args);
   }
}

He also added a constructor to the Account Entity I placed it above in the Entity

Now he teaches Spring Security about our database, with an implementation of UserDetailsService, this Interface is a method of how Spring Security will “transform” our internal Account into a User understandable Username Password and all other details related to Spring Security.

loadByUsername also expects a Exception of type UsernameNotFoundException to be thrown in case the username is not found.

@Service
class AccountUserDetailService implements UserDetailsService {


   private final AccountRepository accountRepository;

   public AccountUserDetailService(AccountRepository accountRepository) {
      this.accountRepository = accountRepository;
   }

   @Override
   public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
      return accountRepository.findByUsername(username).map(account -> new User(account.getUsername(), account.getPassword(),
            account.isActive(), account.isActive(), account.isActive(), account.isActive(),
            AuthorityUtils.createAuthorityList("ROLE_USER", "ROLE_ADMIN")))
            .orElseThrow( () -> new UsernameNotFoundException("Could not find the username "+ username +" ."));
   }
}

In the next step he informs OAuth service how he will delegate the authorization step into the Spring Security using AuthServiceConfiguration

@Configuration
@EnableAuthorizationServer
class AuthServiceConfiguration extends AuthorizationServerConfigurerAdapter {

   private final AuthenticationManager authenticationManager;

   AuthServiceConfiguration(AuthenticationManager authenticationManager) {
      this.authenticationManager = authenticationManager;
   }

   /**
    * Specify what clients we want to authorize
    *
    * @param clients
    * @throws Exception
    */
   @Override
   public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
      clients.inMemory()
            .withClient("html5")
            .secret("password")
            .authorizedGrantTypes("password")
            .scopes("openId");
   }

   /**
    * indicate what authentication manager we want to use
    *
    * @param endpoints
    * @throws Exception
    */
   @Override
   public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
      endpoints.authenticationManager(authenticationManager);
   }
}

 

And now he runs the application.

Also https://gigsterous.github.io/engineering/2017/03/01/spring-boot-4.html has some aditional explanation.

Even more  https://spring.io/guides/tutorials/spring-boot-oauth2/

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-security.html

Setup a Resource Server separate from the Authorization Server

I’ve managed to setup a Resource Server separated from the Authorization server it’s very easy, just placing the annotation in the main class @EnableResourceServer and in application.properties specify the URI of the user information in the remote Authorization Server.

security.oauth2.resource.userInfoUri=http://localhost:9191/uaa/user

This /user address has to be setup in the Authorization Server of Long example like so:

@RequestMapping("/user")
public Principal user(Principal user) {
   return user;
}

This is placed inside the AuthServiceApplication class. And have to place the class AuthServiceApplication has a @RestController

New code will look like this:

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import java.security.Principal;
import java.util.stream.Stream;

import far.botshop.security.backend.authservice.entity.*;
import far.botshop.security.backend.authservice.repository.*;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@EnableResourceServer
@RestController
public class AuthServiceApplication {

   @Bean
   CommandLineRunner demo (AccountRepository accountRepository){
      return args-> Stream.of("jlong,spring", "dsier,cloud").map(tpl -> tpl.split(","))
            .forEach(tpl -> {
               accountRepository.save(new Account(tpl[0], tpl[1], true));
            });
   }

   public static void main(String[] args) {
      SpringApplication.run(AuthServiceApplication.class, args);
   }

   @RequestMapping("/user")
   public Principal user(Principal user) {
      return user;
   }
}

 

The authentication against the Resource Server is made using the token obtained from the Authorization server has previous examples from Long.

curl -X GET "http://localhost:8080/products" -H "Authorization: Bearer 22e70fcf-eb60-483c-9105-xxxx"

That’s it. Now for a JdbcTokenStore so the tokens can be reused…

First in the auth-service we create the dataSource and storeToken

@Autowired
private DataSource dataSource;
@Bean
public TokenStore tokenStore() {
 DataSource tokenDataSource = DataSourceBuilder.create()
 /*
 .driverClassName(oauthClass)
 .username("root")
 .password("")
I used a JDBC URL and ignored this from the example I got
 */
 .url(System.getenv().get("JDBC_DATABASE_URL")) // Here I'm using a JDBC url
 .build();
 return new JdbcTokenStore(tokenDataSource);
}

We change the configure method to use the tokenStore

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    endpoints.authenticationManager(authenticationManager);
    endpoints.userDetailsService(accountUserDetailService);
    endpoints.tokenStore(tokenStore());
}

Add the two tables that will have the tokens stored into them, if your using Postgresql I replaced the Blob type for a bytea type.

create table oauth_access_token (
  token_id VARCHAR(256),
  token BLOB,
  authentication_id VARCHAR(256) PRIMARY KEY,
  user_name VARCHAR(256),
  client_id VARCHAR(256),
  authentication BLOB,
  refresh_token VARCHAR(256)
);

create table oauth_refresh_token (
  token_id VARCHAR(256),
  token BLOB,
  authentication BLOB
);


Remove the CommandLineRunner @Bean from the AuthServiceApplication class.
Create the account table in the SQL Storage your using or place this

spring.jpa.hibernate.ddl-auto=update

in resources/application.properties if you do it the table will be create automatically on the system boot. If not you have to create it by hand.

This bellow was for postgresql

\d account
Table “public.account”
Column | Type | Modifiers
———-+————————+———–
id | bigint | not null
active | boolean | not null
password | character varying(255) |
username | character varying(255) |
Indexes:
“account_pkey” PRIMARY KEY, btree (id)

I was provided with the following link in freenode to github that has the full DB schema for the oauth part.

https://github.com/spring-projects/spring-security-oauth/blob/master/spring-security-oauth2/src/test/resources/schema.sql

Missing in this is the encoding of the User password…

For user jlong password spring

update account set password = ‘$2a$06$.D77Cpf92IZx/L84TUiVAuqTAcV9F1MUblFL26COWDNlvb6dFVCVu’ where id = 1;
UPDATE 1

For password cloud

update account set password = ‘$2a$06$iDAlgXOdcZX1Wm8j0KR1rOi1XyQprLsc78RwH2ikn0to9W9HzM5ci’ where id = 2;
UPDATE 1

Generated using http://bcrypthashgenerator.apphb.com/?PlainText=cloud

Uncomment the

@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}

in

public class AuthServiceConfiguration extends AuthorizationServerConfigurerAdapter {

And had to remove the constructor I had accepting the authenticationManager, and left it only to be inserted by Autowire.

Getting the Principal on the Resource Server…Using the Principal (Active User)to limit the data returned:

Using the Principal on the Resource Server , for this I had to extend the User Object to my own implementation, I didn’t want to touch to much on the Database side of Accounts so I created a new Object UserInfo

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;

import java.util.Collection;

public class UserInfo extends User {

    private Long Id;

    public UserInfo(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities, Long id) {
        super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
        Id = id;
    }

    public Long getId() {
        return Id;
    }
}

Has seen this above has a aditional field Id wich I use to relate the Account to the item being managed in the Resource Server (I’m also returning Roles in this (done by default)). To the Account Entity I added the following method and private class to manage the GrantedAuthority types.

public UserInfo getUser() {
    List authorities = new ArrayList();

    authorities.add(new GrantedAuthorityImpl("ROLE_ADMIN"));

    return new UserInfo(this.getUsername(), this.getPassword(), this.isActive(), this.isActive(), this.isActive(),
            this.isActive(), authorities, this.id);
}

private class GrantedAuthorityImpl implements GrantedAuthority {

    private String auth;

    public GrantedAuthorityImpl(String auth) {
        this.auth = auth;
    }

    @Override
    public String getAuthority() {
        return auth;
    }
}

And in the AccountUserDetailService.java I changed what was returned in the loadByUsername method.

return ac.map(account ->
        account.getUser()
    ).orElseThrow( () -> new UsernameNotFoundException("Could not find the username "+ username +" ."));

For my case this is all I need in the Authorization Server.

Extracting the Principal in the Resource Server

http://javahotpot.blogspot.com.br/2013/12/spring-security-adding-more-information.html

I had to place my custom UserInfo in the ResourceServer

public class UserInfo {

    private String id;

    private String username;

    private String email;

    public String getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id.toString();
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "Username: " + this.getUsername() + " ID: " + this.getId();
    }
}

And created an Extractor PrincipalExtractor Implementation to retrieve this new representation on the Resource Server

import far.botshop.backend.model.UserInfo;
import org.springframework.boot.autoconfigure.security.oauth2.resource.PrincipalExtractor;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class myPrincipalExtractor implements PrincipalExtractor {

    @Override
    public UserInfo extractPrincipal(Map<String, Object> map) {

        Map<String,Object> principal = null;

        if (map.containsKey("principal")) {
            principal = (Map<String, Object>) map.get("principal");
        }

        UserInfo user = new UserInfo();

        if (principal != null ) {
            if (principal.containsKey("id")) {
                user.setId(Long.parseLong(principal.get("id").toString()));
            }

            if (principal.containsKey("username")) {
                user.setUsername(principal.get("username").toString());
            }

            if (principal.containsKey("email")) {
                user.setEmail(principal.get("email").toString());
            }
        }

        System.out.println("----> " + user.getUsername() + " -> " + user.getId());

        return user;
    }
}

 

Using the Principal in the @Query annotation of the Repository to filter only items related to this Account.

For this one I had a few hiccups… https://stackoverflow.com/questions/45901014/spring-using-spel-principal

https://spring.io/blog/2014/07/15/spel-support-in-spring-data-jpa-query-definitions

I created the SecurityEvaluationContextExtension you can read the details on the link above.

@Service
public class SecurityEvaluationContextExtension extends EvaluationContextExtensionSupport {

    @Override
    public String getExtensionId() {
        return "security";
    }

    @Override
    public SecurityExpressionRoot getRootObject() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        System.out.println("SER >>>>> " + authentication.getPrincipal().toString() + " -- " );

        return new SecurityExpressionRoot(authentication) {
            @Override
            public UserInfo getPrincipal() {
                System.out.println("Fetching the principal has user " + authentication.getPrincipal().toString());
                return (UserInfo) authentication.getPrincipal();
            }
        };
    }
}
@Configuration
@EnableJpaRepositories
public class SecurityConfiguration {

    @Bean
    EvaluationContextExtension securityExtension() {
        return new SecurityEvaluationContextExtension();
    }

}

And the related Repository and Query

@CrossOrigin
public interface StoreRepository extends CrudRepository<Store, Long>
{
    @Query("select p , p.store, p.category from Product p JOIN p.store s " +
            " JOIN p.category c " +
            " WHERE p.store.id = :id AND p.keywords LIKE %:keyword% AND p.store.ownerId = ?#{#security.principal.id} ")
    List<Product> findByKeywordIgnoreCase(@Param("id") Long id , @Param("keyword") String keyword);
}

This #security.principal is not in the main docs but I’ve been told in Twitter by JPA Lead Developer ( Oliver Gierke @olivergierke ) that it can be a related bug solved in version 2.x of DATA JPA details in the stackoverflow link.

That’s it, if you do the Authentication to the authorization server and use the Bearer token to access the Resource Server you should have access to your Resource.

Anúncios

PHP: Autentication and Access Control in a modular web application

Hello,

This example is about the access control and authentication on a modular web application, developed in Symfony2 using the EventDispatcher, the logic of implementation can be used in different projects, that don’t necessarily use these tools. The basis of this access control is the usage of a main event dispatcher and listener (EventDriven) to detect destination request address and intercept it before it reaches that destination (controller + method ).

I first became aware of the idea of using Events to control access, I believe it was by on his blog a long time ago.

Anyway here I describe the usage of a Symfony2  custom EventListener to listen to a onKernelRequest

This usually happens this way:

Client -[call]-> Webserver -[dispatch event request]-> triggers onKernelRequest witch does validation -[Validates]-> if passes code continues normally inside symfony2  … Get the idea? I hope so.

First I implemented the interface in the AccessControl Class no other code will interact with this that’s the beauty of using a event for access control, you can have the event manage the control access of all modules without having to interact directly with them. The code is commented for easier reading…

Class AccessControl implements EventSubscriberInterface

public function __construct($em, $dispatcher, $security, $router)
{
$this->em = $em; // the EntityManager not used in this demo
$this->dispatcher = $dispatcher; // The SF2 EventDispatcher
$this->security = $security; // security.context
$this->router = $router; // router to know where the request is going to
}

And of course I will be listening to onKernelRequest events

public static function getSubscribedEvents()
{
return array(
KernelEvents::REQUEST => [‘onKernelRequest’, 0],
);
}

Here follows an example on access control without any dynamic database support

This is a basic decision path based on the destination route using the symfony name and the request from the client.

public function onKernelRequest($event)
{
if ($event->getRequestType() != HttpKernelInterface::MASTER_REQUEST) {
return null; // will only be handled if it’s from a external request else returns null
}

$user = $this->security->getToken()->getUser();  // get the current user information
$request = $event->getRequest(); // get the current request
$requested_uri = $request->getRequestUri(); // get the requested URI
$internal_route = $request->get(‘_route’); // this what is used to validate access

// $internal_route has the route name used by symfony witch I use to compare since it’s simpler

if ($internal_route == ‘fos_user_registration_register’) {
return true; // by default I allow the call to the registering of a new user
}

if ($user == ‘anon.’) {
$mainrequest = $event->getRequest();
// Matched route
$_route = $mainrequest->attributes->get(‘_route’);
// Matched controller
$_controller = $mainrequest->attributes->get(‘_controller’);
// All route parameters including the `_controller`
$params = $mainrequest->attributes->get(‘_route_params’);

if ($_route != ‘fos_user_security_login’) {

// if anonymous is not trying to login
// send him to login
$url = $this->router->generate(‘fos_user_security_login’);
$response = new RedirectResponse($url);
$event->setResponse($response);
}
return;
}

if ($user->hasGroup(“Admin”)) {
return true; // if the user has a group admin allow him to everywhere
}

$request = $event->getRequest();
$requested_uri = $request->getRequestUri();
$internal_route = $request->get(‘_route’); // this is what is used to validate access

if (mb_substr($internal_route, 0, mb_strlen(“lab_”)) == “lab_”) {
if ($user->hasGroup(“Laboratorio”)) {

// allow user to space _lab if he’s from the Group Laboratorio
return true;
} else {
// monolog here
throw new \Exception(“Unauthorized access. $internal_route”);
}
}

if (mb_substr($internal_route, 0, mb_strlen(“stock”)) == “stock”) {
if ($user->hasGroup(“Stock”)) {

// allow the user to access stock route names if he his in the stock Group
return true;
} else {
// monolog here
throw new \Exception(“Unauthorized access. $internal_route”);
}
}

if (mb_substr($internal_route, 0, mb_strlen(“user”)) == “user”) {
if ($user->hasGroup(“Admin”)) {

  // if the user is admin allow him to manage users
return true;
} else {
// monolog here
throw new \Exception(“Unauthorized access. $internal_route”);
}
}

}

After this, configure the services.xml file in Resources/config/  this will allow for the dependencies to be loaded in the object.

security.context provides information about the user logged (or not), router allow’s to generate a different destination route for the Event

In this gist you can see all the code used.

Best regards,

PHP Taking advantage of Traits and Doctrine2 for less lines of code

I did this app a time ago (~1 year) with Doctrine2+Symfony2 with simple Entities basically I was mimicking an excel sheet copying the values from the sheet to the database and setting all up for web usage.

The main Class was Item, this had Sub Entities Location, Protocol, State, etc…

These named here Location, Protocol, State had the same properties (fields), they also had to have a incrementable “Code” field witch, this was a basic copy paste to fill the tables and increment the number. Didn’t want to write the code to the different Entities so I used a Trait in a very lazy way I declared

TautoFill

namespace Far\AssetManagerBundle\Entity;

trait TautoFill {

    public function getAndInsert($val)
    {
        $this->_em->getConnection()->beginTransaction();

        $valtmp = strtoupper(str_replace(' ','',trim($val)));
        $Res = $this->findBy(['code' => $valtmp]);
        if (count($Res) > 0 && $Res[0] != null) {
            $obj = $Res[0];
            $obj->setTcount($obj->getTcount()+1);
            $this->_em->persist($obj);

            $this->_em->flush();

        } else {
            $tmp = $this->getClassName();
            $obj = new $tmp();
            $obj->setDescription($val);
            $obj->setCode($valtmp);
            $obj->setTcount(1);
            // persist
            $this->_em->persist($obj);
            $this->_em->flush();
        }

        $this->_em->getConnection()->commit();
        return $obj;
    }
}

So in a easy use TautoFill I got the data auto inserted and related to the main Item, without much work. Using a trait made the code more dynamic and easier to reimplement in the different situations without compromising hierarchy of the Entities.

PHP NumberFormatter

These are results from NumberFormatter from PHP

in the command line:

php -r ‘$a = new \NumberFormatter(“en”, \NumberFormatter::CURRENCY_CODE); print $a->format(122).PHP_EOL;’

You should get

one hundred twenty-two

Or

 php -r ‘$a = new \NumberFormatter(“pt_PT”, \NumberFormatter::CURRENCY); print $a->format(11122).PHP_EOL;’

You will  get

11 122,00 €

Get the Currency code now

print $a->getTextAttribute(NumberFormatter::CURRENCY_CODE).”\n”;

EUR

Java, Scala

Reading about scala I could only be curious about it, went to read details about the language and how it works. I get the idea that this is happening:

PHP is moving in the Java style direction… (Not trying to compare anything.)

Java is moving into a simpler coding Groovy, Scala ( in some cases harder) has Gosling him self professed. Both languages are being used in the financial markets( scala 1, scala 2, scala 3, Groovy ) for trading algorithms and social network Twitter , LinkedIn, it is said that Actors in Scala are a great way for Async communication Akka.Actors is said to be even better. Would like to have seen this two years ago, could have used this instead of Perl for a daemon I wrote. Both Scala and Groovy can use imported Java code.

James Gosling:
http://www.theserverside.com/news/2240022782/James-Gosling-Interview-from-Basementcoderscom

“I like Scala, but my big problem is that the type theory has gotten really complicated. The language lawyers are driving the bus. It’s turning into something that journeyman developers and even people like me… I started getting into the Scala stuff and my head starts to spin and I go, “what?””

Some Scala comments.

http://www.schauderhaft.de/2010/12/05/is-it-bad-to-use-scala-as-java-with-a-more-concise-syntax/

http://www.infoq.com/news/2009/07/scala-replace-java

Notice:
Gosling is listed as an advisor at the Scala company Typesafe Inc.[13] and Strategic Advisor for Eucalyptus.[14]

Clearly I’m more curious about Scala http://twitter.github.io/scala_school/ although Groovy has company’s supporting it but at the moment I’m just looking and playing not using. Scala Puzzlers

Java and JavaFX

After working with JavaEE I had enough PHP is simpler to use. And then I went to JavaFX and it was truly a better experience building the simple app that I wanted.

It was really simple to design and build the application for what I wanted and found good online support and that is something excellent.

Here’s the code.
https://bitbucket.org/odnanref/fxproductwatcher/src

Since I couldn’t get PHP 5.5 to work in Windows XP I chose to use Java (had something done in Python but the language syntax is more strange to me). The code is commented if anyone wants details about Thread + Tasks and UI.

Java for PHP Developers

I have been working with Java for android and a Web application purely for entertainment. For long I have seen PHP adopt more and more “ideas” from Java so to make it easy for someone that knows PHP to get into java and vice versa I’ll make some easy generic associations. This is from a HTTP point of view to simplify the relations.

Note: I have some basic background on Java and C# (Mono .NET), also I have an understanding of the design patterns that you will see applied in Java and in PHP frameworks and that helps understand the logic faster between the different languages.

  1. In PHP Controllers are Controllers, in Java they are mostly represented by a Servlet. It’s similar to Symfony 2  and Zend Framework adoption for handling requests. (Also in the Java Servlet can provide routing in the service method but not very used according to the reading I have been doing and the web.xml handles more of those requests).
  2. In PHP Models are provided by Frameworks Zend Framework or Symfony also has them, in Java they are usually called Beans and they also take the role of “Services” witch is something that came up in Zend Framework 2 and Symfony 2 not knew but the concept in the framework has been more noticeable.
  3. Template in PHP is done using some one of the following (known to have more) Smarty, Twig, normal PHP + HTML. In Java it is done via “tags” in Javaserver Pages (JSP) the approach of Javaserver Pages + Tags + Controller (Servlet) looked a lot like the Symfony 2 approach. (or vice versa)
  4. HTTP Server Jetty (there is jetty for android) is a simple to use webserver built in java witch is simple to deploy and run you can print a hello world pretty fast with not much work with it. Apache/Nginx install + PHP + some DB still is faster to me since it actually has more documentation and isn’t so java centered.
  5. Build and dependency management tools Maven is a most simple way to manage and install dependency’s in Java just get some example pom.xml files to get your basics and understand the build process and it looks like composer (yes that thing that many criticize). Maven also can create standard working environments and run tests.
  6. A ORM known in PHP is Doctrine a similar ORM in Java can be Hibernate. Hibernate also supports config by Annotations.
  7. Configuration in PHP can be handled on whatever you want to use, in frameworks like Symfony 2 it’s known has app/config.yml in Zend Framework 1 it’s application.ini in Zend Framework 2 it’s TODO something it’s more of a users choice. Symfony 2 also supports Annotations (via Doctrine Annotations) for route config et all, but in Java the Spring Framework his what I know to have those quirks but the Annotations are built in the language the main configuration for web development is usually a web.xml file in a WEB-INF directory.
  8. Database connetions PDO is for PHP what JDBC is for Java for database connection
  9. Packaging WAR or JAR it’s Java package what was based for Phar files in PHP
  10. Unit testing in PHP can be PHPUnit and in Java it can be jUnit
  11. Routing requests If you are looking in a more annotation style configuration for routing requests look at this text from wikipedia JAX-RS: Java API for RESTful Web Services and Rewrite Engine

This is a somewhat generic way of comparing the two languages but what you can notice is that Java like PHP has some built around solutions built with the language but they are supplied by standard API has .jar files and like PHP it also has a very intense activity around and different solutions ( just to say maybe we shouldn’t criticize having a lot of frameworks as Matthew Weier O’Phinney says:

Second, I also think there’s space for multiple implementations of any given component. Often there are different approaches that different authors will take: one might focus on performance, another on having multiple adapters for providing different capabilities, etc. Sometimes having a different background will present different problem areas you want to resolve. As such, having multiple implementations can be a very good thing; developers can look at what each provides, and determine which solves the particular issues presented in the current project.

(this last quote was placed because of a lot of discussion I see in forums and mailing lists regarding standardization of the way the developer codes and the way the language is built. Nothing new was said but the discussion of the PHP group (fig) is “deja vu”.

Coding in Java…

Well it’s not that simple has in PHP… Small example you do a POST in PHP you could just $_POST[“FormDemo”][“id”] , $_POST[“FormDemo”][“name”] , in Java it follows the standards strictly and you can only handle key value pair posts. You can handle the PHP POST array format but that involves regular expressions for what I’ve seen not simple has in PHP.

In Java you get strings via HTTP and change it to the format you require, in PHP you get Strings or whatever and you rarely care and if you care much you can type cast the variable if it’s int, float or Array.

Integer.ParseInt(string) will be your friend for Integer values for the “what you may want”.

Map<String,String> KeyValue = new Map<String,String>();

http://www.vogella.com/articles/EclipseWTP/article.html

Build setup:

I started by using Eclipse + Eclipse Web development tools and jetty with basic code, then installed Maven and https://code.google.com/p/run-jetty-run/ plugin search for it in eclipse market I wasn’t thinking on hibernate but I wanted something more abstract to handle the database and I am using Doctrine in PHP so just searched for a ORM in Java and went with that one.

 

UPDATE:

PHP is simpler to use my issue with Java it’s not about the Type declaration I actually like that and sometimes wish that was better in PHP. I actually didn’t like the server setup requirements I started with jetty witch is very simple but the deployment using maven and all that… If I was coding pure PHP it would have been faster and simpler. Frameworks in Java allow you the basic to build “normal stuff” in a simpler way like “routes” et all. But in PHP you actually can get something like that in a more simpler way and faster by just coding. JavaEE at the just looks like over complicated for a simple web app solution.