Esempio n. 1
0
  private void doTest(String prefix) throws IOException {
    int n = 0;
    int failed = 0;
    for (String name : myMap.keySet()) {
      if (prefix == null && name.contains("/")) {
        continue;
      }
      if (prefix != null && !name.startsWith(prefix)) {
        continue;
      }
      System.out.print("filename = " + name);
      n++;

      final MainParseTest.Test test = myMap.get(name);
      try {
        myFixture.testHighlighting(test.showWarnings, true, test.showInfo, name);

        if (test.expectedResult == Result.ERR) {
          System.out.println(
              "  FAILED. Expression incorrectly parsed OK: "
                  + FileUtil.loadFile(new File(getTestDataPath(), name)));
          failed++;
        } else {
          System.out.println("  OK");
        }
      } catch (Throwable e) {
        if (test.expectedResult == Result.ERR) {
          System.out.println("  OK");
        } else {
          e.printStackTrace();
          System.out.println(
              "  FAILED. Expression = " + FileUtil.loadFile(new File(getTestDataPath(), name)));
          if (myOut.size() > 0) {
            String line;
            final BufferedReader reader = new BufferedReader(new StringReader(myOut.toString()));
            do {
              line = reader.readLine();
            } while (line != null && (line.trim().length() == 0 || line.trim().equals("ERROR:")));
            if (line != null) {
              if (line.matches(".*java.lang.Error: junit.framework.AssertionFailedError:.*")) {
                System.out.println(
                    "ERROR: "
                        + line.replace(
                            "java.lang.Error: junit.framework.AssertionFailedError:", ""));
              }
            } else {
              System.out.println("ERROR: " + myOut.toString());
            }
          }
          failed++;
        }
      }
      myOut.reset();
    }

    System.out.println("");
    System.out.println(n + " Tests executed, " + failed + " failed");

    assertFalse(failed > 0);
  }
Esempio n. 2
0
    public String toString() {
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      PrintStream ps = new PrintStream(baos);

      System.out.printf("START CLASSLITERALS%n");
      System.out.printf("%nCLASSNAME%n%s%n%nLITERALS%n", classname);
      for (int x : ints) {
        System.out.printf("int:%d%n", x);
      }
      for (long x : longs) {
        System.out.printf("long:%d%n", x);
      }
      for (float x : floats) {
        System.out.printf("float:%g%n", x);
      }
      for (double x : doubles) {
        System.out.printf("double:%g%n", x);
      }
      for (String x : strings) {
        System.out.printf("String:\"%s\"%n", x);
      }
      for (Class<?> x : classes) {
        System.out.printf("Class:%s%n", x);
      }
      System.out.printf("%nEND CLASSLITERALS%n", classname);

      return baos.toString();
    }
Esempio n. 3
0
  public void testSendMail() throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream(128);
    String responses = "220\n250\n250\n250\n354\n250\n";
    ByteArrayInputStream bais = new ByteArrayInputStream(responses.getBytes());
    BufferedReader rdr = new BufferedReader(new InputStreamReader(bais));
    mailer.useTestStreams(new PrintWriter(baos), rdr);

    assertTrue(
        mailer.doSMTP(
            "*****@*****.**",
            "*****@*****.**",
            "test subject",
            "test message",
            "testHost",
            25,
            "localName"));
    String expectedMessage =
        "HELO localName\r\n"
            + "MAIL FROM: <*****@*****.**>\r\n"
            + "RCPT TO: <*****@*****.**>\r\n"
            + "DATA\r\n"
            + "From: [email protected]\r\n"
            + "To: [email protected]\r\n"
            + "Subject: test subject\r\n"
            + "X-Mailer: Smtp Mailer\r\n"
            + "\r\n"
            + "test message\r\n"
            + ".\r\n"
            + "QUIT\r\n";
    assertEquals(expectedMessage, baos.toString());
  }
Esempio n. 4
0
  /**
   * Sends a single zip file
   *
   * @param zipFile Name of the zip file in the data directory.
   * @throws IOException
   */
  private void sendZipfile(String zipFile) throws IOException {
    logger.debug("Sending {}", zipFile);
    HttpPost post = new HttpPost(m_remoteUrl + "/api/v1/datapoints");

    File zipFileObj = new File(m_dataDirectory, zipFile);
    FileInputStream zipStream = new FileInputStream(zipFileObj);
    post.setHeader("Content-Type", "application/gzip");

    post.setEntity(new InputStreamEntity(zipStream, zipFileObj.length()));
    try (CloseableHttpResponse response = m_client.execute(post)) {

      zipStream.close();
      if (response.getStatusLine().getStatusCode() == 204) {
        zipFileObj.delete();
      } else {
        ByteArrayOutputStream body = new ByteArrayOutputStream();
        response.getEntity().writeTo(body);
        logger.error(
            "Unable to send file "
                + zipFile
                + ": "
                + response.getStatusLine()
                + " - "
                + body.toString("UTF-8"));
      }
    }
  }
Esempio n. 5
0
 /**
  * POSTs the variables and returns the body
  *
  * @param url - fully qualified and encoded URL to post to
  * @param params
  * @return
  */
 public String doPost(String url, Map<String, String> params)
     throws com.ettrema.httpclient.HttpException, NotAuthorizedException, ConflictException,
         BadRequestException, NotFoundException {
   notifyStartRequest();
   HttpPost m = new HttpPost(url);
   List<NameValuePair> formparams = new ArrayList<NameValuePair>();
   for (Entry<String, String> entry : params.entrySet()) {
     formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
   }
   UrlEncodedFormEntity entity;
   try {
     entity = new UrlEncodedFormEntity(formparams);
   } catch (UnsupportedEncodingException ex) {
     throw new RuntimeException(ex);
   }
   m.setEntity(entity);
   try {
     ByteArrayOutputStream bout = new ByteArrayOutputStream();
     int res = Utils.executeHttpWithStatus(client, m, bout);
     Utils.processResultCode(res, url);
     return bout.toString();
   } catch (HttpException ex) {
     throw new RuntimeException(ex);
   } catch (IOException ex) {
     throw new RuntimeException(ex);
   } finally {
     notifyFinishRequest();
   }
 }
Esempio n. 6
0
  private void runInProcess(
      CompileContext compileContext, VirtualFile outputDir, File kotlinHome, File scriptFile) {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PrintStream out = new PrintStream(outputStream);

    int rc = execInProcess(kotlinHome, outputDir, scriptFile, out, compileContext);

    ProcessAdapter listener = createProcessListener(compileContext);

    BufferedReader reader = new BufferedReader(new StringReader(outputStream.toString()));
    while (true) {
      try {
        String line = reader.readLine();
        if (line == null) break;
        listener.onTextAvailable(
            new ProcessEvent(NullProcessHandler.INSTANCE, line + "\n"), ProcessOutputTypes.STDERR);
      } catch (IOException e) {
        // Can't be
        throw new IllegalStateException(e);
      }
    }

    ProcessEvent termintationEvent = new ProcessEvent(NullProcessHandler.INSTANCE, rc);
    listener.processWillTerminate(termintationEvent, false);
    listener.processTerminated(termintationEvent);
  }
Esempio n. 7
0
  public static String RenderTemplatePage(Bindings b, String templateName) throws IOException {

    MediaType mt = MediaType.TEXT_HTML;
    Resource config = model.createResource("eh:/root");
    Mode prefixMode = Mode.PreferPrefixes;
    ShortnameService sns = new StandardShortnameService();

    List<Resource> noResults = CollectionUtils.list(root.inModel(model));
    Graph resultGraph = graphModel.getGraph();

    resultGraph.getPrefixMapping().setNsPrefix("api", API.NS);
    resultGraph.add(Triple.create(root.asNode(), API.items.asNode(), RDF.nil.asNode()));

    APIResultSet rs = new APIResultSet(resultGraph, noResults, true, true, "details", View.ALL);
    VelocityRenderer vr = new VelocityRenderer(mt, null, config, prefixMode, sns);

    VelocityRendering vx = new VelocityRendering(b, rs, vr);

    VelocityEngine ve = vx.createVelocityEngine();
    VelocityContext vc = vx.createVelocityContext(b);

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    Writer w = new OutputStreamWriter(bos, "UTF-8");
    Template t = ve.getTemplate(templateName);

    t.merge(vc, w);
    w.close();

    return bos.toString();
  }
Esempio n. 8
0
 private static String formatException(Throwable e) {
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   PrintStream ps = new PrintStream(baos);
   e.printStackTrace(ps);
   ps.close();
   return baos.toString();
 }
Esempio n. 9
0
 @Test
 public void shouldBeInformedToGetLibrarianWhenCheckLibraryNumber() {
   in = new ByteArrayInputStream(CHECK.getBytes());
   Bilioteca bilioteca = new Bilioteca(null);
   bilioteca.getMenu().selectMenu(in);
   assertEquals("Please talk to librarian. Thank you.\n", out.toString());
 }
Esempio n. 10
0
  public static String xmlToJson(String xml, boolean formatted) throws XMLStreamException {
    InputStream input = new ByteArrayInputStream(xml.getBytes());
    ByteArrayOutputStream output = new ByteArrayOutputStream();

    JsonXMLConfig config =
        new JsonXMLConfigBuilder()
            .autoArray(true)
            .autoPrimitive(true)
            .prettyPrint(formatted)
            .build();

    try {
      XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(input);
      XMLEventWriter writer = new JsonXMLOutputFactory(config).createXMLEventWriter(output);
      writer.add(reader);
      reader.close();
      writer.close();
      try {
        return output.toString("UTF-8");
      } catch (UnsupportedEncodingException e) {
        throw new XMLStreamException(e.getMessage());
      }
    } finally {
      // dp nothing
    }
  }
Esempio n. 11
0
  void run() throws Exception {
    File classesDir = new File("classes");
    classesDir.mkdirs();
    writeFile(baseFile, baseText);
    String[] javacArgs = {"-d", classesDir.getPath(), baseFile.getPath()};
    com.sun.tools.javac.Main.compile(javacArgs);

    writeFile(srcFile, srcText);
    String[] args = {
      "-d", "api", "-classpath", classesDir.getPath(), "-package", "p", srcFile.getPath()
    };

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintStream ps = new PrintStream(baos);
    PrintStream prev = System.err;
    System.setErr(ps);
    try {
      int rc = com.sun.tools.javadoc.Main.execute(args);
    } finally {
      System.err.flush();
      System.setErr(prev);
    }
    String out = baos.toString();
    System.out.println(out);

    String errorMessage = "java.lang.IllegalArgumentException: <clinit>";
    if (out.contains(errorMessage)) throw new Exception("error message found: " + errorMessage);
  }
Esempio n. 12
0
  // callRestfulApi - Calls restful API and returns results as a string
  public String callRestfulApi(
      String addr, HttpServletRequest request, HttpServletResponse response) {
    if (localCookie) CookieHandler.setDefault(cm);

    try {
      ByteArrayOutputStream output = new ByteArrayOutputStream();
      URL url = new URL(API_ROOT + addr);
      URLConnection urlConnection = url.openConnection();
      String cookieVal = getBrowserInfiniteCookie(request);
      if (cookieVal != null) {
        urlConnection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal);
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setRequestProperty("Accept-Charset", "UTF-8");
      }
      IOUtils.copy(urlConnection.getInputStream(), output);
      String newCookie = getConnectionInfiniteCookie(urlConnection);
      if (newCookie != null && response != null) {
        setBrowserInfiniteCookie(response, newCookie, request.getServerPort());
      }
      return output.toString();
    } catch (IOException e) {
      System.out.println(e.getMessage());
      return null;
    }
  } // TESTED
Esempio n. 13
0
 @Test
 public void shouldGetResponseWhenIInputInvalidSelection() {
   in = new ByteArrayInputStream(INVALID.getBytes());
   Bilioteca bilioteca = new Bilioteca(in);
   bilioteca.getMenu().selectMenu(in);
   assertEquals("Select a valid option!!\n", out.toString());
 }
  /**
   * Test method for {@link
   * org.alfresco.deployment.transformers.EncryptionTransformer#addFilter(java.io.OutputStream,
   * org.alfresco.deployment.DeploymentTransportTransformer.Direction, java.lang.String)}. This test
   * compresses a message with one transformation. Then sends the results through another instance
   * to give us plain text again.
   */
  public void testAddFilter() {
    SampleEncryptionTransformer transformer = new SampleEncryptionTransformer();
    transformer.setPassword("Welcome To Hades");
    transformer.setCipherName("PBEWithMD5AndDES");

    String path = "wibble";

    ByteArrayOutputStream compressed = new ByteArrayOutputStream();

    // A sender should encrypt the stream
    OutputStream out = null;
    // out = (OutputStream)transformer.addFilter(compressed, Direction.SENDER, path);
    out = (OutputStream) transformer.addFilter(compressed, path, null, null);

    assertNotNull("null output stream returned", compressed);

    String clearText = "hello world";

    try {
      out.write(clearText.getBytes());
    } catch (IOException ie) {
      fail("unexpected exception thrown" + ie.toString());
    }

    try {
      out.flush();
      out.close();
    } catch (IOException ie) {
      fail("unexpected exception thrown, " + ie.toString());
    }

    assert (compressed.size() > 0);

    // Now set up another instance to decrypt the message
    InputStream decompress = null;

    ByteArrayInputStream compressedStream = new ByteArrayInputStream(compressed.toByteArray());

    ByteArrayOutputStream result = new ByteArrayOutputStream();

    decompress = (InputStream) transformer.addFilter(compressedStream, "wibble", null, null);

    try {
      byte[] readBuffer = new byte[1002];
      while (true) {
        int readLen = decompress.read(readBuffer);
        if (readLen > 0) {
          result.write(readBuffer, 0, readLen);
        } else {
          break;
        }
      }

    } catch (IOException ie) {
      fail("unexpected exception thrown, " + ie.toString());
    }

    // now uncompress should equal clearText
    assertTrue(result.toString().equalsIgnoreCase(clearText));
  }
Esempio n. 15
0
  // Test the change plan when trying to change a student plan
  @Test
  public void transferpairtest() {
    Backend b = new Backend();
    String[] args = new String[1];
    args[0] = "MasterBankAccounts.txt";

    tlist.clear();

    Transaction t = new Transaction();
    t.setCode("10");
    t.setMisc("A");
    t.setName("");

    Transaction t2 = new Transaction();
    t2.setCode("02");
    t2.setNum("00005");

    Transaction t3 = new Transaction();
    t3.setCode("00");

    tlist.add(t);
    tlist.add(t2);
    tlist.add(t3);

    b.load(args);
    b.setTransactions(tlist);
    b.handletransactions();
    assertEquals("Transfer transactions must come in pairs\n", outContent.toString());
  }
Esempio n. 16
0
  public static String postXml(String url, String xmlData) {
    HttpPost post = new HttpPost(url);
    InputStream is = null;
    ByteArrayOutputStream baos = null;
    try {
      StringEntity entity = new StringEntity(xmlData);
      post.setEntity(entity);
      post.setHeader("Content-Type", "text/xml;charset=UTF-8");

      HttpResponse response = httpClient.execute(post);
      is = response.getEntity().getContent();
      baos = new ByteArrayOutputStream();
      byte[] data = new byte[1024];
      int count = is.read(data);
      while (count != -1) {
        baos.write(data, 0, count);
        count = is.read(data);
      }
      return baos.toString();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (is != null)
        try {
          is.close();
        } catch (Exception ignore) {
        }
      if (baos != null)
        try {
          baos.close();
        } catch (Exception ignore) {
        }
    }
    return null;
  }
    private static void createBrokenMarkerFile(@Nullable Throwable reason) {
      final File brokenMarker = getCorruptionMarkerFile();

      try {
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        final PrintStream stream = new PrintStream(out);
        try {
          new Exception().printStackTrace(stream);
          if (reason != null) {
            stream.print("\nReason:\n");
            reason.printStackTrace(stream);
          }
        } finally {
          stream.close();
        }
        LOG.info("Creating VFS corruption marker; Trace=\n" + out.toString());

        final FileWriter writer = new FileWriter(brokenMarker);
        try {
          writer.write(
              "These files are corrupted and must be rebuilt from the scratch on next startup");
        } finally {
          writer.close();
        }
      } catch (IOException e) {
        // No luck.
      }
    }
Esempio n. 18
0
 // Special serializer: output XML as serialization
 private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   write(baos);
   String str = baos.toString();
   ;
   // System.out.println("str='"+str+"'");
   out.writeUTF(str);
 }
Esempio n. 19
0
 public static String inputStreamToString(InputStream is) throws IOException {
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   int i;
   while ((i = is.read()) != -1) {
     baos.write(i);
   }
   return baos.toString();
 }
 public String getOutput() {
   writer.flush();
   writer.close();
   //		if (this.serveletStream != null) {
   //			try {
   //				this.serveletStream.flush();
   //			} catch (IOException e) {
   //				e.printStackTrace();
   //			}
   //		}
   String output = "";
   try {
     output = "" + stream.toString("UTF8");
   } catch (Exception e) {
     output = "" + stream.toString();
   }
   return output;
 }
Esempio n. 21
0
 /**
  * Returns the response body as a <code>String</code>
  *
  * @return The response body
  * @throws java.io.UnsupportedEncodingException If the encoding is not supported
  */
 public String getString() throws UnsupportedEncodingException {
   if (sw != null) {
     return sw.toString();
   } else if (bos != null) {
     return bos.toString(super.getCharacterEncoding());
   } else {
     return "";
   }
 }
Esempio n. 22
0
 @Test
 public void shouldGetSuccessMessageWhenLoginWithValidUser() throws IOException {
   in = new ByteArrayInputStream(VALIDE_USER.getBytes());
   Bilioteca bilioteca = new Bilioteca(in);
   bilioteca.getMenu().selectMenu(LOGIN);
   assertEquals(
       "Please input username and password separate by one space: \n" + "Login successfully!\n",
       out.toString());
 }
Esempio n. 23
0
 @Test
 public void writeToOutputStream() throws IOException {
   XMLDocument doc =
       db.createFolder("/top").documents().load(Name.create(db, "foo"), Source.xml("<root/>"));
   ByteArrayOutputStream out = new ByteArrayOutputStream();
   doc.write(out);
   out.close();
   assertEquals("<root/>", out.toString());
 }
Esempio n. 24
0
  /**
   * Dale Anson: One of the main reasons I borrowed this class from Ant was to be able to read
   * environment variables. It makes sense to add a method to easily fetch the value of an
   * environment variable here.
   *
   * @param name the name of an environment variable. Much of this code was copied from
   *     org.apache.tools.ant.taskdefs.Execute.
   * @return the value of the environment variable, or null if there is no value for the given name
   */
  public static String getEnvironmentValue(String name) {
    if (environment != null) {
      return (String) environment.get(name);
    }
    environment = new Hashtable<String, String>();

    try {
      String[] env_cmd = getProcEnvCommand();
      Process process = Runtime.getRuntime().exec(env_cmd);
      InputStream is = new BufferedInputStream(process.getInputStream());
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      CopyUtils.copy(is, baos);

      BufferedReader in = new BufferedReader(new StringReader(baos.toString()));

      // this portion copied from org.apache.tools.ant.taskdefs.Execute //
      Vector<String> procEnvironment = new Vector<String>();
      String var = null;
      String line, lineSep = System.getProperty("line.separator");
      while ((line = in.readLine()) != null) {
        if (line.indexOf('=') == -1) {
          // Chunk part of previous env var (UNIX env vars can
          // contain embedded new lines).
          if (var == null) {
            var = lineSep + line;
          } else {
            var += lineSep + line;
          }
        } else {
          // New env var...append the previous one if we have it.
          if (var != null) {
            procEnvironment.addElement(var);
          }
          var = line;
        }
      }
      // Since we "look ahead" before adding, there's one last env var.
      if (var != null) {
        procEnvironment.addElement(var);
      }
      // end copy from Execute //

      // now split out the names from the values and populate a Hashtable
      if (procEnvironment.size() > 0) {
        java.util.Iterator it = procEnvironment.iterator();
        while (it.hasNext()) {
          var = (String) it.next();
          int index = var.indexOf("=");
          String key = var.substring(0, index);
          String value = var.substring(index + 1);
          environment.put(key, value);
        }
      }
    } catch (Exception ignored) {
    }
    return getEnvironmentValue(name);
  }
Esempio n. 25
0
 /**
  * Computes the Base64 encoding of a string
  *
  * @param s a string
  * @return the Base 64 encoding of s
  */
 public static String base64Encode(String s) {
   ByteArrayOutputStream bOut = new ByteArrayOutputStream();
   Base64OutputStream out = new Base64OutputStream(bOut);
   try {
     out.write(s.getBytes());
     out.flush();
   } catch (IOException e) {
   }
   return bOut.toString();
 }
Esempio n. 26
0
  /** Show the applet tag. */
  void appletTag() {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    updateAtts();
    printTag(new PrintStream(out), panel.atts);
    showStatus(amh.getMessage("applettag"));

    Point p = location();
    new TextFrame(
        p.x + XDELTA, p.y + YDELTA, amh.getMessage("applettag.textframe"), out.toString());
  }
  private void finishBuild(Throwable error, boolean hadBuildErrors, boolean markedUptodateFiles) {
    CmdlineRemoteProto.Message lastMessage = null;
    try {
      if (error != null) {
        Throwable cause = error.getCause();
        if (cause == null) {
          cause = error;
        }
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        final PrintStream stream = new PrintStream(out);
        try {
          cause.printStackTrace(stream);
        } finally {
          stream.close();
        }

        final StringBuilder messageText = new StringBuilder();
        messageText
            .append("Internal error: (")
            .append(cause.getClass().getName())
            .append(") ")
            .append(cause.getMessage());
        final String trace = out.toString();
        if (!trace.isEmpty()) {
          messageText.append("\n").append(trace);
        }
        lastMessage =
            CmdlineProtoUtil.toMessage(
                mySessionId, CmdlineProtoUtil.createFailure(messageText.toString(), cause));
      } else {
        CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Status status =
            CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Status.SUCCESS;
        if (myCanceled) {
          status = CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Status.CANCELED;
        } else if (hadBuildErrors) {
          status = CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Status.ERRORS;
        } else if (!markedUptodateFiles) {
          status = CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Status.UP_TO_DATE;
        }
        lastMessage =
            CmdlineProtoUtil.toMessage(
                mySessionId, CmdlineProtoUtil.createBuildCompletedEvent("build completed", status));
      }
    } catch (Throwable e) {
      lastMessage =
          CmdlineProtoUtil.toMessage(
              mySessionId, CmdlineProtoUtil.createFailure(e.getMessage(), e));
    } finally {
      try {
        Channels.write(myChannel, lastMessage).await();
      } catch (InterruptedException e) {
        LOG.info(e);
      }
    }
  }
  /**
   * Reads the next line. A line ends with {@code "\n"} or {@code "\r\n"}, this end of line marker
   * is not included in the result.
   *
   * @return the next line from the input.
   * @throws java.io.IOException for underlying {@code InputStream} errors.
   * @throws java.io.EOFException for the end of source stream.
   */
  public String readLine() throws IOException {
    synchronized (in) {
      if (buf == null) {
        throw new IOException("LineReader is closed");
      }

      // Read more data if we are at the end of the buffered data.
      // Though it's an error to read after an exception, we will let {@code fillBuf()}
      // throw again if that happens; thus we need to handle end == -1 as well as end == pos.
      if (pos >= end) {
        fillBuf();
      }
      // Try to find LF in the buffered data and return the line if successful.
      for (int i = pos; i != end; ++i) {
        if (buf[i] == LF) {
          int lineEnd = (i != pos && buf[i - 1] == CR) ? i - 1 : i;
          String res = new String(buf, pos, lineEnd - pos, charset.name());
          pos = i + 1;
          return res;
        }
      }

      // Let's anticipate up to 80 characters on top of those already read.
      ByteArrayOutputStream out =
          new ByteArrayOutputStream(end - pos + 80) {
            @Override
            public String toString() {
              int length = (count > 0 && buf[count - 1] == CR) ? count - 1 : count;
              try {
                return new String(buf, 0, length, charset.name());
              } catch (UnsupportedEncodingException e) {
                throw new AssertionError(e); // Since we control the charset this will never happen.
              }
            }
          };

      while (true) {
        out.write(buf, pos, end - pos);
        // Mark unterminated line in case fillBuf throws EOFException or IOException.
        end = -1;
        fillBuf();
        // Try to find LF in the buffered data and return the line if successful.
        for (int i = pos; i != end; ++i) {
          if (buf[i] == LF) {
            if (i != pos) {
              out.write(buf, pos, i - pos);
            }
            pos = i + 1;
            return out.toString();
          }
        }
      }
    }
  }
Esempio n. 29
0
 /**
  * Gives string representation of a tree, parametrized by how to represent each position. It does
  * a preorder traversal, giving a newline and some indentation before each node, then represents
  * each node as specified. It can print a tree which is at most 100 levels deep.
  *
  * @param t tree to stringify
  * @param pts how to stringify each position
  * @throws IndexOutOfBoundsException if the tree is more then 100 levels deep
  * @return the string representation of t
  */
 public static String stringfor(InspectableTree t, PositionToString pts) {
   if (spaces == null) {
     spaces = new byte[200]; // tree can't be more than 100 levels deep
     for (int i = 0; i < 200; ++i) spaces[i] = (byte) ' ';
   }
   // the 4 below was generated entirely at random
   ByteArrayOutputStream bstr = new ByteArrayOutputStream(t.size() * 4);
   DataOutputStream ostr = new DataOutputStream(bstr);
   writeNodeAndChildren(t.root(), pts, ostr, t, 0, 2);
   return bstr.toString();
 }
 public String encodeBuffer(byte abyte0[]) {
   ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream();
   ByteArrayInputStream bytearrayinputstream = new ByteArrayInputStream(abyte0);
   try {
     encodeBuffer(
         ((InputStream) (bytearrayinputstream)), ((OutputStream) (bytearrayoutputstream)));
   } catch (Exception exception) {
     throw new Error("CharacterEncoder.encodeBuffer internal error");
   }
   return bytearrayoutputstream.toString();
 }