blob: 2396dd34a2a02b17efe2978c71f4f6deb47ebce3 [file] [log] [blame]
Paul Duffin7fc0b452015-11-10 17:45:15 +00001/*
2 * Copyright (C) 2010 Google Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.google.caliper;
18
19import com.google.gson.JsonParseException;
20
21import java.io.ByteArrayInputStream;
22import java.io.ByteArrayOutputStream;
23import java.io.IOException;
24import java.io.InputStream;
25import java.io.InputStreamReader;
26
27/**
28 * Helps with deserialization of results, given uncertainty about the format (xml or json) they
29 * are in.
30 */
31public final class ResultsReader {
32 public Result getResult(InputStream in) throws IOException {
33 // save input into a byte array since we may need to read it twice
34 byte[] postedData = readAllBytes(in);
35 Result result;
36 InputStreamReader baisJsonReader = new InputStreamReader(new ByteArrayInputStream(postedData));
37 try {
38 result = Json.getGsonInstance().fromJson(baisJsonReader, Result.class);
39 } catch (JsonParseException e) {
40 // probably an old client is trying to send data, so try to parse it as XML instead.
41 ByteArrayInputStream baisXml = new ByteArrayInputStream(postedData);
42 try {
43 result = Xml.resultFromXml(baisXml);
44 } catch (Exception e2) {
45 throw new RuntimeException(e);
46 } finally {
47 baisXml.close();
48 }
49 } finally {
50 baisJsonReader.close();
51 }
52 return result;
53 }
54
55 private byte[] readAllBytes(InputStream in) throws IOException {
56 ByteArrayOutputStream baos = new ByteArrayOutputStream();
57 byte[] buf = new byte[4096];
58 int read;
59 while ((read = in.read(buf)) != -1) {
60 baos.write(buf, 0, read);
61 }
62 return baos.toByteArray();
63 }
64}