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.net.server; 018 019 import java.io.InputStream; 020 import java.nio.charset.Charset; 021 022 import org.apache.logging.log4j.core.LogEvent; 023 import org.apache.logging.log4j.core.jackson.Log4jJsonObjectMapper; 024 025 /** 026 * Reads and logs JSON {@link LogEvent}s from an {@link InputStream}.. 027 */ 028 public class JsonInputStreamLogEventBridge extends InputStreamLogEventBridge { 029 030 private static final int[] END_PAIR = new int[] { END, END }; 031 private static final char EVENT_END_MARKER = '}'; 032 private static final char EVENT_START_MARKER = '{'; 033 private static final char JSON_ESC = '\\'; 034 private static final char JSON_STR_DELIM = '"'; 035 036 public JsonInputStreamLogEventBridge() { 037 this(1024, Charset.defaultCharset()); 038 } 039 040 public JsonInputStreamLogEventBridge(final int bufferSize, final Charset charset) { 041 super(new Log4jJsonObjectMapper(), bufferSize, charset, String.valueOf(EVENT_END_MARKER)); 042 } 043 044 @Override 045 protected int[] getEventIndices(final String text, final int beginIndex) { 046 // Scan the text for the end of the next JSON object. 047 final int start = text.indexOf(EVENT_START_MARKER, beginIndex); 048 if (start == END) { 049 return END_PAIR; 050 } 051 final char[] charArray = text.toCharArray(); 052 int stack = 0; 053 boolean inStr = false; 054 boolean inEsc = false; 055 for (int i = start; i < charArray.length; i++) { 056 final char c = charArray[i]; 057 if (!inEsc) { 058 inEsc = false; 059 switch (c) { 060 case EVENT_START_MARKER: 061 if (!inStr) { 062 stack++; 063 } 064 break; 065 case EVENT_END_MARKER: 066 if (!inStr) { 067 stack--; 068 } 069 break; 070 case JSON_STR_DELIM: 071 inStr = !inStr; 072 break; 073 case JSON_ESC: 074 inEsc = true; 075 break; 076 } 077 if (stack == 0) { 078 return new int[] { start, i }; 079 } 080 } 081 } 082 return END_PAIR; 083 } 084 085 }