스프링 프레임워크 메인 프로젝트 Spring framework project

Posted by HULIA(휴리아)
2018. 4. 5. 01:58 백엔드개발/자바스프링

Main Projects

1.Spring IO Platform

2.Spring Boot

3.Spring Framework

4.Spring Cloud Data Flow

5.Spring Cloud

6.Spring Data

7.Spring Integration

8.Spring Batch

9.Spring Security

10.Spring Hateoas

11.Spring Rest Docs

12.Spring Social

13.Spring Amqp

14.Spring Mobile

15.Spring For Android

16.Spring Web Flow

17.Spring Web Services

18.Spring Ldap

19.Spring Session

20.Spring Shell

21.Spring Flo

22.Spring Kafka

23.Spring Statemachine



Spring IO Platform

https://platform.spring.io/platform/

Spring IO is a cohesive, versioned platform for building modern applications. It is a modular, enterprise-grade distribution that delivers a curated set of dependencies while keeping developers in full control of deploying only the parts they need. Spring IO is 100% open source, lean, and modular.


The Spring IO platform includes Foundation Layer modules and Execution Layer domain-specific runtimes (DSRs). The Foundation layer represents the core Spring modules and associated third-party dependencies that have been harmonized to ensure a smooth development experience. The DSRs provided by the Spring IO Execution Layer dramatically simplify building production-ready, JVM-based workloads. The first release of Spring IO includes two DSRs: Spring Boot and Grails


Features

One platform, many workloads - build web, integration, batch, reactive or big data applications

Radically simplified development experience with Spring Boot

Production-ready features provided out of the box

Curated and harmonized dependencies that just work together

Modular platform that allows developers to deploy only the parts they need

Support for embedded runtimes, classic application server, and PaaS deployments

Depends only on Java SE, and supports Groovy, Grails and some Java EE

Works with your existing dependency management tools such as Maven and Gradle

The Spring IO Platform is certified to work on JDK 7 and 8*

*While the Spring IO Platform supports JDK 7 and 8, many individual Spring projects also support older JDK versions. Please refer to the [individual projects' documentation] (http://spring.io/docs) for the specific minimum requirements.



Spring Boot

https://projects.spring.io/spring-boot/

Takes an opinionated view of building production-ready Spring applications. Spring Boot favors convention over configuration and is designed to get you up and running as quickly as possible.


Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can "just run". We take an opinionated view of the Spring platform and third-party libraries so you can get started with minimum fuss. Most Spring Boot applications need very little Spring configuration.


Features

Create stand-alone Spring applications

Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files)

Provide opinionated 'starter' POMs to simplify your Maven configuration

Automatically configure Spring whenever possible

Provide production-ready features such as metrics, health checks and externalized configuration

Absolutely no code generation and no requirement for XML configuration

The reference guide includes detailed descriptions of all the features, plus an extensive howto for common use cases.



Spring Framework

https://projects.spring.io/spring-framework/

The Spring Framework provides a comprehensive programming and configuration model for modern Java-based enterprise applications - on any kind of deployment platform. A key element of Spring is infrastructural support at the application level: Spring focuses on the "plumbing" of enterprise applications so that teams can focus on application-level business logic, without unnecessary ties to specific deployment environments.


Features

Core technologies: dependency injection, events, resources, i18n, validation, data binding, type conversion, SpEL, AOP.

Testing: mock objects, TestContext framework, Spring MVC Test, WebTestClient.

Data Access: transactions, DAO support, JDBC, ORM, Marshalling XML.

Spring MVC and Spring WebFlux web frameworks

Integration: remoting, JMS, JCA, JMX, email, tasks, scheduling, cache.

Languages: Kotlin, Groovy, dynamic languages.


Minimum requirements

JDK 8+ for Spring Framework 5.x

JDK 6+ for Spring Framework 4.x

JDK 5+ for Spring Framework 3.x



Spring Cloud Data Flow

https://cloud.spring.io/spring-cloud-dataflow/

Spring Cloud Data Flow is a toolkit for building data integration and real-time data processing pipelines.


Pipelines consist of Spring Boot apps, built using the Spring Cloud Stream or Spring Cloud Task microservice frameworks. This makes Spring Cloud Data Flow suitable for a range of data processing use cases, from import/export to event streaming and predictive analytics.


The Spring Cloud Data Flow server uses Spring Cloud Deployer, to deploy pipelines onto modern runtimes such as Cloud Foundry, Kubernetes, Apache Mesos or Apache YARN.


A selection of pre-built stream and task/batch starter apps for various data integration and processing scenarios facilitate learning and experimentation.


Custom stream and task applications, targeting different middleware or data services, can be built using the familiar Spring Boot style programming model.


A simple stream pipeline DSL makes it easy to specify which apps to deploy and how to connect outputs and inputs. A new composed task DSL was added in v1.2.


The dashboard offers a graphical editor for building new pipelines interactively, as well as views of deployable apps and running apps with metrics.


The Spring Could Data Flow server exposes a REST API for composing and deploying data pipelines. A separate shell makes it easy to work with the API from the command line.


Platform Implementations

An easy way to get started on Spring Cloud Data Flow would be to follow the platform-specific implementation links from the table below. Each of the implementations evolves in isolation with independent release cadences. It is highly recommended to review the platform-specific reference docs to learn more about the feature capabilities.


Server Type Stable Release Milestone/Snapshot Release

Local Server         1.4.0.RELEASE[docs] 1.5.0.BUILD-SNAPSHOT[docs]

Cloud Foundry Server 1.4.0.RELEASE[docs] 1.5.0.BUILD-SNAPSHOT[docs]

Kubernetes Server     1.4.0.RELEASE[docs] 1.5.0.BUILD-SNAPSHOT[docs]

Apache YARN Server 1.2.2.RELEASE[docs] 1.2.3.BUILD-SNAPSHOT[docs]

Apache Mesos Server 1.0.0.RELEASE[docs] 1.1.0.BUILD-SNAPSHOT[docs]



Spring Cloud

https://projects.spring.io/spring-cloud/

Spring Cloud provides tools for developers to quickly build some of the common patterns in distributed systems (e.g. configuration management, service discovery, circuit breakers, intelligent routing, micro-proxy, control bus, one-time tokens, global locks, leadership election, distributed sessions, cluster state). Coordination of distributed systems leads to boiler plate patterns, and using Spring Cloud developers can quickly stand up services and applications that implement those patterns. They will work well in any distributed environment, including the developer's own laptop, bare metal data centres, and managed platforms such as Cloud Foundry.


Spring Cloud builds on Spring Boot by providing a bunch of libraries that enhance the behaviour of an application when added to the classpath. You can take advantage of the basic default behaviour to get started really quickly, and then when you need to, you can configure or extend to create a custom solution.




Spring Data

https://projects.spring.io/spring-data/

Spring Data’s mission is to provide a familiar and consistent, Spring-based programming model for data access while still retaining the special traits of the underlying data store. 


It makes it easy to use data access technologies, relational and non-relational databases, map-reduce frameworks, and cloud-based data services. This is an umbrella project which contains many subprojects that are specific to a given database. The projects are developed by working together with many of the companies and developers that are behind these exciting technologies.


Features

Powerful repository and custom object-mapping abstractions

Dynamic query derivation from repository method names

Implementation domain base classes providing basic properties

Support for transparent auditing (created, last changed)

Possibility to integrate custom repository code

Easy Spring integration via JavaConfig and custom XML namespaces

Advanced integration with Spring MVC controllers

Experimental support for cross-store persistence


Main modules

Spring Data Commons - Core Spring concepts underpinning every Spring Data project.

Spring Data Gemfire - Provides easy configuration and access to GemFire from Spring applications.

Spring Data JPA - Makes it easy to implement JPA-based repositories.

Spring Data JDBC - JDBC-based repositories.

Spring Data KeyValue - Map-based repositories and SPIs to easily build a Spring Data module for key-value stores.

Spring Data LDAP - Provides Spring Data repository support for Spring LDAP.

Spring Data MongoDB - Spring based, object-document support and repositories for MongoDB.

Spring Data REST - Exports Spring Data repositories as hypermedia-driven RESTful resources.

Spring Data Redis - Provides easy configuration and access to Redis from Spring applications.

Spring Data for Apache Cassandra - Spring Data module for Apache Cassandra.

Spring Data for Apache Solr - Spring Data module for Apache Solr.


Community modules

Spring Data Aerospike - Spring Data module for Aerospike.

Spring Data ArangoDB - Spring Data module for ArangoDB.

Spring Data Couchbase - Spring Data module for Couchbase.

Spring Data Azure DocumentDB - Spring Data module for Microsoft Azure DocumentDB.

Spring Data DynamoDB - Spring Data module for DynamoDB.

Spring Data Elasticsearch - Spring Data module for Elasticsearch.

Spring Data Hazelcast - Provides Spring Data repository support for Hazelcast.

Spring Data Jest - Spring Data for Elasticsearch based on the Jest REST client.

Spring Data Neo4j - Spring based, object-graph support and repositories for Neo4j.

Spring Data Spanner - Google Spanner support via Spring Cloud GCP.

Spring Data Vault - Vault repositories built on top of Spring Data KeyValue.


Related modules

Spring Data JDBC Extensions - Provides extensions to the JDBC support provided in the Spring Framework.

Spring for Apache Hadoop - Simplifies Apache Hadoop by providing a unified configuration model and easy to use APIs for using HDFS, MapReduce, Pig, and Hive.

Spring Content - Associate content with your Spring Data Entities and store it in a number of different stores including the File-system, S3, Database or Mongo’s GridFS.


Release train

Spring Data is an umbrella project consisting of independent projects with, in principle, different release cadences. To manage the portfolio, a BOM (Bill of Materials - see this example) is published with a curated set of dependencies on the individual project. The release trains have names, not versions, to avoid confusion with the sub-projects.


The names are an alphabetic sequence (so you can sort them chronologically) with names of famous computer scientists and software developers. When point releases of the individual projects accumulate to a critical mass, or if there is a critical bug in one of them that needs to be available to everyone, the release train will push out “service releases” with names ending “-SRX”, where “X” is a number.


Currently the release train contains the following modules:


Spring Data Commons

Spring Data JPA

Spring Data KeyValue

Spring Data LDAP

Spring Data MongoDB

Spring Data Gemfire

Spring Data for Apache Geode

Spring Data REST

Spring Data Redis

Spring Data for Apache Cassandra

Spring Data for Apache Solr

Spring Data Couchbase (community module)

Spring Data Elasticsearch (community module)

Spring Data Neo4j (community module)



Spring Integration

https://projects.spring.io/spring-integration/

Extends the Spring programming model to support the well-known Enterprise Integration Patterns. Spring Integration enables lightweight messaging within Spring-based applications and supports integration with external systems via declarative adapters. Those adapters provide a higher-level of abstraction over Spring's support for remoting, messaging, and scheduling. Spring Integration's primary goal is to provide a simple model for building enterprise integration solutions while maintaining the separation of concerns that is essential for producing maintainable, testable code.


Using the Spring Framework encourages developers to code using interfaces and use dependency injection (DI) to provide a Plain Old Java Object (POJO) with the dependencies it needs to perform its tasks. Spring Integration takes this concept one step further, where POJOs are wired together using a messaging paradigm and individual components may not be aware of other components in the application. Such an application is built by assembling fine-grained reusable components to form a higher level of functionality. WIth careful design, these flows can be modularized and also reused at an even higher level.


In addition to wiring together fine-grained components, Spring Integration provides a wide selection of channel adapters and gateways to communicate with external systems. Channel Adapters are used for one-way integration (send or receive); gateways are used for request/reply scenarios (inbound or outbound). For a full list of adapters and gateways, refer to the reference documentation.


The Spring Cloud Stream project builds on Spring Integration, where Spring Integration is used as an engine for message-driven microservices.


Features

Implementation of most of the Enterprise Integration Patterns

Endpoint

Channel (Point-to-point and Publish/Subscribe)

Aggregator

Filter

Transformer

Control Bus

Integration with External Systems

ReST/HTTP

FTP/SFTP

Twitter

WebServices (SOAP and ReST)

TCP/UDP

JMS

RabbitMQ

Email

The framework has extensive JMX support

Exposing framework components as MBeans

Adapters to obtain attributes from MBeans, invoke operations, send/receive notifications




Spring Batch

https://projects.spring.io/spring-batch/

A lightweight, comprehensive batch framework designed to enable the development of robust batch applications vital for the daily operations of enterprise systems.



Spring Batch provides reusable functions that are essential in processing large volumes of records, including logging/tracing, transaction management, job processing statistics, job restart, skip, and resource management. It also provides more advanced technical services and features that will enable extremely high-volume and high performance batch jobs through optimization and partitioning techniques. Simple as well as complex, high-volume batch jobs can leverage the framework in a highly scalable manner to process significant volumes of information.


Features

Transaction management

Chunk based processing

Declarative I/O

Start/Stop/Restart

Retry/Skip

Web based administration interface (Spring Cloud Data Flow)



Spring Security

https://projects.spring.io/spring-security/

Spring Security is a powerful and highly customizable authentication and access-control framework. It is the de-facto standard for securing Spring-based applications.


Spring Security is a framework that focuses on providing both authentication and authorization to Java applications. Like all Spring projects, the real power of Spring Security is found in how easily it can be extended to meet custom requirements


Features

Comprehensive and extensible support for both Authentication and Authorization

Protection against attacks like session fixation, clickjacking, cross site request forgery, etc

Servlet API integration

Optional integration with Spring Web MVC

Much more…



Spring Hateoas

https://projects.spring.io/spring-hateoas/

Create REST representations that follow the HATEOAS principle from your Spring-based applications.


Spring HATEOAS provides some APIs to ease creating REST representations that follow the HATEOAS principle when working with Spring and especially Spring MVC. The core problem it tries to address is link creation and representation assembly.


Features

Model classes for link, resource representation models

Link builder API to create links pointing to Spring MVC controller methods

Support for hypermedia formats like HAL



Spring Rest Docs

https://projects.spring.io/spring-restdocs/

Document RESTful services by combining hand-written documentation with auto-generated snippets produced with Spring MVC Test.


Spring REST Docs helps you to document RESTful services. It combines hand-written documentation written with Asciidoctor and auto-generated snippets produced with Spring MVC Test. This approach frees you from the limitations of the documentation produced by tools like Swagger. It helps you to produce documentation that is accurate, concise, and well-structured. This documentation then allows your users to get the information they need with a minimum of fuss.




Spring Social

https://projects.spring.io/spring-social/

Connect your Spring application with Software-as-a-Service (SaaS) API providers such as Facebook, Twitter, and LinkedIn.


SPRING SOCIAL CORE

A framework for creating connections between a Spring application and an API. Also includes support for "Sign in With [Provider]" for authenticating via an API provider.

 

SPRING SOCIAL FACEBOOK

A provider extension for Spring Social to enable connectivity with Facebook and an API binding for Facebook's Graph API.

 

SPRING SOCIAL TWITTER

A provider extension for Spring Social to enable connectivity with Twitter and an API binding for Twitter's REST API.

 

SPRING SOCIAL LINKEDIN

A provider extension for Spring Social to enable connectivity with LinkedIn and an API binding for LinkedIn's REST API.



Spring Amqp

https://projects.spring.io/spring-amqp/

The Spring AMQP project applies core Spring concepts to the development of AMQP-based messaging solutions. It provides a "template" as a high-level abstraction for sending and receiving messages. It also provides support for Message-driven POJOs with a "listener container". These libraries facilitate management of AMQP resources while promoting the use of dependency injection and declarative configuration. In all of these cases, you will see similarities to the JMS support in the Spring Framework.



The project consists of two parts; spring-amqp is the base abstraction, and spring-rabbit is the RabbitMQ implementation.


Features

Listener container for asynchronous processing of inbound messages

RabbitTemplate for sending and receiving messages

RabbitAdmin for automatically declaring queues, exchanges and bindings




Spring Mobile

https://projects.spring.io/spring-mobile/

Spring Mobile is an extension to Spring MVC that aims to simplify the development of mobile web applications.


Spring Mobile is a framework that provides capabilities to detect the type of device making a request to your Spring web site and serve alternative views based on that device. Like all Spring projects, the real power of Spring Mobile is found in how easily it can be extended.


Features

A Device resolver abstraction for server-side detection of mobile and tablet devices

Site preference management that allows the user to indicate if he or she prefers a "normal", "mobile", or "tablet" experience

A site switcher capable of switching the user to the most appropriate site, either mobile, tablet, or normal, based on his or her device and optionally indicated site preference

Device aware view management for organizing and managing different views for specific devices



Spring For Android

https://projects.spring.io/spring-android/

Spring for Android is an extension of the Spring Framework that aims to simplify the development of native Android applications.


Spring for Android is a framework that is designed to provide components of the Spring family of projects for use in Android apps. Like all Spring projects, the real power of Spring for Android is found in how easily it can be extended.


Features

A Rest Client for Android

Auth support for accessing secure APIs



Spring Web Flow

https://projects.spring.io/spring-webflow/

Spring Web Flow builds on Spring MVC and allows implementing the "flows" of a web application. A flow encapsulates a sequence of steps that guide a user through the execution of some business task. It spans multiple HTTP requests, has state, deals with transactional data, is reusable, and may be dynamic and long-running in nature..



The sweet spot for Spring Web Flow are stateful web applications with controlled navigation such as checking in for a flight, applying for a loan, shopping cart checkout, or even adding a confirmation step to a form. What these scenarios have in common is one or more of the following traits:


There is a clear start and an end point.

The user must go through a set of screens in a specific order.

The changes are not finalized until the last step.

Once complete it shouldn't be possible to repeat a transaction accidentally



Spring Web Services

https://projects.spring.io/spring-ws/

Spring Web Services aims to facilitate contract-first SOAP service development, allowing for the creation of flexible web services using one of the many ways to manipulate XML payloads.


Spring Web Services (Spring-WS) is a product of the Spring community focused on creating document-driven Web services. Spring Web Services aims to facilitate contract-first SOAP service development, allowing for the creation of flexible web services using one of the many ways to manipulate XML payloads. The product is based on Spring itself, which means you can use the Spring concepts such as dependency injection as an integral part of your Web service.


People use Spring-WS for many reasons, but most are drawn to it after finding alternative SOAP stacks lacking when it comes to following Web service best practices. Spring-WS makes the best practice an easy practice. This includes practices such as the WS-I basic profile, Contract-First development, and having a loose coupling between contract and implementation. The other key features of Spring Web services are:


Features

Makes the Best Practice an Easy Practice: Spring Web Services makes enforcing best practices easier. This includes practices such as the WS-I basic profile, Contract-First development, and having a loose coupling between contract and implementation.

Powerful mappings: You can distribute incoming XML request to any object, depending on message payload, SOAP Action header, or an XPath expression.

XML API support: Incoming XML messages can be handled in standard JAXP APIs such as DOM, SAX, and StAX, but also JDOM, dom4j, XOM, or even marshalling technologies.

Flexible XML Marshalling: The Object/XML Mapping module in the Spring Web Services distribution supports JAXB 1 and 2, Castor, XMLBeans, JiBX, and XStream. And because it is a separate module, you can use it in non-Web services code as well.

Reuses your Spring expertise: Spring-WS uses Spring application contexts for all configuration, which should help Spring developers get up-to-speed nice and quickly. Also, the architecture of Spring-WS resembles that of Spring-MVC.

Supports WS-Security: WS-Security allows you to sign SOAP messages, encrypt and decrypt them, or authenticate against them.

Integrates with Acegi Security: The WS-Security implementation of Spring Web Services provides integration with Spring Security. This means you can use your existing configuration for your SOAP service as well.

Built by Maven: This assists you in effectively reusing the Spring Web Services artifacts in your own Maven-based projects.

Apache license. You can confidently use Spring-WS in your project.



Spring Ldap

https://projects.spring.io/spring-ldap/

Makes it easier to build Spring-based applications that use the Lightweight Directory Access Protocol.


Spring LDAP is a Java library for simplifying LDAP operations, based on the pattern of Spring's JdbcTemplate. The framework relieves the user of common chores, such as looking up and closing contexts, looping through results, encoding/decoding values and filters, and more.


Features

Provides LDAP template which eliminates the need to worry about creating and closing LdapContext and looping through NamingEnumeration

Comprehensive unchecked Exception hierarchy built on Spring's DataAccessException

Contains classes for dynamically building LDAP filters and Distinguished Names (DNs)

Client-side LDAP transaction management

Much more…



Spring Session

https://projects.spring.io/spring-session/

Spring Session provides an API and implementations for managing a user’s session information.


Features

Spring Session makes it trivial to support clustered sessions without being tied to an application container specific solution. It also provides transparent integration with:


HttpSession - allows replacing the HttpSession in an application container (i.e. Tomcat) neutral way, with support for providing session IDs in headers to work with RESTful APIs

WebSocket - provides the ability to keep the HttpSession alive when receiving WebSocket messages

WebSession - allows replacing the Spring WebFlux’s WebSession in an application container neutral way

Modules

Spring Session consists of the following modules:


Spring Session Core - provides core Spring Session functionalities and APIs

Spring Session Data Redis - provides SessionRepository and ReactiveSessionRepository implementation backed by Redis and configuration support

Spring Session JDBC - provides SessionRepository implementation backed by a relational database and configuration support

Spring Session Hazelcast - provides SessionRepository implementation backed by Hazelcast and configuration support




Spring Shell

https://projects.spring.io/spring-shell/

The Spring Shell project provides an interactive shell that allows you to plugin your own custom commands using a Spring based programming model.


Users of the Spring Shell project can easily build a full featured shell ( aka command line) application by depending on the Spring Shell jars and adding their own commands (which come as methods on spring beans). Creating a command line application can be useful e.g. to interact with your project's REST API, or to work with local file content.


Features

Spring Shell's features include


A simple, annotation driven, programming model to contribute custom commands

Use of Spring Boot auto-configuration functionality as the basis for a command plugin strategy

Tab completion, colorization, and script execution

Customization of command prompt, shell history file name, handling of results and errors

Dynamic enablement of commands based on domain specific criteria

Integration with the bean validation API

Already built-in commands, such as clear screen, gorgeous help, exit

ASCII art Tables, with formatting, alignment, fancy borders, etc.



Spring Flo

https://projects.spring.io/spring-flo/

Spring Flo is a JavaScript library that offers a basic embeddable HTML5 visual builder for pipelines and simple graphs. This library is used as the basis of the stream builder in Spring Cloud Data Flow.


Flo includes all the basic elements of an integration-flow designer such as connectors, control nodes, palettes, state transitions, and graph topologies—importantly, there is a textual shell, DSL support, and a graphical canvas designed for creating and reviewing comprehensive workflows.


Features

Create, manage, and monitor stream pipelines using DSL, a graphical canvas, or both

Write pipelines via DSL with content-assist and auto-complete

See a visual representation of modules across a distributed deployment

Use auto-adjustment and grid-layout capabilities in the GUI for easier and more efficient organization of pipelines



Spring Kafka

https://projects.spring.io/spring-kafka/

The Spring for Apache Kafka (spring-kafka) project applies core Spring concepts to the development of Kafka-based messaging solutions. It provides a "template" as a high-level abstraction for sending messages. It also provides support for Message-driven POJOs with @KafkaListener annotations and a "listener container". These libraries promote the use of dependency injection and declarative. In all of these cases, you will see similarities to the JMS support in the Spring Framework and RabbitMQ support in Spring AMQP.


Features

KafkaTemplate

KafkaMessageListenerContainer

@KafkaListener

KafkaTransactionManager

spring-kafka-test jar with embedded kafka server




Spring Statemachine

https://projects.spring.io/spring-statemachine/

Spring Statemachine is a framework for application developers to use state machine concepts with Spring applications.

Spring Statemachine aims to provide following features:

Easy to use flat one level state machine for simple use cases.
Hierarchical state machine structure to ease complex state configuration.
State machine regions to provide even more complex state configurations.
Usage of triggers, transitions, guards and actions.
Type safe configuration adapter.
Builder pattern for easy instantiation for use outside of Spring Application context
Recipes for usual use cases
Distributed state machine based on a Zookeeper
State machine event listeners.
UML Eclipse Papyrus modeling.
Store machine config in a persistent storage.
Spring IOC integration to associate beans with a state machine.
State machines are powerful because behaviour is always guaranteed to be consistent, making it relatively easy to debug. This is because operational rules are written in stone when the machine is started. The idea is that your application may exist in a finite number of states and certain predefined triggers can take your application from one state to the next. Such triggers can be based on either events or timers.

It is much easier to define high level logic outside of your application and then rely on the state machine to manage state. You can interact with the state machine by sending an event, listening for changes or simply request a current state.

Do you want to ask a question? Go to StackOverflow and use a tag spring-statemachine or Gitter.


앱)logback.xml sample example

Posted by HULIA(휴리아)
2018. 4. 4. 15:39 백엔드개발/자바스프링
<?xml version"1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="1 seconds">

<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
         <encoder>
                <pattern>[%d{yyyy-MM-dd HH:mm:ss.SSS}][%-5level][%logger] %msg%n</pattern>
         </endcoder>
</appender>

<appender name="SERVICE_LOG" class="ch.qos.logback.core.rolling.RollingFileAppender">
      <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
                <fileNamePattern>c:/test/service.log.%d{yyyy-MM-dd-HH}</fileNamePattern>
      </rollingPolicy>
      <encoder>
                 <pattern>[%d{yyyy-MM-dd HH:mm:ss.SSS}][%-5level][%logger] %msg%n</pattern>
      </encoder>
</appender>

<root level="INFO">
         <appender-ref ref="CONSOLE" />
         <appender-ref ref="SERVICE_LOG" />
</root>


<logger name="SERVICE_LOGGER" level="DEBUG" additivity="false">
       <appender-ref ref="CONSOLE" />
</logger>

</configuration>

앱)loggerutil 자바 common 코드

Posted by HULIA(휴리아)
2018. 4. 2. 15:29 백엔드개발/자바스프링
public static void debug(Logger logger, String msg, Object... params){
      if(logger.isDebugEnabled()){
            logger.debug(msg.params);
       }
}

public static void info(Logger logger, String msg, Object... params){
       if(logger.isInfoEnabled()){
             logger.info(msg, params);
       }
}

//같은 방식으로 warn, error추가하면 됨

앱)aesciperutil 자바 common 코드

Posted by HULIA(휴리아)
2018. 4. 2. 15:26 백엔드개발/자바스프링
static String key = "~~~~~~";


byte[] hexToByteArray(String hex){
       if( hex == null || hex.length() == 0){
     return null;
}

      byte[] ba = new byte[hex.length() / 2];
       for( int i =0 ; i<ba.length; i++){
            ba[i] = (byte) Integer.parseInt(hex.substring(2*i, 2*i+2), 16);
       }
       return ba;
}


String byteArrayToHex(byte[] ba){
      if( ba == null || ba.length == 0){
          return null;
      }
    
       StringBuffer sb = new StringBuffer(ba.length*2);
        String hexNumber;

         for( int x = 0; x<ba.length; x++){
                hexNumber = "0" + Integer.toHexString(0xff & ba[x]);
                sb.append(hexNumber.substring(hexNumber.length() - 2);
          }
          return sb.toString();
}


String encrypt(String message){
        SecretKeySpec skeySpec = new SecretKeySpec(key.getByte(), "AES");

         Cipher cipher = Cipher.getInstance("AES");
          chpher.init(Cipher.ENCRYPT_MODE, skeySpec);
    
       byte[] encrypted = cipher.doFinal(message.getByte());
       return byteArrayToHex(encrypted);
}


String decrypt(String encrypted){
        SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), "AES");
         
          Cipher cipher = Cipher.getInstance("AES");
          cipher.init(Cipher.DECRYPT_MODE, skeySpec);
          byte[] original = cipher.doFinal(hexToByteArray(encrypted));
          String originalString = new String(original);
          return originalString;
}


public static void main(String[] args){
        String enc = encrypt("~~~~~");
       

          String dec = decrypt("~~~~~");
}

앱)md5util 자바 common 코드

Posted by HULIA(휴리아)
2018. 4. 2. 15:25 백엔드개발/자바스프링
public static String getMD5Checksum(String filename){
        byte[] b  = createChecksum(fileaname);

         String result = "";
      
         for(int i=0; i<b.length; i++){
               result += Integer.toString((b[i] & 0xff) + 0x100, 16).subString(1);
         }
         return result;
}

private static byte[] createChecksum(String filename){
       InputStream fis = new FileInputStream(filename);
   
        byte[] buffer = new byte[1024];
        MessageDigest complete = MessageDigest.getInstance("MD5");

         int numRead;
         do{
               numRead = fis.read(buffer);
               if(numRead > 0){
                  complete.update(buffer, 0, numRead);
               }
           }while(numRead != -1);
        
            fis.close();
            return complete.digest();
}

앱)servletparamutil 자바 common 코드

Posted by HULIA(휴리아)
2018. 3. 30. 10:36 백엔드개발/자바스프링
String param(HttpServletRequest request, String param, String def){
         return checkParam(request.getParameter(param), def);
}


String param(HttpServletRequest request, String param){
       return param(request, param, "").trim();
}

String nonCheckParam(HttpServletRequest request, String param){
       return request.getParameter(param);
}

String checkParam(String temp, String default){
        if(temp != null){
         temp = temp.trim();
         //temp = URLDecoder.decode(temp, "UTF-8");

         Matcher m;
         /* XSS(Cross Site Scription) depend code */
          Pattern scripts = Pattern.compile("<(no)?script[^>]*>.*?</(no)?script>", Pattern.DOTALL);
          Pattern style = Pattern.compile("<style[^>]*>.*</style>", Pattern.DOTALL);
          Pattern tags = Pattern.compile("<(\"[^\"]*\"|\'[^\']*\'|[^\'\">])*>");

        m = scripts.matcher(temp);
        temp = m.replaceAll("");
         m = style.matcher(temp);
         temp = m.replaceAll("");
          m = tags.matcher(temp);
        temp = m.repaceAll("");

        //SQL Injection depend code
        Pattern sql = Pattern.compile("(\\%27)|(\\')|(\\-\\-)", Pattern.DOTALL);

         m = sql.matcher(temp);
         temp = m.replaceAll("");
         } else {
           temp = default;
         }
         return temp;
}         

앱)hashutil 자바 common 코드

Posted by HULIA(휴리아)
2018. 3. 30. 10:14 백엔드개발/자바스프링
private MessageDigest sha;

MessageDigest getSHADigest(){
      if(sha == null){
           sha = MessageDigetst.getInstance("SHA-256");
      }
      return sha;
}


synchronized String getSHA256Base64(String imei) {
       String ret = null;
       if(imei != null){
           getSHADigest();
           sha.update(imei.getBytes());
           ret = new String(Base64.encode(sha.digest()));
           sha.reset();

           return ret;
        }
        return ret;
}


boolean checkDigit(String str){
        if(isRawDigit(str)) {
            return true;
        }
        return false;
}

boolean isRawDigit(String str){
        if(str != null && !str.trim().equals("")){
             char[] chars = str.trim().toCharArray();
             for(int i =0; len=chars.length; i<len; i++){
                     if(!Character.isDigit(chars[i])){
                           return false;
                       }
                 }
        return true;
        }
        return false;
}

앱)fileutil 자바 common 코드

Posted by HULIA(휴리아)
2018. 3. 30. 10:03 백엔드개발/자바스프링
void copyFile(String sourcePath, String sourceFileName, String targetPath, String targetFileName){
       File sourceFile = new File(sourcePath, sourceFileName);
       File targetDir = new File(targetPath);
       targetDir.mkdirs();
       File targetFile = new File(targetDir, targetFileName);
       FileCopyUtils.copy(sourceFile, targetFile);
}

void moveFile(String sourcePath, String sourceFileName, String targetPath, String targetFileName){
      File sourceFile = new File(sourcePath, sourceFileName);
      File targetDir = new File(targetPath);
      targetDir.mkdirs);
      File targetFile = new File(targetDir, targetFileName);
      sourceFile.renameTo(targetFile);
}

Long getTotalSpace(String fullpath){
     File f = new File(fullpath);
      return f.length();
}


String getFileUnitSize(String sizeString){
      String[] unit = {"Byte", "KB", "MB"};
      String returnSizeString = new String();
      int unitType=0;
      double changeSize = 0;
      long sourceSize = 0;
      try {
            sourceSize = Long.parseLong(sizeString);
            for (int typeSeq = 0; (sourceSize / (double) 1024) > 0; typeSeq++, sourceSize /= (double) 1024){
             unitType = typeSeq;
             changeSize = sourceSize;
      }
      returnSizeString  = changeSize + " " + unit[unitType];
     }catch(Exception e){
         returnSizeString = "0.0 Byte";
     }

     return returnSizeString;
}


//파일에서 경로만 리턴
String getOnlyPathFromFile(String fullPath){
      return fullPath.subString(0, fullPath.lastIndexOf(File.separator));
}

//파일에서 경로만 리턴
String getOnlyPathFromFile(String fullPath, String separator) {
       return fullPAth.subString(0, fullPath.lastIndexOf(separator));
}


//파일에서 파일명만 리턴
String getOnlyFileNameFromFile(String fullPath){
      return fullPath.subString(fullPath.lastIndexOf(File.separator)+1, fullPath.length());
}

String getOnlyFileNameFromFile(String fullPath, String separator){
        return fullPath.subString(fullPath.lastIndexOf(separator)+1, fullPath.length());
}


//파일에서 파일 확장자만 리턴
String getOnlyFileExtFromFile(String fileName) {
        return fileName.subString(fileName.lastIndexOf(",")+1, fileName.length());
}


String getOnlyFileExtFromFile(String fileName, String separator){
      return fileName.subString(fileName.lastIndexOf(separator) + 1, fileName.length));
}

앱)Springframework version 버젼별 간단 특징 요약 역사

Posted by HULIA(휴리아)
2018. 2. 6. 13:46 백엔드개발/자바스프링
Springframework는 2004년에 처음 release되었음

2.0
XML namespace와 AspectJ support

2.5
annotaion 기반의 설정 방법 추가

3.0
Java5 지원
Spring Expression 지원
Java based bean metadata 지원
Type conversion and fileld formatting 지원
REST 지원
@MVC 추가
Java6 지원
Embedded 데이터베이스 지원

4.0
Java8 지원
WebSocket. SockJS, STOMP messaging 지원
Groovy Bean DSL 지원

앱)Slf4j API print format 정리 예제

Posted by HULIA(휴리아)
2018. 1. 31. 10:19 백엔드개발/자바스프링
debug, info, warn, fatal, error 모두 같은 형식을 지원하므로
 debug만 대표적으로 알아봄

slf4j.debug 메소드의 overloading 메소드 정리
debug(String arg0);
debug(Marker arg0, String arg1);
debug(String arg0, Object arg1);
debug(String arg0, Object...arg1);
debug(String arg0, Throwable arg1);
debug(Marker arg0, String arg1, Object arg2);
debug(Marker arg0, String arg1, Object...arg2);
debug(Marker arg0, String arg1, Throwable arg2);
debug(String arg0, Ojbect arg1, Obejct arg2);
debug(Marker arg0, String arg1, Object arg2, Object arg3);



Marker
Marker fatal = MarkerFactory.getMarker("FATAL");

Logger
Logger logger = LoggerFactory.getLogger("LOG");

Throwable과 Exception은 비슷
try-catch문에서 catch문에서 Exception출력을 할때 이용하거나 Exception을 throw 할때 사용


예시1)
logger.error(fatal, "Failed to obtain JDBC connection", e);

예시2)
logger.debug("Entry number: " + i + "is" + String.valueOf(entry[i]));

예시3)
Object entry = new SomeObject();//자바의 모든 객체 다 쓸 수 있음
logger.debug("The entry is {}" , entry);
//출력 : The entry is 3

예시4)
logger.debug("The new entry is {}. It replaces {}.", entry, oldEntry);
//출력 : The new entry is 3. It replaces 6.

예시5)
logger.debug("Value {} was inserted between {} and {}.", newVal, below, above);
//출력: Value 7 was inserted between 5 and 10.


예시6)
logger.debug("Set {1,2} differs from {{}}", "3");
//출력 : Set {1,2} differs from {3}


예시7)
logger.debug("Set \\{} differs from {}", "3");
//출력 : Set {} differs from 3


예시8)
logger.debug("File name is c:\\\\{}.", "file.zip");
//출력 : File name is c:\file.zip.


예시9)
String s = "hello world";
try {
Integer i = Integer.valueOf(s);
}catch(NumberFormatException e) {
 logger.error("Failed to format {}, s, e);
}


예시10)
public class LoggerUtil {
public static void debug (Logger logger,String msg,Object...params){
if (logger.isDebugEnabled ()){
logger.debug (msg,params);
}
}
}