001package org.hl7.fhir.r5.context;
002
003/*-
004 * #%L
005 * org.hl7.fhir.r5
006 * %%
007 * Copyright (C) 2014 - 2019 Health Level 7
008 * %%
009 * Licensed under the Apache License, Version 2.0 (the "License");
010 * you may not use this file except in compliance with the License.
011 * You may obtain a copy of the License at
012 * 
013 *      http://www.apache.org/licenses/LICENSE-2.0
014 * 
015 * Unless required by applicable law or agreed to in writing, software
016 * distributed under the License is distributed on an "AS IS" BASIS,
017 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
018 * See the License for the specific language governing permissions and
019 * limitations under the License.
020 * #L%
021 */
022
023
024import java.io.FileNotFoundException;
025import java.io.FileOutputStream;
026import java.io.PrintStream;
027import java.io.UnsupportedEncodingException;
028import java.util.List;
029
030import org.hl7.fhir.r5.utils.client.ToolingClientLogger;
031import org.hl7.fhir.utilities.Utilities;
032
033public class TextClientLogger implements ToolingClientLogger {
034
035  private PrintStream file;
036  private int id = 0;
037  private String lastId;
038  
039  public TextClientLogger(String log) {
040    if (log != null) {
041      try {
042        file = new PrintStream(new FileOutputStream(log));
043      } catch (FileNotFoundException e) {
044      }
045    }
046  }
047
048  @Override
049  public void logRequest(String method, String url, List<String> headers, byte[] body) {
050    if (file == null)
051      return;
052    id++;
053    lastId = Integer.toString(id);
054    file.println("\r\n--- "+lastId+" -----------------\r\nRequest: \r\n");
055    file.println(method+" "+url+" HTTP/1.0");
056    for (String s : headers)  
057      file.println(Utilities.escapeXml(s));
058    if (body != null) {
059      file.println("");
060      try {
061        file.println(Utilities.escapeXml(new String(body, "UTF-8")));
062      } catch (UnsupportedEncodingException e) {
063      }
064    }
065  }
066
067  @Override
068  public void logResponse(String outcome, List<String> headers, byte[] body) {
069    if (file == null)
070      return;
071    file.println("\r\n\r\nResponse: \r\n");
072    file.println(outcome);
073    for (String s : headers)  
074      file.println(Utilities.escapeXml(s));
075    if (body != null) {
076      file.println("");
077      try {
078        file.println(Utilities.escapeXml(new String(body, "UTF-8")));
079      } catch (UnsupportedEncodingException e) {
080      }
081    }
082  }
083
084  public String getLastId() {
085    return lastId;
086  }
087
088  public void clearLastId() {
089    lastId = null;    
090  }
091
092}