Tuesday, January 31, 2017

Reaching Millennials With Social Media: New Research

Are Millennials part of your customer base? Wondering how best to reach them on social media? In this article, you’ll discover insights from new research you can use to get your social media messages in front of Millennials. #1: Millennials Are Digital Shoppers Millennials, those individuals born between 1980 and 2000, make up 25% of [...]

This post Reaching Millennials With Social Media: New Research first appeared on .
- Your Guide to the Social Media Jungle


by Michelle Krasniak via

north2

An unusual bunch of creatives who share one vision - making websites that stand out of the many.
by via Awwwards - Sites of the day

Monday, January 30, 2017

Share It While It's Hot: 7 Secrets to Shareable Content

In order online content to be shareable, it must meet countless requirements. Interesting to viewers, usefulness, calls-to-action, and so on. Sometimes, it seems like making the content viral requires magic because it is difficult to surprise people. While it is completely true that viral content...

[ This is a content summary only. Visit our website http://ift.tt/1b4YgHQ for full links, other content, and more! ]

by Guest Author via Digital Information World

Using CDI/Weld to Inject JPA/Hibernate Entity Managers

In this post we'll learn how easy it is to leverage the power of CDI (Contexts and Dependency Injection) / Weld in the development of a full-blow JPA / Hibernate application. The inherently permissive nature of CDI allows to turn literally any class into an injectable component, thus making the injection of Java EE resources as easy as injecting POJOs. This means that, for example, entity managers and even datasources objects can be injected anywhere by using just a few custom qualifiers.

This is a very powerful - yet pretty underrated - feature, quite often overlooked by CDI newcomers, who just don't know that the standard provides this functionality out of the box. Let's see now how to make an entity manager an injectable resource and build a simple JPA application from the ground up!

In a recent article I covered the basics of the CDI / Weld tandem, ranging from using the @Default, @Alternative and @Producesannotations, to working with a few more distilled features, such as polymorphic injection points and custom qualifiers. I used them to develop a naive standalone application, which showed how to inject different implementers of a simple interface into a client object at run time to parse a string entered in the console. We will use these skills now, so if you're not entirely sure how to do those things, read up on it - I'll wait.

Considering that we'll be working extensively with JPA / Hibernate in this walkthrough, I assume that you have at least a minimal background on them - otherwise check this Hibernate tutorial.

Creating an Injectable Entity Manager

The crux of the matter of any CDI-based JPA application is the creation of an injectable entity manager. It's worth noting that regardless of the approach that we use to get the manager, once it becomes an injectable Java EE resource, the entirety of the examples shown in the rest of the post are equally valid. From that point onward, creating and injecting all sort of objects across different layers is quite simple.

So the first task that we need to tackle is exactly that one: making the entity manager an injectable resource. In doing so, we can bind JPA to Hibernate (the reference JPA implementation) and run CRUD operations on some naive JPA entities without hassle.

In fact, there are a few straightforward approaches that we can pick from to accomplish this.

Using the @PersistentContext Annotation

The most painless way, which only works with a Java EE application server, such as Apache TomEE, JBoss Widlfly or Jetty, is the @PersistenceContext annotation. As we might expect, this methodology binds a persistence context (and a persistence unit, of course) to an entity manager, and the manager's lifecycle is entirely managed by the container (aka a container-managed entity manager).

At a broadly generic level, this approach can be implemented by using a custom qualifier like this:

@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD,
        ElementType.TYPE, ElementType.PARAMETER})
public @interface MySQLDatabase {}

public class EntityManagerProducer {

    @Produces
    @PersistenceContext(unitName = "my-persistence-unit")
    @MySQLDatabase
    private EntityManager entityManager;

}

In this case, the unitName attribute specifies the name of a sample persistence unit associated with the corresponding persistence context. So, if you're going to use this approach, make sure the name matches the one specified in Hibernate's persistence.xml file.

With that code in place, a simple DAO class that takes the entity manager in the constructor can be defined as follows:

public class MyDao {

    private EntityManager entityManager;

    @Inject
    public MyDao(@MySQLDatabase EntityManager entityManager) {
        this.entityManager = entityManager;
    }

}

While this will work with a fully-qualified Java EE container (feel free to give it a try if you already have one installed on your system), we don't want to rely on that particular method, since we won't be using a Java EE container for running the JPA application presented in this article.

Using a Producer Method

Just plain Java, CDI, and Weld should get the job done for us. How do we do the injection of the manager in this environment? Well, we can encapsulate the creation of a non-managed entity manager inside a producer method and bind to it a custom qualifier, as follows:

@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD,
        ElementType.TYPE, ElementType.PARAMETER})
public @interface MySQLDatabase {}

public class EntityManagerProducer {

    @Produces
    @MySQLDatabase
    public EntityManager createEntityManager() {
        return Persistence
                .createEntityManagerFactory("my-persistence-unit")
                .createEntityManager();
    }

    public void close(
            @Disposes @MySQLDatabase EntityManager entityManager) {
        entityManager.close();
    }

}

In this case, the createEntityManager() method is responsible for creating the non-managed entity manager through an entity manager factory. As with the first approach, the name of the persistence unit passed to the createEntityManagerFactory() method must be the same as the one defined in Hibernate's configuration file. Make sure to do that, before you pull out your hair trying to figure out why Hibernate can't find a persistence unit to work with.

This is JPA at its most elemental level, so the only point worth stressing here is the use of the @Disposes annotation. It informs the CDI container that this method closes the entity manager, which makes the container call it before releasing the manager.

At this stage, we've managed to create a fully injectable entity manager with a simple producer method. But let's think through this: Why should we bother ourselves with the twist and turns of this process, if we're not going to use the manager in a productive way? Yikes!

As we saw earlier, a typical use case is to inject the manager into a DAO class, something that would allow us to perform CRUD operations on some JPA entities through an easily consumable API, and, best of all, without having to unnecessarily expose from top to bottom the manager's API to client code. The most effective way to design this distilled, abstract API is by implementing a simple data access layer (DAL). CDI makes building this layer a breeze, but as usual, an example would help us understand the inner workings of this process much more easily.

[caption id="attachment_146280" align="aligncenter" width="1024"]Published by Sean Michael Ragan under CC-BY 2.0 Published by Sean Michael Ragan under CC-BY 2.0[/caption]

Abstracting Data Access with a Basic Data Access Layer (DAL)

Continue reading %Using CDI/Weld to Inject JPA/Hibernate Entity Managers%


by Alejandro Gervasio via SitePoint

New Course: Start Coding With ASP.NET Core

A Beginners Guide to Webpack 2 and Module Bundling

A squeezing machine that compresses all web elements

Webpack is a module bundler

Webpack has become one of the most important tools for modern web development. Primarily it's a module bundler for your JavaScript but it can be taught to transform all of your front-end assets like HTML and CSS, even images. It can give you more control over the number of HTTP requests your app is making and allows you to use other flavors of those assets (Jade, Sass & ES6 for example). Webpack also allows you to easily consume packages from npm.

This article is aimed at those who are new to webpack and will cover initial setup and configuration, modules, loaders, plugins, code splitting and hot module replacement. If you find video tutorials helpful I can highly recommend Glen Maddern's Webpack from First Principles as a starting point to understand what it is that makes webpack special.

To follow along at home you'll need to have Node.js installed. You can also download the demo app from our Github repo.

Setup

Let's initialize a new project with npm and install webpack:

mkdir webpack-demo
cd webpack-demo
npm init -y
npm install webpack@beta --save-dev
mkdir src
touch index.html src/app.js webpack.config.js

Edit these files:

<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Hello webpack</title>
  </head>
  <body>
    <div id="root"></div>
    <script src="dist/bundle.js"></script>
  </body>
</html>

// src/app.js
const root = document.querySelector('#root')
root.innerHTML = `<p>Hello webpack.</p>`

// webpack.config.js
const config = {
  context: __dirname + '/src',
  entry: './app.js',
  output: {
    path: __dirname + '/dist',
    filename: 'bundle.js'
  },
  module: {
    rules: [{
      test: /\.js$/,
      include: __dirname + '/src',
      use: [{
        loader: 'babel-loader',
        options: {
          presets: [
            ['es2015', { modules: false }]
          ]
        }
      }]
    }]
  }
}

module.exports = config

The config above is a common starting point, it instructs webpack to compile our entry point src/app.js into our output /dist/bundle.js and all .js files will be transpiled from ES2015 to ES5 with Babel.

To get this running we're going to need to install three packages, babel-core, the webpack loader babel-loader and the preset babel-preset-es2015 for the flavor of JavaScript we want to write. { modules: false } enables Tree Shaking to remove unused exports from your bundle to bring down the file size.

npm install babel-core babel-loader babel-preset-es2015 --save-dev

Lastly, replace the scripts section of package.json with the following:

"scripts": {
  "start": "webpack --watch",
  "build": "webpack -p"
},

Running npm start from the command line will start webpack in watch mode which will recompile our bundle whenever a .js file is changed in our src directory. The output in the console tells us about the bundles being being created, it's important to keep an eye on the number of bundles and the size.

Console output of running webpack in watch mode

You should now be able to load index.html in your browser and be greeted with "Hello webpack.".

open index.html

Open up dist/bundle.js to see what webpack has done, at the top is webpack's module bootstrapping code and right at the bottom is our module. You may not be colored impressed just yet but if you've come this far you can now start authoring ES6 modules and webpack will be able to produce a bundle for production that will work in all browsers.

Stop webpack with Ctrl + C and run npm run build to compile our bundle in production mode.

Notice that the bundle size has come down from 2.61 kB to 585 bytes.
Take another look at dist/bundle.js and you'll see a big ugly mess of code, our bundle has been minified with UglifyJS, the code will run exactly the same but it's done with the fewest characters needed.

Modules

Out of the box webpack knows how to consume JavaScript modules in a variety of formats, the most notable two are:

  • ES2015 import statements
  • CommonJS require() statements

We can test this out by installing lodash and importing it from app.js

npm install lodash --save

// src/app.js
import {groupBy} from 'lodash/collection'

const people = [{
  manager: 'Jen',
  name: 'Bob'
}, {
  manager: 'Jen',
  name: 'Sue'
}, {
  manager: 'Bob',
  name: 'Shirley'
}, {
  manager: 'Bob',
  name: 'Terrence'
}]
const managerGroups = groupBy(people, 'manager')

const root = document.querySelector('#root')
root.innerHTML = `<pre>${JSON.stringify(managerGroups, null, 2)}</pre>`

Run npm start to start webpack and refresh index.html, you should see an array of people grouped by manager.

Let's move the array of people into its own module people.js

// src/people.js
const people = [{
  manager: 'Jen',
  name: 'Bob'
}, {
  manager: 'Jen',
  name: 'Sue'
}, {
  manager: 'Bob',
  name: 'Shirley'
}, {
  manager: 'Bob',
  name: 'Terrence'
}]

export default people

We can simply import it from app.js with a relative path.

// src/app.js
import {groupBy} from 'lodash/collection'
import people from './people'

const managerGroups = groupBy(people, 'manager')

const root = document.querySelector('#root')
root.innerHTML = `<pre>${JSON.stringify(managerGroups, null, 2)}</pre>`

Note: Imports without a relative path like 'lodash/collection' are modules from npm installed to /node_modules, your own modules will always need a relative path like './people', this is how you can tell them apart.

Loaders

We've already been introduced to babel-loader, one of many loaders that you can configure to tell webpack what to do when it encounters imports for different file types. You can chain loaders together into a series of transforms, a good way to see how this works is by importing Sass from our JavaScript.

Continue reading %A Beginners Guide to Webpack 2 and Module Bundling%


by Mark Brown via SitePoint

Web Design Weekly #265

Headlines

Understanding the Critical Rendering Path

Ire Aderinokun explains in a clear and concise manner why having knowledge of the critical rendering path for web pages is useful for understanding how a site’s performance can be improved. (bitsofco.de)

Opinions of Leaders Considered Harmful (cssmojo.com)

Sponsor Web Design Weekly and reach over 22,000 passionate designers and developers

Articles

Design like a Developer

Some great tips on how to go about designing as if you were building UI components in a development environment. (medium.com)

Crash Course – UI Design

A pretty epic article by Jeff Wang that revisits the design process he took on a recent project from the UI angle. (medium.com)

A Simple Use of CSS Grid

A nice little primer to get your feet wet with CSS Grid. (theboldreport.net)

The Infrastructure Behind Twitter – Scale (blog.twitter.com)

Tools / Resources

A Quick Intro to Styled Components

Sacha Greif gives us a small glimpse into Styled Components so we can decide if it’s worth checking out. (freecodecamp.com)

Practical Redux, Part 8

Another awesome deep dive into the inner workings of Redux by Mark Erikson. If you happen to be working with Redux, Mark’s series is a must read. (blog.isquaredsoftware.com)

An Introduction to Observables for Angular Developers

Jen Looper looks into the concept of the Observable; what they are, why she prefers them to other methods for handling data and some real world examples. (developer.telerik.com)

Awesome Case Studies

A curated list of technical case studies, mostly around front-end/creative development. (github.com)

Running Express, Koa And Hapi On HTTP/2 (ivanjov.com)

Inspiration

Smashing Magazine Case Study (sarasoueidan.com)

Developer Tea with Wes Bos (spec.fm)

New Mozilla Branding (subtraction.com)

Jobs

Designer at Help Scout

Designers at Help Scout are responsible for the brand, and for creating an exceptional product experience. Everything customer-facing passes through the design team in some way. You’ll be making things that are seen and/or used by several hundred thousand people every month. (helpscout.net)

Product Designer at Pusher

We’re going to do this by creating even more great products which are beautiful, simple to use, reliable and built with developers in mind. Now we’re looking for a Designer to help us get there. (pusher.com)

Need to find passionate developers or designers? Why not advertise in the next newsletter

Last but not least…

JavaScript Rising Stars (risingstars2016.js.org)

The post Web Design Weekly #265 appeared first on Web Design Weekly.


by Jake Bresnehan via Web Design Weekly