Tuesday, April 28, 2020

Java Decompiler Download and How to Use

What is Java Decompiler?

There are times when you need to see the API internal implementation or to know its behavior during development, but if it's not an open source, you may feel frustrated because only the already compiled .class file exists. The Decompiler allows you to decompile back to JAVA grammar based on the compilation rules based on the byte code of the compiled .class file.

However, since the decompiler decompiles according to the compile rules, it cannot be returned exactly as the original source. However, it can be very helpful to analyze compiled sources because we show the source according to the JAVA grammar we use when developing, not byte code.

So, You can use Java Decompiler by using the jd-gui program or by installing the Decompiler plug-in from Eclipse.


Installing the JD-GUI


Install jd-gui from the link below.

http://java-decompiler.github.io/


When you run the jd-gui program, you can see the above screen. Click the folder icon in the upper left corner to view the contents of the class file.

Select the class file you want to check and click Open.

Once the file is selected and opened, the class file can be viewed as java-written content.


Installing Java Decompiler from Eclipse


Click the Eclipse top menu. Help > Eclipse Marketplace..



If you search by decompile in the Find input window in Marketplace, you will get two results as below. Here I will try to install the Enhanced Class Decompiler. Click Install.



Click Confirm.



Check I accept... to accept and click Finish.



A security-related alert appears, which appears every time the plug-in is installed, so click Install anyway.



Click Restart Now. The Eclipse is restarted to apply the plug-in.



To verify compiled sources

When the compiler plug-in is finished installing, press Ctrl + Shift + T in Eclipse to open the Open Type search pop-up and search for the java.lang.String class, which is your most popular class.






You can see that the decompiled String.class file opens.


Sunday, April 19, 2020

[Spring] Using log4j to collect logs

What is log4j?

 log4j is a library that provides log-related functions. For maintenance purposes, web applications store log files of information, such as user information that is accessed to the website or the time when a method is called, and log4j is used to collect logs.

Setting log4j

 The log4j.xml file allows you to set up settings for the log, but there are some things you need to know before you do.

log4j tag

TagsDescription
<appender>Determines the output location of the log.
<layout>Sets the format in which the log is output
<logger>Pass the logging message to the appender.

appender Class

 You can set the location and method of log collection by specifying the class properties of the appender tag.
appender Class AttributeDescription
ConsoleAppenderOutputs a log message to the console.
FileAppenderOutputs a log message to a file.
RollingFileAppenderIf the file size exceeds a certain criteria, replace the baseline file with a backup file and rewrite it from the beginning.
DailyRollingAppenderAs a class, you create a new file in a set period of time and record a log message.

 Each property has the following meaning, and the log is output formatted into the value property of the param tag in the layout tag.
AttributeDescription
%pLog level name
%mLog Message Output
%dWhen a Logging Event Occurs
%FProgram file name where logging occurred
%lInformation about the caller where logging occurred
%LNumber of lines on the caller where logging occurred
%cFull package name or full file name before logging message

 Log Level

The log level consists of a total of six steps, and the lower the table, the lower the level.
Log LevellDescription
FATALThe level to be output when the application is not operational.
ERRORIndicates the status of a problem while the application is running.
WARNIndicates a warning message that may cause future system errors.
INFOIndicates information messages related to actual application operations, such as logins and status changes.
DEBUGIndicates the message used for debugging during development.
TRACELevel introduced to output more detailed logging information than DEBUG level.
 If you set the reference level to a lower level in the log.xml file, all messages that you set above that level will be output. If set to info, all false, error, and warn level messages are output.

log4j.xml
<!-- Appenders -->
 <appender name="console" class="org.apache.log4j.ConsoleAppender">
  <param name="Target" value="System.out" />
  <layout class="org.apache.log4j.PatternLayout">
   <param name="ConversionPattern" value="%-5p: %c - %m%n" />
  </layout>
 </appender>
 
 <!-- Application Loggers -->
 <logger name="com.example.spring01">
  <level value="info" />
 </logger>
 
 <!-- 3rdparty Loggers -->
 <logger name="org.springframework.core">
  <level value="info" />
 </logger>
 
 <logger name="org.springframework.beans">
  <level value="info" />
 </logger>
 
 <logger name="org.springframework.context">
  <level value="info" />
 </logger>

 <logger name="org.springframework.web">
  <level value="info" />
 </logger>

 <!-- Root Logger -->
 <root>
  <priority value="warn" />
  <appender-ref ref="console" />
 </root>
  If you want to change the format of the log in the xml file, you can change the value property value of the param tag in the layout tag. Also, if you look at the application loggers in annotation, we set the reference log level using the logger tag.

[Spring] Using @RestController

@RestController

 The @RestController Annotation is an annotation that supports spring 4-point versions, and only @RestController is attached to the controller class to send strings, JSON, and so on without having to attach @ResponseBody Annotation to the method. Unlike @Controller, which has methods to return views, @RestController has methods to return strings, objects, etc.

Transferring strings to @RestController

example
@RestController
@RequestMapping("/main/*")
public class RestController {
 
    @RequestMapping("/hello")
    public String hello() {
     return "hello";
    }
}
If you connect to http://localhost:8080/main/hello, you can see that the string "hello" was sent.

Send command objects to @RestController

 Use JSON-related libraries because sending command objects requires transmission in the form of JSON.

pom.xml
<!--JSON-->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.5.4</version>
</dependency>

example
@RestController
@RequestMapping("/main/*")
public class RestController {
 
    @RequestMapping("/hello")
    public UserVO hello() {
    
     UserVO userVO = new userVO();
        userVO.setUserId("yunyc");
        userVO.setUserPassword("1234");
        userVO.setEmail("yunyc1024@gmail.com");
        
     return userVO;
    }
}
Paste the above code into the pom.xml file.

result
{"id":"yunyc", "password":"1234", "email":"yunyc@gmail.com"}


Send collection objects to @RestController

 As with the command object, the collection is sent in the form of JSON when the value of the collection object property is set and returned.

example
@RestController
@RequestMapping("/main/*")
public class RestController {
 
    @RequestMapping("/hello")
    public List<UserVO> hello() {
    
        List<UserVO> userList = userService.selectUserList();
     
        for (int i = 0; i < 2; i++) {
          UserVO userVO = new userVO();
          
          userVO.setUserId("yunyc");
          userVO.setUserPassword(i);
          userVO.setEmail("yunyc@gmail.com");
          
          userList.add(userVO);
        
        }
     return userList;
    }
}

result
{"id":"yunyc", "password":"0", "email":"yunyc@gmail.com"}
{"id":"yunyc", "password":"1", "email":"yunyc@gmail.com"}
{"id":"yunyc", "password":"2", "email":"yunyc@gmail.com"}

Pass map to @RestController

 The delivery method is the same as the delivery of a command object.

example
@RestController
@RequestMapping("/main/*")
public class RestController {
 
    @RequestMapping("/hello")
    public HashMap<String, Object> hello() {
    
        HashMap<String, Object> hashMap = new HashMap<String, Object>();
    
     hashMap.put("id", "yunyc");
        hashMap.put("password", "1234");
        hashMap.put("email", "yunyc@gmail.com");
        
     return hashMap;
    }
}

result
{"id":"yunyc", "password":"1234", "email":"yunyc@gmail.com"}

[Spring] Uploading files from a spring

pom.xml

 Enter the libraries required to upload the file into pom.xml.

pom.xml
<!-- Apache Commons FileUpload -->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
</dependency>
<!-- Apache Commons IO -->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>

Set Empty Object


root-context.xml
<!-- MultipartResolver 설정 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  <property name="maxUploadSize" value="100000000" />
  <property name="maxInMemorySize" value="100000000" />
</bean>
 Injects a MultipartResolver bin that allows you to receive files. With the maxUploadSize property, you can set the maximum size of the file to be uploaded, and you can set the maximum capacity that can be allowed to remain in memory with maxInMemorySize.

Jsp file

 Jsp screen to transfer files to.
example
<form action="/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file"/>
    <input type="submit" value="제출"/>
</form>
 The file transfer is sent in post format only and sets the roottype to multipart/form-data. Then enter the input tag to which you want to upload.

When using Spring Secutiry
<form:form action="/upload?${_csrf.parameterName}=${_csrf.token}" method="post" enctype="multipart/form-data">
    <input type="file" name="file"/>
    <input type="submit" value="제출"/>
</form:form>
If you are using spring security after request url, "?You must paste ${_csrf.parameterName}=${_csrf.token}" before you can request it with that url.

Controller

Method of controller file that is executed upon request from form tag.

example
@RequestMapping(value = "/upload" , method = RequestMethod.POST)
public String upload(MultipartHttpServletRequest mtf) throws Exception {
 // 파일 태그
 String fileTag = "file";
     // 업로드 파일이 저장될 경로
 String filePath = "C:\\temp\\";
 // 파일 이름 
 MultipartFile file = mtf.getFile(fileTag);
 String fileName = file.getOriginalFilename();
 // 파일 전송
 try {
     file.transferTo(new File(filePath + fileName));
 } catch(Exception e) {
     System.out.println("업로드 오류");
 }
           ...
}
 The file information sent to the form tag will be received in the form of MultipartHttpServletRequest and will be included as a method parameter. Then create a variable called fileTag to enter a value for the name property entered in the form tag. In the filePath variable, enter the path where the uploaded file will be stored. You then create a MultipartFile object to save the transferred file information and save the file name in the fileName variable by the getOrganalFilename method. Finally, the upload completes when you pass the file object with the full path of the upload file entered into the transforTo method as a parameter.

[Spring] Collecting logs with AOP

Logging can be a big help for debugging because it's easier to collect logs from specific methods that run with the AOP feature. This is because log collection makes it easy to know when the method was executed and what parameters were received.

jointPoint Interface

 Logging can be a big help for debugging because it's easier to collect logs from specific methods that run with the AOP feature. This is because log collection makes it easy to know when the method was executed and what parameters were received.

메서드설명
getSigniture()method with pointpoint applied (signature)
getSigniture().getName()Name of the method to which the pointpoint is applied
getSigniture().toLongString()Full name (output to package) of method with pointpoint applied
getSigniture().toShortString()Abbreviated name with pointpoint (only output method name)
getArgs()Parameters for method with pointpoint applied

Log processing using AOP


BoardAspect.java
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
...

@Component
@Aspect
public class BoardAspect {
 
 private static final Logger logger = LoggerFactory.getLogger(BoardAspect.class);
    
 // spring01/모든 폴더/service/이름이 ~Serviceimpl로 끝나는 클래스에 적용 
 @Around("execution(* com.example.spring01.*.service.*ServiceImpl.*(..))")
 public Object logging(ProceedingJoinPoint jp) throws Throwable {
    
        // 메서드가 실행되기 전
        logger.info("메서드 명: " + jp.getSignature().getName() + " 시작");
        logger.info("파라미터: " + Arrays.toString(jp.getArgs()));
        
        // 메서드 실행
        Object result = jointPoint.proceed();
  
        // 메서드가 실행된 후
        logger.info("메서드 명: " + jp.getSignature().getName() + " 종료");
        return result;
     }
 The AOP function specified a method for the BoardServiceImpl class that implemented the BoardService interface through an exit specifier. Before the method runs, the name is output by the getName method and the array of parameters returned by the getArgs() method is output by toString. After the method is executed, the name of the method is printed again and the method is terminated.

BoardVO
public class BoardVO {
 
    //프로퍼티 정의
    private int BoardId;
    private String BoardTitle;
            ...
    
    // getter, setter 설정
    public void setBoardId(int boardId) {
        this.BoardId = boardId;
    }
            ...
    
    @Override
    public String toString() {
        return "BoardVO [boardId=" + boardId + ", boardTitle=" + boardTitle + ", boardContent=" + boardContent
             + ", boardType=" + boardType + ", boardDate=" + boardDate + ", userId=" + userId + "]";
 }
}
 The VO object class to be passed over to the parameter of the method. Define the properties, define the getter/setters, and override the toString method as above to output the values of the properties. Automatically and easily create by pressing the Shortcut Alt + Shift + S and clicking Generate toString...

BoardController.java
@Controller
public clas BoardController {

    @Resource
    private BoardService boardService;

    @RequestMapping("/url")
    public String init(BoardVO boardVO) {
     // AOP가 적용된 selectBoardList 메서드
     List<BoardVO> homeList = homeService.selectBoardList(boardVO);
     
     return null;
    }
}
 Invoke the selectBoardList method with AOP feature on the controller. Run it and check the console window to see if any of the numerous logs defined above are printed.

결과
14:42:03.438 [http-nio-8079-exec-1] INFO com.example.project.aop.LogAspect - selectBoardList 시작
14:42:03.456 [http-nio-8079-exec-1] INFO com.example.project.aop.LogAspect - 파라미터: [Board