All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.ironsoftware.ironpdf.internal.staticapi.Utils_Util Maven / Gradle / Ivy

Go to download

IronPDF Java library offers an extensive compatibility range, making it a go-to solution for a wide array of developers. It fully supports JVM languages like Java, Scala, and Kotlin, making it incredibly versatile. This Java PDF library is also compatible with Java 8 and above, providing optimum performance across multiple platforms. It's been designed with a wide range of users in mind Here's a look at what it supports: JVM Languages: Java, Scala, Kotlin.Platforms: Java 8 and above.Operating Systems: Microsoft Windows, Linux, Docker, Azure, AWS.IDEs: Jetbrains IntelliJ IDEA, Eclipse. You can deploy IronPDF Java across various platforms, including Microsoft Windows, Linux, Docker, Azure, and AWS. It is also fully compatible with popular IDEs like Jetbrains IntelliJ IDEA and Eclipse, facilitating smooth project development and management. Your pom.xml file is essentially the backbone of your project when you're using Maven. It's here where you introduce new dependencies that you wish to include. To make IronPDF Java package a part of your Maven project, you simply need to add the following snippets to your pom.xml: Remember to replace '20xx.xx.xxxx' with the latest version of IronPDF. IronPDF Java simplifies the process of creating PDF files. Convert HTML files, HTML strings, or URLs directly to new PDF documents in a few lines of code. The variety of file formats it handles is vast, as it can even transform images into PDF documents and vice versa. Need to use base 64 encoding, base URLs, or custom file paths? No problem! IronPDF Java has got you coveredFor more detail about installing and using IronPDF Java. When you run your project for the first time post-integration, IronPDF's engine binaries will automatically be downloaded. The engine starts its journey when you call any IronPDF function for the first time and takes a breather when your application is either closed or enters an idle state. It is not an open source java PDF library but here's the best part - IronPDF Java is offering a 30-day free trial. So, why wait? Give it a go and boost your PDF operations today.

There is a newer version: 2025.1.1
Show newest version
package com.ironsoftware.ironpdf.internal.staticapi;

import com.ironsoftware.ironpdf.internal.proto.*;
import org.slf4j.Logger;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import static com.ironsoftware.ironpdf.internal.staticapi.Utils_StringHelper.isNullOrEmpty;

/**
 * The type Utils util.
 */
final class Utils_Util {

    /**
     * The Chunk size.
     */
    static final int CHUNK_SIZE = 65536; // 64 * 1024 // 65.53600 kilobytes // GRPC msg size limit 4MB

    /**
     * Enum comparable string.
     *
     * @param input the input
     * @return the string
     */
    static String enumComparable(String input) {
        return input.toUpperCase().trim().replace("_", "").replace("-", "");
    }

    /**
     * Null guard string.
     *
     * @param input the input
     * @return the string
     */
    static String nullGuard(String input) {
        if (isNullOrEmpty(input)) {
            return "";
        }

        return input;
    }

    /**
     * Null if empty string.
     *
     * @param input the input
     * @return the string
     */
    static String nullIfEmpty(String input) {
        return isNullOrEmpty(input) ? null : input;
    }

    /**
     * Chunk list.
     *
     * @param   the type parameter
     * @param data the data
     * @return the list
     */
    static  List chunk(final T[] data) {
        return chunk(data, CHUNK_SIZE);
    }

    /**
     * Chunk list.
     *
     * @param        the type parameter
     * @param data      the data
     * @param chunkSize the chunk size
     * @return the list
     */
    @SuppressWarnings("SameParameterValue")
    static  List chunk(T[] data, int chunkSize) {
        return IntStream.iterate(0, i -> i + chunkSize)
                .limit((data.length + chunkSize - 1) / chunkSize)
                .mapToObj(i -> Arrays.copyOfRange(data, i, Math.min(i + chunkSize, data.length)))
                .collect(Collectors.toList());

    }

    /**
     * Chunk iterator.
     *
     * @param data the data
     * @return the iterator
     */
    static Iterator chunk(final byte[] data) {
        return chunk(data, CHUNK_SIZE);
    }

    /**
     * Chunk iterator.
     *
     * @param data      the data
     * @param chunkSize the chunk size
     * @return the iterator
     */
    @SuppressWarnings("SameParameterValue")
    static Iterator chunk(byte[] data, int chunkSize) {
        return IntStream.iterate(0, i -> i + chunkSize)
                .limit((data.length + chunkSize - 1) / chunkSize)
                .mapToObj(i -> Arrays.copyOfRange(data, i, Math.min(i + chunkSize, data.length)))
                .iterator();
    }

    /**
     * Chunk iterator.
     *
     * @param data the data
     * @return the iterator
     */
    static Iterator chunk(final char[] data) {
        return chunk(data, CHUNK_SIZE);
    }

    /**
     * Chunk iterator.
     *
     * @param data      the data
     * @param chunkSize the chunk size
     * @return the iterator
     */
    @SuppressWarnings("SameParameterValue")
    static Iterator chunk(char[] data, int chunkSize) {
        return IntStream.iterate(0, i -> i + chunkSize)
                .limit((data.length + chunkSize - 1) / chunkSize)
                .mapToObj(i -> Arrays.copyOfRange(data, i, Math.min(i + chunkSize, data.length)))
                .iterator();
    }

    /**
     * Handle empty result.
     *
     * @param emptyResult the empty result
     */
    static void handleEmptyResult(EmptyResultP emptyResult) {
        if (emptyResult.getResultOrExceptionCase() == EmptyResultP.ResultOrExceptionCase.EXCEPTION) {
            throw Exception_Converter.fromProto(emptyResult.getException());
        }
    }

    /**
     * Handle empty result chunks.
     *
     * @param emptyResultChunks the empty result chunks
     */
    static void handleEmptyResultChunks(List emptyResultChunks) {
        if (emptyResultChunks.size() == 0) {
            throw new RuntimeException("No response from IronPdf.");
        }

        EmptyResultP res = emptyResultChunks.stream().findFirst().get();

        handleEmptyResult(res);
    }

    /**
     * Handle boolean result boolean.
     *
     * @param booleanResult the boolean result
     * @return the boolean
     */
    static boolean handleBooleanResult(BooleanResultP booleanResult) {
        if (booleanResult.getResultOrExceptionCase() == BooleanResultP.ResultOrExceptionCase.EXCEPTION) {
            throw Exception_Converter.fromProto(booleanResult.getException());
        }
        return booleanResult.getResult();
    }

    /**
     * Handle images result list.
     *
     * @param resultChunks the result chunks
     * @return the list
     * @throws IOException the io exception
     */
    static List handleImagesResult(List resultChunks) throws IOException {
        if (resultChunks.size() == 0) {
            throw new IOException("No response from IronPdf.");
        }
        resultChunks.stream().filter(ImagesResultStreamP::hasException).findFirst().ifPresent(x -> {
            throw Exception_Converter.fromProto(x.getException());
        });

        java.util.Map> grouped = resultChunks.stream()
                .map(ImagesResultStreamP::getRawImagesChunk)
                .collect(Collectors.groupingBy(RawImageChunkWithIndexP::getImageIndex,
                        Collectors.mapping(c -> c.getRawImageChunk().toByteArray(), Collectors.toList())));

        return grouped.values().stream().map(Utils_Util::combineChunk).collect(Collectors.toList());
    }

    /**
     * Handle image result list.
     *
     * @param resultChunks the result chunks
     * @return the list
     * @throws IOException the io exception
     */
    static byte[] handleImageResult(List resultChunks) throws IOException {
        if (resultChunks.size() == 0) {
            throw new IOException("No response from IronPdf.");
        }
        resultChunks.stream().filter(ImageResultStreamP::hasException).findFirst().ifPresent(x -> {
            throw Exception_Converter.fromProto(x.getException());
        });
        List chunks = resultChunks.stream()
                .map(c -> c.getRawImageChunk().toByteArray()).collect(Collectors.toList());
        return Utils_Util.combineChunk(chunks);
    }

    /**
     * Combine chunk byte [ ].
     *
     * @param chunks the chunks
     * @return the byte [ ]
     */
    static byte[] combineChunk(List chunks) {
        int totalLength = 0;
        for (byte[] chunk : chunks) {
            totalLength += chunk.length;
        }
        byte[] result = new byte[totalLength];
        int offset = 0;
        for (byte[] chunk : chunks) {
            System.arraycopy(chunk, 0, result, offset, chunk.length);
            offset += chunk.length;
        }
        return result;
    }

    /**
     * Handle pdf document result internal pdf document.
     *
     * @param res the res
     * @return the internal pdf document
     */
    static InternalPdfDocument handlePdfDocumentResult(PdfDocumentResultP res) {
        if (res.getResultOrExceptionCase() == PdfDocumentResultP.ResultOrExceptionCase.EXCEPTION) {
            throw Exception_Converter.fromProto(res.getException());
        }

        return new InternalPdfDocument(res.getResult());
    }

    /**
     * Handle pdf document chunks internal pdf document.
     *
     * @param resChunks the res chunks
     * @return the internal pdf document
     */
    static InternalPdfDocument handlePdfDocumentChunks(List resChunks) {
        if (resChunks.size() == 0) {
            throw new RuntimeException("No response from IronPdf.");
        }

        PdfDocumentResultP res = resChunks.stream().findFirst().get();

        return handlePdfDocumentResult(res);
    }

    static byte[] handleByteChunks(List resultChunks){
        List bytesChunks = resultChunks.stream().map(res -> {
                    if (res.getResultOrExceptionCase() == BytesResultStreamP.ResultOrExceptionCase.EXCEPTION) {
                        throw Exception_Converter.fromProto(res.getException());
                    }
                    return res.getResultChunk().toByteArray();
                }
        ).collect(Collectors.toList());

        return Utils_Util.combineChunk(bytesChunks);
    }

    /**
     * Wait and check.
     *
     * @param           the type parameter
     * @param finishLatch  the finish latch
     * @param resultChunks the result chunks
     */
    static  void waitAndCheck(CountDownLatch finishLatch, List resultChunks) {
        try {
            finishLatch.await(Setting_Api.ironPdfEngineTimeout, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


        if (resultChunks.size() == 0) {
            throw new RuntimeException("No response from IronPdfEngine.");
        }
    }

    static void logInfoOrSystemOut(Logger logger, String msg) {
        if (logger.isInfoEnabled())
            logger.info(msg);
        else
            System.out.println(msg);
    }
}





© 2015 - 2025 Weber Informatics LLC | Privacy Policy