Home > Software engineering >  Convert to scala code PEM to DER Certificate Follow it up from Google KMS Library
Convert to scala code PEM to DER Certificate Follow it up from Google KMS Library

Time:06-23

I am new to scala andwas trying to convert this to scala code.

  public static byte[] convertPemToDer(String pem) {
            BufferedReader bufferedReader = new BufferedReader(new StringReader(pem));
            String encoded =
                    bufferedReader
                            .lines()
                            .filter(line -> !line.startsWith("-----BEGIN") && !line.startsWith("-----END"))
                            .collect(Collectors.joining());
            return Base64.getDecoder().decode(encoded);
        }


def convertPemToDer(pem: String): Array[Byte] = {
    val bufferedReader = new BufferedReader(new StringReader(pem))
    val encoded = bufferedReader.lines.filter((line: String) => !line.startsWith("-----BEGIN") && !line.startsWith("-----END")).collect(Collectors.joining)
    Base64.getDecoder.decode(encoded)
  }

It shows type mismatch within filter.

CodePudding user response:

Double check your imports. I could run your code by using these imports:

import java.io.{BufferedReader, StringReader}
import java.util.Base64
import java.util.stream.Collectors

The code compiled and ran just fine. I just added a println at the end:

object Main extends App {

  def convertPemToDer(pem: String): Array[Byte] = {
    val bufferedReader = new BufferedReader(new StringReader(pem))
    val encoded = bufferedReader.lines
      .filter((line: String) =>
        !line.startsWith("-----BEGIN") && !line.startsWith("-----END")
      )
      .collect(Collectors.joining)
    Base64.getDecoder.decode(encoded)
  }

  println(convertPemToDer("Elephant").mkString("Array(", ", ", ")"))

}

Output:

Array(18, 87, -87, -123, -87, -19)

If you are not using Intellij with the Scala plugin, your IDE might not be able to recognize Functional Interfaces as Single Abstract Methods. So you might need to adapt your code into a more Java-style approach, like this:

  def convertPemToDer(pem: String): Array[Byte] = {
    val bufferedReader = new BufferedReader(new StringReader(pem))
    val encoded = bufferedReader.lines
      .filter(new Predicate[String] {
        override def test(line: String): Boolean =
          !line.startsWith("-----BEGIN") && !line.startsWith("-----END")
      })
      .collect(Collectors.joining)
    Base64.getDecoder.decode(encoded)
  }
  • Related