001 /* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache license, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the license for the specific language governing permissions and 015 * limitations under the license. 016 */ 017 package org.apache.logging.log4j.core.appender.db.jpa.converter; 018 019 import javax.persistence.AttributeConverter; 020 021 /** 022 * A JPA 2.1 attribute converter for {@link StackTraceElement}s in {@link org.apache.logging.log4j.core.LogEvent}s. This 023 * converter is capable of converting both to and from {@link String}s. 024 */ 025 public class StackTraceElementAttributeConverter implements AttributeConverter<StackTraceElement, String> { 026 private static final int UNKNOWN_SOURCE = -1; 027 028 private static final int NATIVE_METHOD = -2; 029 030 @Override 031 public String convertToDatabaseColumn(final StackTraceElement element) { 032 return element.toString(); 033 } 034 035 @Override 036 public StackTraceElement convertToEntityAttribute(final String s) { 037 return StackTraceElementAttributeConverter.convertString(s); 038 } 039 040 static StackTraceElement convertString(final String s) { 041 int open = s.indexOf("("); 042 043 String classMethod = s.substring(0, open); 044 String className = classMethod.substring(0, classMethod.lastIndexOf(".")); 045 String methodName = classMethod.substring(classMethod.lastIndexOf(".") + 1); 046 047 String parenthesisContents = s.substring(open + 1, s.indexOf(")")); 048 049 String fileName = null; 050 int lineNumber = UNKNOWN_SOURCE; 051 if ("Native Method".equals(parenthesisContents)) { 052 lineNumber = NATIVE_METHOD; 053 } else if (!"Unknown Source".equals(parenthesisContents)) { 054 int colon = parenthesisContents.indexOf(":"); 055 if (colon > UNKNOWN_SOURCE) { 056 fileName = parenthesisContents.substring(0, colon); 057 try { 058 lineNumber = Integer.parseInt(parenthesisContents.substring(colon + 1)); 059 } catch (NumberFormatException ignore) { 060 // we don't care 061 } 062 } else { 063 fileName = parenthesisContents.substring(0); 064 } 065 } 066 067 return new StackTraceElement(className, methodName, fileName, lineNumber); 068 } 069 }