Example usage for com.lowagie.text.pdf.codec Base64 encodeBytes

List of usage examples for com.lowagie.text.pdf.codec Base64 encodeBytes

Introduction

In this page you can find the example usage for com.lowagie.text.pdf.codec Base64 encodeBytes.

Prototype

public static String encodeBytes(byte[] source) 

Source Link

Document

Encodes a byte array into Base64 notation.

Usage

From source file:br.gov.jfrj.siga.vraptor.ExArquivoController.java

License:Open Source License

@Get("/app/arquivo/exibir")
public Download aExibir(final String sigla, final boolean popup, final String arquivo, byte[] certificado,
        String hash, final String HASH_ALGORITHM, final String certificadoB64, boolean completo,
        final boolean semmarcas) {
    try {//  w w w. j  av  a2s.  c o m
        final String servernameport = getRequest().getServerName() + ":" + getRequest().getServerPort();
        final String contextpath = getRequest().getContextPath();
        final boolean pacoteAssinavel = (certificadoB64 != null);
        final boolean fB64 = getRequest().getHeader("Accept") != null
                && getRequest().getHeader("Accept").startsWith("text/vnd.siga.b64encoded");
        final boolean isPdf = arquivo.endsWith(".pdf");
        final boolean isHtml = arquivo.endsWith(".html");
        boolean estampar = !semmarcas;
        final boolean somenteHash = (hash != null) || (HASH_ALGORITHM != null);
        if (somenteHash) {
            if (hash == null)
                hash = HASH_ALGORITHM;
            if (hash != null) {
                if (!(hash.equals("SHA1") || hash.equals("SHA-256") || hash.equals("SHA-512")
                        || hash.equals("MD5"))) {
                    throw new AplicacaoException(
                            "Algoritmo de hash invlido. Os permitidos so: SHA1, SHA-256, SHA-512 e MD5.");
                }
            }
            completo = false;
            estampar = false;
        }
        if (pacoteAssinavel) {
            certificado = Base64.decode(certificadoB64);
            completo = false;
            estampar = false;
        }
        final ExMobil mob = Documento.getMobil(arquivo);
        if (mob == null) {
            throw new AplicacaoException("A sigla informada no corresponde a um documento da base de dados.");
        }
        if (!Ex.getInstance().getComp().podeAcessarDocumento(getTitular(), getLotaTitular(), mob)) {
            throw new AplicacaoException("Documento " + mob.getSigla() + " inacessvel ao usurio "
                    + getTitular().getSigla() + "/" + getLotaTitular().getSiglaCompleta() + ".");
        }
        final ExMovimentacao mov = Documento.getMov(mob, arquivo);
        final boolean imutavel = (mov != null) && !completo && !estampar && !somenteHash && !pacoteAssinavel;
        String cacheControl = "private";
        final Integer grauNivelAcesso = mob.doc().getExNivelAcessoDoDocumento().getGrauNivelAcesso();
        if (ExNivelAcesso.NIVEL_ACESSO_PUBLICO == grauNivelAcesso
                || ExNivelAcesso.NIVEL_ACESSO_ENTRE_ORGAOS == grauNivelAcesso) {
            cacheControl = "public";
        }
        byte ab[] = null;
        if (isPdf) {
            if (mov != null && !completo && !estampar && hash == null) {
                ab = mov.getConteudoBlobpdf();
            } else {
                ab = Documento.getDocumento(mob, mov, completo, estampar, hash, null);
            }
            if (ab == null) {
                throw new Exception("PDF invlido!");
            }
            if (pacoteAssinavel) {
                CdService client = Service.getCdService();
                final Date dt = dao().consultarDataEHoraDoServidor();
                getResponse().setHeader("Atributo-Assinavel-Data-Hora", Long.toString(dt.getTime()));
                byte[] sa = client.produzPacoteAssinavel(certificado, certificado, ab, true, dt);
                return new InputStreamDownload(makeByteArrayInputStream(sa, fB64), APPLICATION_OCTET_STREAM,
                        arquivo);
            }
            if (hash != null) {
                return new InputStreamDownload(makeByteArrayInputStream(ab, fB64), APPLICATION_OCTET_STREAM,
                        arquivo);
            }
        }
        if (isHtml) {
            ab = Documento.getDocumentoHTML(mob, mov, completo, contextpath, servernameport);
            if (ab == null) {
                throw new Exception("HTML invlido!");
            }
        }
        if (imutavel) {
            getResponse().setHeader("Cache-Control", cacheControl);
            getResponse().setDateHeader("Expires", new Date().getTime() + (365 * 24 * 3600 * 1000L));
        } else {
            final MessageDigest md = MessageDigest.getInstance("MD5");
            final int m = match(ab);
            if (m != -1) {
                md.update(ab, 0, m);
            } else {
                md.update(ab);
            }
            final String etag = Base64.encodeBytes(md.digest());
            final String ifNoneMatch = getRequest().getHeader("If-None-Match");
            getResponse().setHeader("Cache-Control", "must-revalidate, " + cacheControl);
            getResponse().setDateHeader("Expires", (new Date()).getTime() + 30000);
            getResponse().setHeader("ETag", etag);

            if ((etag).equals(ifNoneMatch) && ifNoneMatch != null) {
                getResponse().sendError(HttpServletResponse.SC_NOT_MODIFIED);
                return new InputStreamDownload(makeByteArrayInputStream((new byte[0]), false), TEXT_PLAIN,
                        "arquivo invlido");
            }
        }
        getResponse().setHeader("Pragma", "");
        return new InputStreamDownload(makeByteArrayInputStream(ab, fB64), checkDownloadType(ab, isPdf, fB64),
                arquivo);
    } catch (Exception e) {
        if (e.getClass().getSimpleName().equals("ClientAbortException")) {
            return new InputStreamDownload(makeByteArrayInputStream((new byte[0]), false), TEXT_PLAIN,
                    "arquivo invlido");
        }
        throw new RuntimeException("erro na gerao do documento.", e);
    }
}

From source file:br.gov.jfrj.siga.vraptor.ExArquivoController.java

License:Open Source License

private Download iniciarDownload(ExMobil mob, ExInputStreamDownload exDownload) {
    try {//from ww w  . j a v  a 2s.  c  o m
        // Calcula o hash do documento, mas no leva em considerao
        // para fins de hash os ltimos bytes do arquivos, pois l
        // fica armazanada a ID e as datas de criao e modificao
        // e estas so sempre diferente de um pdf para o outro.
        MessageDigest md = MessageDigest.getInstance("MD5");

        byte ab[] = exDownload.getBytes();
        int m = match(ab);
        if (m != -1)
            md.update(ab, 0, m);
        else
            md.update(ab);

        String etag = Base64.encodeBytes(md.digest());
        String ifNoneMatch = getRequest().getHeader("If-None-Match");
        getResponse().setHeader("Cache-Control", "must-revalidate, " + getCacheControl(mob));
        getResponse().setDateHeader("Expires", 0);
        getResponse().setHeader("ETag", etag);
        getResponse().setHeader("Pragma", "");

        if (ifNoneMatch != null && ifNoneMatch.equals(etag)) {
            getResponse().sendError(HttpServletResponse.SC_NOT_MODIFIED);
            return null;
        }
        return exDownload;
    } catch (Exception e) {
        throw new AplicacaoException("erro na gerao do documento.");
    }
}

From source file:br.gov.jfrj.siga.vraptor.ExArquivoController.java

License:Open Source License

private ByteArrayInputStream makeByteArrayInputStream(final byte[] content, final boolean fB64) {
    final byte[] conteudo = (fB64 ? Base64.encodeBytes(content).getBytes() : content);
    return (new ByteArrayInputStream(conteudo));
}

From source file:clients.Client1.java

License:Apache License

public String fileOverSoap(String endpoint, String file) {
    Service service = null;//ww  w.  ja  v  a2  s .  c  o m
    Call call = null;
    String result = null;
    File f = new File(file);
    try {
        service = new Service();
        call = (Call) service.createCall();
        call.setTargetEndpointAddress(new URL(endpoint + "TestWS"));
        call.setOperationName(new QName("getFileOverSoap"));
        FileInputStream fileStream = new FileInputStream(file);
        InputStream in = fileStream;

        FileOutputStream fileOut = new FileOutputStream(file + ".tmp");

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] tmp = new byte[5 * 1024 * 1024];
        int len = 0;
        String data = "";
        byte[] tmp2;
        while ((len = in.read(tmp)) != -1) {
            //                data = Base64.encodeBytes(tmp,0,len);

            baos.write(tmp, 0, len);

            //                System.out.println("Unencoded------------: "+new String(baos.toByteArray()));
            data = Base64.encodeBytes(baos.toByteArray());
            //                System.out.println("Base64---------------: "+data);
            tmp2 = Base64.decode(data);
            //                System.out.println("Dencoded-------------: " + new String(tmp2) );
            //                System.out.println("Len------------------: " + len);

            fileOut.write(tmp2);

            Object[] args = { new String(f.getName()), data.getBytes() };
            result = (String) call.invoke(args);
            baos.reset();
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return result;
}

From source file:clients.Client1.java

License:Apache License

public SOAPMessage createSoapMessage(String method, String endpoint, String file) {

    SOAPMessage message = null;//from w ww  .  j a  va  2 s. c  om
    try {

        MessageFactory mf = MessageFactory.newInstance();
        message = mf.createMessage();

        SOAPPart soapPart = message.getSOAPPart();
        SOAPEnvelope envelope = soapPart.getEnvelope();
        envelope.addNamespaceDeclaration("xsi", "http://www.w3.org/2001/XMLSchema-instance");
        envelope.getHeader().detachNode();

        SOAPBody body = envelope.getBody();
        SOAPElement bodyElement = body.addChildElement(method);

        SOAPElement arg0 = bodyElement.addChildElement("arg0");
        arg0.setAttribute("xsi:type", "SOAP-ENC:string");
        arg0.addTextNode("SomeFile");

        SOAPElement arg1 = bodyElement.addChildElement("arg1");
        arg1.setAttribute("xsi:type", "SOAP-ENC:string");
        arg1.addTextNode("/home/alogo/testTrans/client/");

        SOAPElement arg2 = bodyElement.addChildElement("arg2");
        arg2.setAttribute("xsi:type", "SOAP-ENC:base64Bin");
        String de = Base64.encodeBytes("HEEEEEEEEEEEEELOOOOOOOOOOOOOO".getBytes());
        arg2.setNodeValue("83698670828586708285867082858670828586778448578084485780844857808448578084485661");
        //            arg2.addTextNode("83698670828586708285867082858670828586778448578084485780844857808448578084485661");     
        //           "83698670828586708285867082858670828586778448578084485780844857808448578084485661"
        //            "U0VWRlJVVkZSVVZGUlVWRlJVVk1UMDlQVDA5UFQwOVBUMDlQVDA4PQ=="
        //            for(int i=0;i<de.getBytes().length;i++){
        //                System.out.print(de.getBytes()[i]);
        //            }

        //            FileInputStream fileStream = new FileInputStream(file);
        byte[] tmp = new byte[1024];
        int len = 0;

        //            while ((len = fileStream.read(tmp)) != -1) {

        //                arg0.addTextNode(Base64.encode(tmp,0,len));
        //                System.out.println(Base64.encode(tmp,0,len));
        //                data.addTextNode("data");
        //            }

        //            arg0.setAttribute("xsi:type","SOAP-ENC:string");
        //            arg0.addTextNode("AAAAAAAAAAAAAAAA");
        //
        //            SOAPElement arg1 = bodyElement.addChildElement("arg1");
        //            arg1.setAttribute("xsi:type","SOAP-ENC:string");
        //            arg1.addTextNode("BBBBBBBBBBBBBBBBBBBB");

        MimeHeaders hd = message.getMimeHeaders();
        hd.addHeader("SOAPAction", "http://just-a-uri.org/");

        message.saveChanges();

        //            message.getSOAPPart().getContent().

        System.out.println("REQUEST:");
        //            Display Request Message
        displayMessage(message);

        System.out.println("\n\n");

        SOAPConnection conn = SOAPConnectionFactory.newInstance().createConnection();
        //            SOAPMessage response = conn.call(message, endpoint);
        //            
        //            System.out.println("RESPONSE:");
        //            displayMessage(response);
        //            
        //            result = (String)call.invoke(args);

        //            java.text.MessageFormat d = new java.text.MessageFormat("PassernsadcsS");
        //            String soapMesgTemplate = d.format(args);
        //            System.out.println(soapMesgTemplate);

    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return null;
}

From source file:com.avbravo.avbravoutils.crypto.CryptoConverter.java

@Override
public String convertToDatabaseColumn(String ccNumber) {
    // do some encryption
    Key key = new SecretKeySpec(KEY, "AES");

    try {//from   ww  w .  j  a  v  a  2s. co m
        Cipher c = Cipher.getInstance(ALGORITHM);
        c.init(Cipher.ENCRYPT_MODE, key);
        return Base64.encodeBytes(c.doFinal(ccNumber.getBytes()));
    } catch (InvalidKeyException | NoSuchAlgorithmException | BadPaddingException | IllegalBlockSizeException
            | NoSuchPaddingException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.cruta.hecas.generales.CryptoConverter.java

@Override
public String convertToDatabaseColumn(String ccNumber) {
    // do some encryption
    Key key = new SecretKeySpec(KEY, "AES");
    try {/*from w w  w  .  j  a v a  2 s  .  c om*/
        Cipher c = Cipher.getInstance(ALGORITHM);
        c.init(Cipher.ENCRYPT_MODE, key);
        return Base64.encodeBytes(c.doFinal(ccNumber.getBytes()));
    } catch (InvalidKeyException | NoSuchAlgorithmException | BadPaddingException | IllegalBlockSizeException
            | NoSuchPaddingException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.gst.infrastructure.documentmanagement.api.ImagesApiResource.java

License:Apache License

/**
 * Returns a base 64 encoded client image Data URI
 *//*from ww w  .  j av  a  2s  .  c  om*/
@GET
@Consumes({ MediaType.TEXT_PLAIN, MediaType.TEXT_HTML, MediaType.APPLICATION_JSON })
@Produces({ MediaType.TEXT_PLAIN })
public Response retrieveImage(@PathParam("entity") final String entityName,
        @PathParam("entityId") final Long entityId, @QueryParam("maxWidth") final Integer maxWidth,
        @QueryParam("maxHeight") final Integer maxHeight, @QueryParam("output") final String output) {
    validateEntityTypeforImage(entityName);
    if (ENTITY_TYPE_FOR_IMAGES.CLIENTS.toString().equalsIgnoreCase(entityName)) {
        this.context.authenticatedUser().validateHasReadPermission("CLIENTIMAGE");
    } else if (ENTITY_TYPE_FOR_IMAGES.STAFF.toString().equalsIgnoreCase(entityName)) {
        this.context.authenticatedUser().validateHasReadPermission("STAFFIMAGE");
    }

    if (output != null && (output.equals("octet") || output.equals("inline_octet"))) {
        return downloadClientImage(entityName, entityId, maxWidth, maxHeight, output);
    }

    final ImageData imageData = this.imageReadPlatformService.retrieveImage(entityName, entityId);

    // TODO: Need a better way of determining image type
    String imageDataURISuffix = ContentRepositoryUtils.IMAGE_DATA_URI_SUFFIX.JPEG.getValue();
    if (StringUtils.endsWith(imageData.location(),
            ContentRepositoryUtils.IMAGE_FILE_EXTENSION.GIF.getValue())) {
        imageDataURISuffix = ContentRepositoryUtils.IMAGE_DATA_URI_SUFFIX.GIF.getValue();
    } else if (StringUtils.endsWith(imageData.location(),
            ContentRepositoryUtils.IMAGE_FILE_EXTENSION.PNG.getValue())) {
        imageDataURISuffix = ContentRepositoryUtils.IMAGE_DATA_URI_SUFFIX.PNG.getValue();
    }

    final String clientImageAsBase64Text = imageDataURISuffix
            + Base64.encodeBytes(imageData.getContentOfSize(maxWidth, maxHeight));
    return Response.ok(clientImageAsBase64Text).build();
}

From source file:com.jk.framework.application.config.CommonsConfigManager.java

License:Apache License

/**
 * Encode./*  w  w  w  .j a va  2s  .c  o  m*/
 *
 * @param string
 *            the string
 * @return the string
 */
public static String encode(final String string) {
    return Base64.encodeBytes(string.getBytes());
}

From source file:com.jk.framework.application.config.CommonsConfigManager.java

License:Apache License

/**
 * Sets the property./*from  ww w  .  j a v  a2 s .co  m*/
 *
 * @param name
 *            the name
 * @param value
 *            the value
 * @param encoded
 *            the encoded
 */
public void setProperty(final String name, String value, final boolean encoded) {
    if (encoded) {
        value = Base64.encodeBytes(value.getBytes());
    }
    this.prop.setProperty(fixKey(name), value);
}