Example usage for java.util Base64 getEncoder

List of usage examples for java.util Base64 getEncoder

Introduction

In this page you can find the example usage for java.util Base64 getEncoder.

Prototype

public static Encoder getEncoder() 

Source Link

Document

Returns a Encoder that encodes using the Basic type base64 encoding scheme.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception { // main method
    // Encode a String into bytes
    String inputString = "this is a test";
    byte[] input = inputString.getBytes("UTF-8");

    // Compress the bytes
    byte[] output1 = new byte[input.length];
    Deflater compresser = new Deflater();
    compresser.setInput(input);//from  w w w  .  j ava 2s  .c o  m
    compresser.finish();
    int compressedDataLength = compresser.deflate(output1);
    compresser.end();

    String str = new String(Base64.getEncoder().encode(output1));
    System.out.println("Deflated String:" + str);

    byte[] output2 = Base64.getDecoder().decode(str);

    // Decompress the bytes
    Inflater decompresser = new Inflater();
    decompresser.setInput(output2);
    byte[] result = str.getBytes();
    int resultLength = decompresser.inflate(result);
    decompresser.end();

    // Decode the bytes into a String
    String outputString = new String(result, 0, resultLength, "UTF-8");
    System.out.println("Deflated String:" + outputString);

}

From source file:utybo.branchingstorytree.swing.utils.FontTF.java

public static void main(String[] args) throws MalformedURLException, IOException {
    Scanner sc = new Scanner(System.in);
    System.out.print("Path to transform from => ");
    String s = sc.nextLine();//  w  ww  . j  a v a  2 s.c om
    System.out.print("Save to => ");
    File f = new File(sc.nextLine());
    f.createNewFile();
    System.out.println("Downloading...");
    String string = IOUtils.toString(new FileInputStream(new File(s)), StandardCharsets.UTF_8);
    System.out.println(string);
    System.out.println("Transforming");
    Pattern p = Pattern.compile("local\\(.*?\\), local\\(.*?\\), url\\((http.+?)\\)", Pattern.MULTILINE);
    Matcher m = p.matcher(string);
    while (m.find()) {
        String toReplace = m.group();
        String url = m.group(1);
        System.out.println("Downloading " + url);
        byte[] raw = IOUtils.toByteArray(new URL(url).openStream());
        System.out.println("Converting");
        String b64 = Base64.getEncoder().encodeToString(raw);
        string = string.replace(toReplace, "url(data:font/woff2;charset=utf-8;base64," + b64 + ")");
        System.out.println(string);
        m.reset(string);
    }
    System.out.println("Writing");
    FileUtils.write(f, string, StandardCharsets.UTF_8);
    System.out.println("Done");
    sc.close();
}

From source file:com.daon.identityx.utils.GenerateAndroidFacet.java

public static void main(String[] args) {

    String androidKeystoreLocation = System.getProperty("ANDROID_KEYSTORE_LOCATION",
            DEFAULT_ANDROID_KEYSTORE_LOCATION);
    String androidKeystorePassword = System.getProperty("ANDROID_KEYSTORE_PASSWORD",
            DEFAULT_ANDROID_KEYSTORE_PASSWORD);
    String androidKeystoreCert = System.getProperty("ANDROID_KEYSTORE_CERT_NAME",
            DEFAULT_ANDROID_KEYSTORE_CERT_NAME);
    String hashingAlgorithm = System.getProperty("HASHING_ALGORITHM", DEFAULT_HASHING_ALGORITHM);

    try {/*from w w  w  .ja  va 2  s. c o  m*/
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        File filePath = new File(androidKeystoreLocation);
        if (!filePath.exists()) {
            System.err.println(
                    "The filepath to the debug keystore could not be located at: " + androidKeystoreCert);
            System.exit(1);
        } else {
            System.out.println("Found the Android Studio keystore at: " + androidKeystoreLocation);
        }

        keyStore.load(new FileInputStream(filePath), androidKeystorePassword.toCharArray());
        System.out.println("Keystore loaded - password and location were OK");

        Certificate cert = keyStore.getCertificate(androidKeystoreCert);
        if (cert == null) {
            System.err.println(
                    "Could not location the certification in the store with the name: " + androidKeystoreCert);
            System.exit(1);
        } else {
            System.out.println("Certificate found in the store with name: " + androidKeystoreCert);
        }

        byte[] certBytes = cert.getEncoded();

        MessageDigest digest = MessageDigest.getInstance(hashingAlgorithm);
        System.out.println("Hashing algorithm: " + hashingAlgorithm + " found.");
        byte[] hashedCert = digest.digest(certBytes);
        String base64HashedCert = Base64.getEncoder().encodeToString(hashedCert);
        System.out.println("Base64 encoded SHA-1 hash of the certificate: " + base64HashedCert);
        String base64HashedCertRemoveTrailing = StringUtils.deleteAny(base64HashedCert, "=");
        System.out.println(
                "Add the following facet to the Facets file in order for the debug app to be trusted by the FIDO client");
        System.out.println("\"android:apk-key-hash:" + base64HashedCertRemoveTrailing + "\"");

    } catch (Throwable ex) {
        ex.printStackTrace();
    }

}

From source file:test.TestJavaService.java

/**
 * Main.  The cmdline arguments either do or don't contain the flag -remote: that's the only supported flag.  If it is specified,
 *   we test code on the AWS instance.  If it is not, we test code running locally.
 * The first non-flag argument is the "verb", which (currently) should be one of the verbs set at the top of source file
 *   org.qcert.javasrc.Main.  Remaining non-flag arguments are file names.  There must be at least one.  The number of such 
 *   arguments and what they should contain depends on the verb.
 * @throws Exception/* w w w .j a v a 2 s . c  om*/
 */
public static void main(String[] args) throws Exception {
    /* Parse command line */
    List<String> files = new ArrayList<>();
    String loc = "localhost", verb = null;
    for (String arg : args) {
        if (arg.equals("-remote"))
            loc = REMOTE_LOC;
        else if (arg.startsWith("-"))
            illegal();
        else if (verb == null)
            verb = arg;
        else
            files.add(arg);
    }
    /* Simple consistency checks and verb-specific parsing */
    if (files.size() == 0)
        illegal();
    String file = files.remove(0);
    String schema = null;
    switch (verb) {
    case "parseSQL":
    case "serialRule2CAMP":
    case "sqlSchema2JSON":
        if (files.size() != 0)
            illegal();
        break;
    case "techRule2CAMP":
        if (files.size() != 1)
            illegal();
        schema = files.get(0);
        break;
    case "csv2JSON":
        if (files.size() < 1)
            illegal();
        break;
    default:
        illegal();
    }

    /* Assemble information from arguments */
    String url = String.format("http://%s:9879?verb=%s", loc, verb);
    byte[] contents = Files.readAllBytes(Paths.get(file));
    String toSend;
    if ("serialRule2CAMP".equals(verb))
        toSend = Base64.getEncoder().encodeToString(contents);
    else
        toSend = new String(contents);
    if ("techRule2CAMP".equals(verb))
        toSend = makeSpecialJson(toSend, schema);
    else if ("csv2JSON".equals(verb))
        toSend = makeSpecialJson(toSend, files);
    HttpClient client = HttpClients.createDefault();
    HttpPost post = new HttpPost(url);
    StringEntity entity = new StringEntity(toSend);
    entity.setContentType("text/plain");
    post.setEntity(entity);
    HttpResponse resp = client.execute(post);
    int code = resp.getStatusLine().getStatusCode();
    if (code == HttpStatus.SC_OK) {
        HttpEntity answer = resp.getEntity();
        InputStream s = answer.getContent();
        BufferedReader rdr = new BufferedReader(new InputStreamReader(s));
        String line = rdr.readLine();
        while (line != null) {
            System.out.println(line);
            line = rdr.readLine();
        }
        rdr.close();
        s.close();
    } else
        System.out.println(resp.getStatusLine());
}

From source file:net.kolola.msgparsercli.MsgParseCLI.java

public static void main(String[] args) {

    // Parse options

    OptionParser parser = new OptionParser("f:a:bi?*");
    OptionSet options = parser.parse(args);

    // Get the filename
    if (!options.has("f")) {
        System.err.print("Specify a msg file with the -f option");
        System.exit(0);/*from  www  .j  av a2s.c  o  m*/
    }

    File file = new File((String) options.valueOf("f"));

    MsgParser msgp = new MsgParser();
    Message msg = null;

    try {
        msg = msgp.parseMsg(file);
    } catch (UnsupportedOperationException | IOException e) {
        System.err.print("File does not exist or is not a valid msg file");
        //e.printStackTrace();
        System.exit(1);
    }

    // Show info (as JSON)
    if (options.has("i")) {
        Map<String, Object> data = new HashMap<String, Object>();

        String date;

        try {
            Date st = msg.getClientSubmitTime();
            date = st.toString();
        } catch (Exception g) {
            try {
                date = msg.getDate().toString();
            } catch (Exception e) {
                date = "[UNAVAILABLE]";
            }
        }

        data.put("date", date);
        data.put("subject", msg.getSubject());
        data.put("from", "\"" + msg.getFromName() + "\" <" + msg.getFromEmail() + ">");
        data.put("to", "\"" + msg.getToRecipient().toString());

        String cc = "";
        for (RecipientEntry r : msg.getCcRecipients()) {
            if (cc.length() > 0)
                cc.concat("; ");

            cc.concat(r.toString());
        }

        data.put("cc", cc);

        data.put("body_html", msg.getBodyHTML());
        data.put("body_rtf", msg.getBodyRTF());
        data.put("body_text", msg.getBodyText());

        // Attachments
        List<Map<String, String>> atts = new ArrayList<Map<String, String>>();
        for (Attachment a : msg.getAttachments()) {
            HashMap<String, String> info = new HashMap<String, String>();

            if (a instanceof FileAttachment) {
                FileAttachment fa = (FileAttachment) a;

                info.put("type", "file");
                info.put("filename", fa.getFilename());
                info.put("size", Long.toString(fa.getSize()));
            } else {
                info.put("type", "message");
            }

            atts.add(info);
        }

        data.put("attachments", atts);

        JSONObject json = new JSONObject(data);

        try {
            System.out.print(json.toString(4));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    // OR return an attachment in BASE64
    else if (options.has("a")) {
        Integer anum = Integer.parseInt((String) options.valueOf("a"));

        Encoder b64 = Base64.getEncoder();

        List<Attachment> atts = msg.getAttachments();

        if (atts.size() <= anum) {
            System.out.print("Attachment " + anum.toString() + " does not exist");
        }

        Attachment att = atts.get(anum);

        if (att instanceof FileAttachment) {
            FileAttachment fatt = (FileAttachment) att;
            System.out.print(b64.encodeToString(fatt.getData()));
        } else {
            System.err.print("Attachment " + anum.toString() + " is a message - That's not implemented yet :(");
        }
    }
    // OR print the message body
    else if (options.has("b")) {
        System.out.print(msg.getConvertedBodyHTML());
    } else {
        System.err.print(
                "Specify either -i to return msg information or -a <num> to print an attachment as a BASE64 string");
    }

}

From source file:OCRRestAPI.java

public static void main(String[] args) throws Exception {
    /*//from w  w w.java  2 s.  co  m
              
         Sample project for OCRWebService.com (REST API).
         Extract text from scanned images and convert into editable formats.
         Please create new account with ocrwebservice.com via http://www.ocrwebservice.com/account/signup and get license code
            
     */

    // Provide your user name and license code
    String license_code = "88EF173D-CDEA-41B6-8D64-C04578ED8C4D";
    String user_name = "FERGOID";

    /*
            
      You should specify OCR settings. See full description http://www.ocrwebservice.com/service/restguide
             
      Input parameters:
             
     [language]      - Specifies the recognition language. 
                  This parameter can contain several language names separated with commas. 
                    For example "language=english,german,spanish".
               Optional parameter. By default:english
            
     [pagerange]     - Enter page numbers and/or page ranges separated by commas. 
               For example "pagerange=1,3,5-12" or "pagerange=allpages".
                    Optional parameter. By default:allpages
             
      [tobw]           - Convert image to black and white (recommend for color image and photo). 
               For example "tobw=false"
                    Optional parameter. By default:false
             
      [zone]          - Specifies the region on the image for zonal OCR. 
               The coordinates in pixels relative to the left top corner in the following format: top:left:height:width. 
               This parameter can contain several zones separated with commas. 
                 For example "zone=0:0:100:100,50:50:50:50"
                    Optional parameter.
              
      [outputformat]  - Specifies the output file format.
                    Can be specified up to two output formats, separated with commas.
               For example "outputformat=pdf,txt"
                    Optional parameter. By default:doc
            
      [gettext]      - Specifies that extracted text will be returned.
               For example "tobw=true"
                    Optional parameter. By default:false
            
       [description]  - Specifies your task description. Will be returned in response.
                    Optional parameter. 
            
            
     !!!!  For getting result you must specify "gettext" or "outputformat" !!!!  
            
    */

    // Build your OCR:

    // Extraction text with English language
    String ocrURL = "http://www.ocrwebservice.com/restservices/processDocument?gettext=true";

    // Extraction text with English and German language using zonal OCR
    ocrURL = "http://www.ocrwebservice.com/restservices/processDocument?language=english,german&zone=0:0:600:400,500:1000:150:400";

    // Convert first 5 pages of multipage document into doc and txt
    // ocrURL = "http://www.ocrwebservice.com/restservices/processDocument?language=english&pagerange=1-5&outputformat=doc,txt";

    // Full path to uploaded document
    String filePath = "sarah-morgan.jpg";

    byte[] fileContent = Files.readAllBytes(Paths.get(filePath));

    URL url = new URL(ocrURL);

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setRequestMethod("POST");

    connection.setRequestProperty("Authorization",
            "Basic " + Base64.getEncoder().encodeToString((user_name + ":" + license_code).getBytes()));

    // Specify Response format to JSON or XML (application/json or application/xml)
    connection.setRequestProperty("Content-Type", "application/json");

    connection.setRequestProperty("Content-Length", Integer.toString(fileContent.length));

    int httpCode;
    try (OutputStream stream = connection.getOutputStream()) {

        // Send POST request
        stream.write(fileContent);
        stream.close();
    } catch (Exception e) {
        System.out.println(e.toString());
    }

    httpCode = connection.getResponseCode();

    System.out.println("HTTP Response code: " + httpCode);

    // Success request
    if (httpCode == HttpURLConnection.HTTP_OK) {
        // Get response stream
        String jsonResponse = GetResponseToString(connection.getInputStream());

        // Parse and print response from OCR server
        PrintOCRResponse(jsonResponse);
    } else if (httpCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
        System.out.println("OCR Error Message: Unauthorizied request");
    } else {
        // Error occurred
        String jsonResponse = GetResponseToString(connection.getErrorStream());

        JSONParser parser = new JSONParser();
        JSONObject jsonObj = (JSONObject) parser.parse(jsonResponse);

        // Error message
        System.out.println("Error Message: " + jsonObj.get("ErrorMessage"));
    }

    connection.disconnect();

}

From source file:Algorithm.ImageEncoder.java

public static String getImageString(InputStream img, int height, int width, String _class) {
    String theString = "";
    try {//from www .  j ava2  s.c  o  m
        byte[] barr = IOUtils.toByteArray(img);
        Base64.Encoder en = Base64.getEncoder();
        theString = en.encodeToString(barr);
    } catch (IOException iOException) {
        // Do nothing
    }
    //item.write(f);

    return "<img class=\"" + _class + "\" src=\"data:image/jpeg;base64," + theString
            + "\" data-holder-rendered=\"true\" style=\"width: " + width + "px; height: " + height + ";\">";
}

From source file:rmblworx.tools.timey.gui.AnalyzeTestHelper.java

/**
 * Erzeugt einen Screenshot und gibt dessen Inhalt Base64-kodiert auf der Konsole aus.
 * uerst ntzlich, um nur auf Travis fehlschlagende Tests zu analysieren.
 * @throws IOException/*from   w w  w.ja  va 2 s. com*/
 */
public static void printBase64EncodedScreenshotContent() throws IOException {
    final File screenshot = GuiTest.captureScreenshot();
    System.out.println(String.format("Base64-encoded content of %s:", screenshot.getAbsolutePath()));
    System.out.println(Base64.getEncoder().encodeToString(FileUtils.readFileToByteArray(screenshot)));
    System.out.println();
}

From source file:bridgempp.PermissionsManager.java

public static String generateKey(int permissions, boolean useOnce) {
    SecureRandom random = new SecureRandom();
    byte[] byteKey = new byte[32];
    random.nextBytes(byteKey);/* www.j  a  va  2 s  . c  o m*/
    String key = Base64.getEncoder().encodeToString(byteKey);
    accessKeys.put(key, new AccessKey(key, permissions, useOnce));
    return key;
}

From source file:org.elasticsearch.xpack.watcher.common.http.auth.basic.ApplicableBasicAuth.java

public static String headerValue(String username, char[] password) {
    return "Basic " + Base64.getEncoder()
            .encodeToString((username + ":" + new String(password)).getBytes(StandardCharsets.UTF_8));
}