Java Code Examples for com.intuit.karate.FileUtils#toString()

The following examples show how to use com.intuit.karate.FileUtils#toString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Consumer.java    From karate with MIT License 7 votes vote down vote up
public Payment create(Payment payment) {
    try {
        HttpURLConnection con = getConnection("/payments");
        con.setRequestMethod("POST");
        con.setDoOutput(true);
        con.setRequestProperty("Content-Type", "application/json");
        String json = JsonUtils.toJson(payment);
        IOUtils.write(json, con.getOutputStream(), "utf-8");
        int status = con.getResponseCode();
        if (status != 200) {
            throw new RuntimeException("status code was " + status);
        }
        String content = FileUtils.toString(con.getInputStream());
        return JsonUtils.fromJson(content, Payment.class);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 2
Source File: ResponseLoggingInterceptor.java    From karate with MIT License 6 votes vote down vote up
@Override
public void process(HttpResponse response, HttpContext httpContext) throws HttpException, IOException {
    HttpRequest actual = context.getPrevRequest();
    actual.stopTimer();
    int id = requestInterceptor.getCounter().get();
    StringBuilder sb = new StringBuilder();
    sb.append("response time in milliseconds: ").append(actual.getResponseTimeFormatted()).append('\n');
    sb.append(id).append(" < ").append(response.getStatusLine().getStatusCode()).append('\n');
    HttpLogModifier responseModifier = logModifier == null ? null : logModifier.enableForUri(actual.getUri()) ? logModifier : null;
    LoggingUtils.logHeaders(responseModifier, sb, id, '<', response);
    HttpEntity entity = response.getEntity();
    if (LoggingUtils.isPrintable(entity)) {
        LoggingEntityWrapper wrapper = new LoggingEntityWrapper(entity);
        String buffer = FileUtils.toString(wrapper.getContent());
        if (context.getConfig().isLogPrettyResponse()) {
            buffer = FileUtils.toPrettyString(buffer);
        }
        if (responseModifier != null) {
            buffer = responseModifier.response(actual.getUri(), buffer);
        }
        sb.append(buffer).append('\n');
        response.setEntity(wrapper);
    }
    context.logger.debug(sb.toString());
}
 
Example 3
Source File: ConvertUtilsTest.java    From karate with MIT License 6 votes vote down vote up
@Test
public void testReadingSinglePostmanItemWithOneRequest() {
    InputStream is = getClass().getResourceAsStream("postman-echo-single.postman_collection");
    String json = FileUtils.toString(is);
    List<PostmanItem> items = PostmanUtils.readPostmanJson(json);
    logger.debug("list: {}", items);
    assertEquals(1, items.size());
    PostmanItem item = items.get(0);
    PostmanRequest request = item.getRequest();
    assertEquals("OAuth1.0 Verify Signature", item.getName());
    assertEquals("https://echo.getpostman.com/oauth1", request.getUrl());
    assertEquals("GET", request.getMethod());
    assertEquals(1, request.getHeaders().size());
    assertEquals("OAuth oauth_consumer_key=\"RKCGzna7bv9YD57c\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"1442394747\",oauth_nonce=\"UIGipk\",oauth_version=\"1.0\",oauth_signature=\"CaeyGPr2mns1WCq4Cpm5aLvz6Gs=\"", request.getHeaders().get("Authorization"));
    logger.debug(request.getBody());
}
 
Example 4
Source File: ConvertUtilsTest.java    From karate with MIT License 6 votes vote down vote up
@Test
public void testReadingItemListWithSubItems() {
    String collectionFileName = "postman-multiple-items-and-sub-items.postman_collection";
    InputStream is = getClass().getResourceAsStream(collectionFileName);
    String json = FileUtils.toString(is);
    List<PostmanItem> items = PostmanUtils.readPostmanJson(json);
    logger.debug("list: {}", items);
    String featureJson = PostmanUtils.toKarateFeature(collectionFileName, items).trim();
    assertTrue(featureJson.startsWith("Feature: " + collectionFileName)); // assert feature name
    assertTrue(featureJson.contains("Scenario: rootItem-1")); // assert scenario names
    assertTrue(featureJson.contains("Scenario: rootItem-2"));
    assertTrue(featureJson.contains("Scenario: rootItem-3"));
    assertTrue(featureJson.contains("# subitem-1-1")); // assert comment for each sub request
    assertTrue(featureJson.contains("# subitem-1-2"));
    assertTrue(featureJson.contains("# subitem-2-1"));
}
 
Example 5
Source File: RequestBuilderTest.java    From karate with MIT License 6 votes vote down vote up
@Test
public void testConverting() {
    InputStream is = getClass().getResourceAsStream("postman-echo-single.postman_collection");
    String json = FileUtils.toString(is);
    List<PostmanItem> items = PostmanUtils.readPostmanJson(json);
    logger.debug("list: {}", items);
    assertEquals(1, items.size());
    PostmanItem item = items.get(0);
    PostmanRequest request = item.getRequest();
    RequestBuilder builder = new RequestBuilder();
    assertEquals("OAuth1.0 Verify Signature", item.getName().trim());
    builder.addUrl(request.getUrl());
    assertEquals("'https://echo.getpostman.com/oauth1'", builder.getUrl().trim());
    builder.addHeaders(request.getHeaders());
    String authorizationValue = "OAuth oauth_consumer_key=\"RKCGzna7bv9YD57c\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"1442394747\",oauth_nonce=\"UIGipk\",oauth_version=\"1.0\",oauth_signature=\"CaeyGPr2mns1WCq4Cpm5aLvz6Gs=\"";
    assertEquals("And header Authorization = '"+ authorizationValue + "'", builder.getHeaders().trim());
    builder.addMethod(request.getMethod());
    assertEquals("GET", builder.getMethod().trim());
    builder.addBody(request.getBody());
    logger.debug(builder.getBody());
}
 
Example 6
Source File: RequestLoggingInterceptor.java    From karate with MIT License 5 votes vote down vote up
@Override
public void process(org.apache.http.HttpRequest request, HttpContext httpContext) throws HttpException, IOException {
    HttpRequest actual = new HttpRequest();
    int id = counter.incrementAndGet();
    String uri = (String) httpContext.getAttribute(ApacheHttpClient.URI_CONTEXT_KEY);
    String method = request.getRequestLine().getMethod();
    actual.setUri(uri);
    actual.setMethod(method);        
    StringBuilder sb = new StringBuilder();
    sb.append("request:\n").append(id).append(" > ").append(method).append(' ').append(uri).append('\n');
    HttpLogModifier requestModifier = logModifier == null ? null : logModifier.enableForUri(uri) ? logModifier : null;
    LoggingUtils.logHeaders(requestModifier, sb, id, '>', request, actual);
    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request;
        HttpEntity entity = entityRequest.getEntity();
        if (LoggingUtils.isPrintable(entity)) {
            LoggingEntityWrapper wrapper = new LoggingEntityWrapper(entity); // todo optimize, preserve if stream
            String buffer = FileUtils.toString(wrapper.getContent());
            if (context.getConfig().isLogPrettyRequest()) {
                buffer = FileUtils.toPrettyString(buffer);
            }
            if (requestModifier != null) {
                buffer = requestModifier.request(uri, buffer);
            }
            sb.append(buffer).append('\n');
            actual.setBody(wrapper.getBytes());
            entityRequest.setEntity(wrapper);
        }
    }
    context.setPrevRequest(actual);
    context.logger.debug(sb.toString());
    actual.startTimer();
}
 
Example 7
Source File: ScenarioJobServer.java    From karate with MIT License 5 votes vote down vote up
@Override
public void handleUpload(File upload, String executorId, String chunkId) {
    File jsonFile = getFirstFileWithExtension(upload, "json");
    if (jsonFile == null) {
        return;
    }
    String json = FileUtils.toString(jsonFile);
    File videoFile = getFirstFileWithExtension(upload, "mp4");
    List<Map<String, Object>> list = JsonUtils.toJsonDoc(json).read("$[0].elements");
    synchronized (CHUNK_RESULTS) {
        ChunkResult cr = CHUNK_RESULTS.remove(chunkId);
        LOGGER.info("chunk complete: {}, remaining: {}", chunkId, CHUNK_RESULTS.keySet());
        if (cr == null) {
            LOGGER.error("could not find chunk: {}", chunkId);
            return;
        }
        ScenarioResult sr = new ScenarioResult(cr.scenario, list, true);
        sr.setStartTime(cr.getStartTime());
        sr.setEndTime(System.currentTimeMillis());
        sr.setThreadName(executorId);
        cr.setResult(sr);
        if (videoFile != null) {
            File dest = new File(FileUtils.getBuildDir()
                    + File.separator + "cucumber-html-reports" + File.separator + chunkId + ".mp4");
            FileUtils.copy(videoFile, dest);
            sr.appendEmbed(Embed.forVideoFile(dest.getName()));
        }
        if (cr.parent.isComplete()) {
            LOGGER.info("feature complete, calling onComplete(): {}", cr.parent);
            cr.parent.onComplete();
        }
    }
}
 
Example 8
Source File: HttpUtils.java    From karate with MIT License 5 votes vote down vote up
public static String multiPartToString(List<MultiPartItem> items, String boundary) {
    StringBuilder sb = new StringBuilder();
    boolean firstItem = true;
    for (MultiPartItem item : items) {
        if (firstItem) {
            firstItem = false;
            sb.append("--");
        } else {
            sb.append("\r\n--");
        }
        sb.append(boundary);
        sb.append("\r\n");
        ScriptValue sv = item.getValue();
        String contentType = getContentType(sv);
        sb.append("Content-Type: ").append(contentType);
        sb.append("\r\n");
        String name = item.getName();
        if (name != null) {
            sb.append("Content-Disposition: form-data");
            if (item.getFilename() != null) {
                sb.append("; filename=\"").append(item.getFilename()).append("\"");
            }
            sb.append("; name=\"").append(name).append("\"");
            sb.append("\r\n");
        }
        sb.append("\r\n");
        if (sv.getType() == Type.INPUT_STREAM) {
            InputStream is = sv.getValue(InputStream.class);
            String bytes = FileUtils.toString(is);
            sb.append(bytes);
        } else {
            sb.append(sv.getAsString());
        }
    }
    sb.append("\r\n--");
    sb.append(boundary);
    sb.append("--\r\n");
    return sb.toString();
}
 
Example 9
Source File: FileLogAppender.java    From karate with MIT License 5 votes vote down vote up
@Override
public String collect() {
    try {
        int pos = (int) channel.position();
        ByteBuffer buf = ByteBuffer.allocate(pos - prevPos);
        channel.read(buf, prevPos);
        prevPos = pos;
        ((Buffer) buf).flip(); // java 8 to 9 fix
        return FileUtils.toString(buf.array());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 10
Source File: ScenarioResultTest.java    From karate with MIT License 5 votes vote down vote up
@Test
public void testJsonToScenarioResult() {
    String json = FileUtils.toString(getClass().getResourceAsStream("simple1.json"));
    List<Map<String, Object>> list = JsonUtils.toJsonDoc(json).read("$[0].elements");
    Feature feature = FeatureParser.parse("classpath:com/intuit/karate/core/simple1.feature");
    Scenario scenario = feature.getSections().get(0).getScenario();
    ScenarioResult sr = new ScenarioResult(scenario, list, true);
    Match.init(list.get(0)).equalsObject(sr.backgroundToMap());
    Match.init(list.get(1)).equalsObject(sr.toMap());
}
 
Example 11
Source File: ScriptBridge.java    From karate with MIT License 5 votes vote down vote up
public String exec(String command) {
    Runtime runtime = Runtime.getRuntime();
    try {
        InputStream is = runtime.exec(command).getInputStream();
        return FileUtils.toString(is);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 12
Source File: PostmanConverterTest.java    From karate with MIT License 5 votes vote down vote up
@Test
public void testSuccess() throws IOException {
    if (FileUtils.isOsWindows()) { // TODO
        return;
    }
    // create the temp file and dirctory
    File tempSource = File.createTempFile("karate-postman-input", ".postman_collection.json");
    tempSource.deleteOnExit();
    Path tempOutput = Files.createTempDirectory("karate-postman-output");
    tempOutput.toFile().deleteOnExit();

    // populate the temp source file with the Postman export data
    InputStream is = getClass().getResourceAsStream("postman-echo-single.postman_collection");
    String postman = FileUtils.toString(is);
    Files.write(Paths.get(tempSource.toURI()), postman.getBytes());

    // perform the conversion
    boolean successful = new PostmanConverter().convert(tempSource.toString(), tempOutput.toString());
    Assert.assertTrue(successful);

    // load the expected output from the resources
    is = getClass().getResourceAsStream("expected-converted.txt");
    String expectedConverted = FileUtils.toString(is);

    // load the actual output form the disk
    Path actualOutputPath = Paths.get(tempOutput.toString(),
        tempSource.getName().replace(".postman_collection.json", "") + ".feature");
    String converted = new String(Files.readAllBytes(actualOutputPath), StandardCharsets.UTF_8);

    // the first line is dynamic, as it contains the temp dir characters
    Assert.assertTrue(converted.startsWith("Feature: karate-postman-input"));

    // trim the file so it doesn't contain the line starting with 'Feature':
    String convertedTrimmed = Arrays.stream(converted.split(System.lineSeparator()))
        .filter(line -> !line.startsWith("Feature:"))
        .collect(Collectors.joining(System.lineSeparator()));

    // assert that the trimmed actual output equals the trimmed expected output
    Assert.assertEquals(convertedTrimmed.trim(), expectedConverted.trim());
}
 
Example 13
Source File: FeatureReuseTest.java    From karate with MIT License 4 votes vote down vote up
private static String resultXml(String name) {
    Feature feature = FeatureParser.parse("classpath:com/intuit/karate/core/" + name);
    FeatureResult result = Engine.executeFeatureSync(null, feature, null, null);
    File file = Engine.saveResultXml("target", result, null);
    return FileUtils.toString(file);        
}
 
Example 14
Source File: FeatureEditTest.java    From karate with MIT License 4 votes vote down vote up
private Feature parse(String name) {
    InputStream is = getClass().getResourceAsStream(name);
    String text = FileUtils.toString(is);
    Resource resource = Resource.EMPTY;
    return FeatureParser.parseText(new Feature(resource), text);
}
 
Example 15
Source File: FeatureResultTest.java    From karate with MIT License 4 votes vote down vote up
private static String xml(FeatureResult result) {
    File file = Engine.saveResultXml("target", result, null);
    return FileUtils.toString(file);           
}
 
Example 16
Source File: Engine.java    From karate with MIT License 4 votes vote down vote up
public static String getClasspathResource(String name) {
    return FileUtils.toString(Engine.class.getClassLoader().getResourceAsStream(name));
}
 
Example 17
Source File: Embed.java    From karate with MIT License 4 votes vote down vote up
public String getAsString() {
    return FileUtils.toString(bytes);
}
 
Example 18
Source File: TestLogAppender.java    From karate with MIT License 4 votes vote down vote up
@Override
protected void append(ILoggingEvent event) {
    byte[] bytes = encoder.encode(event);
    String line = FileUtils.toString(bytes);
    sb.append(line).append('\n');
}