Example usage for org.apache.commons.codec.binary Base64 Base64

List of usage examples for org.apache.commons.codec.binary Base64 Base64

Introduction

In this page you can find the example usage for org.apache.commons.codec.binary Base64 Base64.

Prototype

public Base64() 

Source Link

Document

Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.

Usage

From source file:es.logongas.ix3.web.security.impl.WebSessionSidStorageImplAbstractJws.java

private String serialize(Serializable serializable) {
    try {//w  ww  .j a va2 s  . c  om
        Base64 base64 = new Base64();

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ObjectOutputStream so = new ObjectOutputStream(outputStream);
        so.writeObject(serializable);
        so.flush();

        return base64.encodeAsString(outputStream.toByteArray());
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:fi.aalto.seqpig.io.BamStorer.java

public BamStorer(String samfileheaderfilename) {

    String str = "";
    this.samfileheader = "";

    try {//from  w ww . j a va  2 s. c  o m
        Configuration conf = UDFContext.getUDFContext().getJobConf();

        // see https://issues.apache.org/jira/browse/PIG-2576
        if (conf == null || conf.get("mapred.task.id") == null) {
            // we are running on the frontend
            decodeSAMFileHeader();
            return;
        }

        URI uri = new URI(samfileheaderfilename);
        FileSystem fs = FileSystem.get(uri, conf);

        BufferedReader in = new BufferedReader(new InputStreamReader(fs.open(new Path(samfileheaderfilename))));

        while (true) {
            str = in.readLine();

            if (str == null)
                break;
            else
                this.samfileheader += str + "\n";
        }

        in.close();
    } catch (Exception e) {
        System.out.println("ERROR: could not read BAM header from file " + samfileheaderfilename);
        System.out.println("exception was: " + e.toString());
    }

    try {
        Base64 codec = new Base64();
        Properties p = UDFContext.getUDFContext().getUDFProperties(this.getClass());

        ByteArrayOutputStream bstream = new ByteArrayOutputStream();
        ObjectOutputStream ostream = new ObjectOutputStream(bstream);
        ostream.writeObject(this.samfileheader);
        ostream.close();
        String datastr = codec.encodeBase64String(bstream.toByteArray());
        p.setProperty("samfileheader", datastr);
    } catch (Exception e) {
        System.out.println("ERROR: Unable to store SAMFileHeader in BamStorer!");
    }

    this.samfileheader_decoded = getSAMFileHeader();
}

From source file:com.sap.dirigible.runtime.scripting.AbstractScriptExecutor.java

protected void registerDefaultVariables(HttpServletRequest request, HttpServletResponse response, Object input,
        Map<Object, Object> executionContext, IRepository repository, Object scope) {
    // put the execution context
    registerDefaultVariable(scope, "context", executionContext); //$NON-NLS-1$
    // put the system out
    registerDefaultVariable(scope, "out", System.out); //$NON-NLS-1$
    // put the default data source
    DataSource dataSource = null;
    if (repository instanceof DBRepository) {
        dataSource = ((DBRepository) repository).getDataSource();
    } else {//  ww w .j a va 2s. com
        dataSource = RepositoryFacade.getInstance().getDataSource();
    }
    registerDefaultVariable(scope, "datasource", dataSource); //$NON-NLS-1$
    // put request
    registerDefaultVariable(scope, "request", request); //$NON-NLS-1$
    // put response
    registerDefaultVariable(scope, "response", response); //$NON-NLS-1$
    // put repository
    registerDefaultVariable(scope, "repository", repository); //$NON-NLS-1$
    // put mail sender
    MailSender mailSender = new MailSender();
    registerDefaultVariable(scope, "mail", mailSender); //$NON-NLS-1$
    // put Apache Commons IOUtils
    IOUtils ioUtils = new IOUtils();
    registerDefaultVariable(scope, "io", ioUtils); //$NON-NLS-1$
    // put Apache Commons HttpClient and related classes wrapped with a
    // factory like HttpUtils
    HttpUtils httpUtils = new HttpUtils();
    registerDefaultVariable(scope, "http", httpUtils); //$NON-NLS-1$
    // put Apache Commons Codecs
    Base64 base64Codec = new Base64();
    registerDefaultVariable(scope, "base64", base64Codec); //$NON-NLS-1$
    Hex hexCodec = new Hex();
    registerDefaultVariable(scope, "hex", hexCodec); //$NON-NLS-1$
    DigestUtils digestUtils = new DigestUtils();
    registerDefaultVariable(scope, "digest", digestUtils); //$NON-NLS-1$
    // standard URLEncoder and URLDecoder functionality
    URLUtils urlUtils = new URLUtils();
    registerDefaultVariable(scope, "url", urlUtils); //$NON-NLS-1$
    // user name
    registerDefaultVariable(scope, "user", RepositoryFacade.getUser(request)); //$NON-NLS-1$
    // file upload
    ServletFileUpload fileUpload = new ServletFileUpload(new DiskFileItemFactory());
    registerDefaultVariable(scope, "upload", fileUpload); //$NON-NLS-1$
    // UUID
    UUID uuid = new UUID(0, 0);
    registerDefaultVariable(scope, "uuid", uuid); //$NON-NLS-1$
    // the input from the execution chain if any
    registerDefaultVariable(scope, "input", input); //$NON-NLS-1$
    // DbUtils
    DbUtils dbUtils = new DbUtils(dataSource);
    registerDefaultVariable(scope, "db", dbUtils); //$NON-NLS-1$
    // EscapeUtils
    StringEscapeUtils stringEscapeUtils = new StringEscapeUtils();
    registerDefaultVariable(scope, "xss", stringEscapeUtils); //$NON-NLS-1$
    // Extension Manager
    ExtensionManager extensionManager = new ExtensionManager(repository, dataSource);
    registerDefaultVariable(scope, "extensionManager", extensionManager); //$NON-NLS-1$
    // Apache Lucene Indexer
    IndexerUtils indexerUtils = new IndexerUtils();
    registerDefaultVariable(scope, "indexer", indexerUtils); //$NON-NLS-1$
    // Mylyn Confluence Format
    WikiUtils wikiUtils = new WikiUtils();
    registerDefaultVariable(scope, "wiki", wikiUtils); //$NON-NLS-1$
    // Simple binary storage
    StorageUtils storageUtils = new StorageUtils(dataSource);
    registerDefaultVariable(scope, "storage", storageUtils); //$NON-NLS-1$
    // Simple file storage
    FileStorageUtils fileStorageUtils = new FileStorageUtils(dataSource);
    registerDefaultVariable(scope, "fileStorage", fileStorageUtils); //$NON-NLS-1$
    // Simple binary storage
    ConfigStorageUtils configStorageUtils = new ConfigStorageUtils(dataSource);
    registerDefaultVariable(scope, "config", configStorageUtils); //$NON-NLS-1$
    // XML to JSON and vice-versa
    XMLUtils xmlUtils = new XMLUtils();
    registerDefaultVariable(scope, "xml", xmlUtils); //$NON-NLS-1$

}

From source file:fi.aalto.seqpig.io.SamStorer.java

public SamStorer(String samfileheaderfilename) {

    String str = "";
    this.samfileheader = "";

    try {/*from   w  w  w.  j ava2  s .com*/
        Configuration conf = UDFContext.getUDFContext().getJobConf();

        // see https://issues.apache.org/jira/browse/PIG-2576
        if (conf == null || conf.get("mapred.task.id") == null) {
            // we are running on the frontend
            decodeSAMFileHeader();
            return;
        }

        URI uri = new URI(samfileheaderfilename);
        FileSystem fs = FileSystem.get(uri, conf);

        BufferedReader in = new BufferedReader(new InputStreamReader(fs.open(new Path(samfileheaderfilename))));

        while (true) {
            str = in.readLine();

            if (str == null)
                break;
            else
                this.samfileheader += str + "\n";
        }

        in.close();
    } catch (Exception e) {
        System.out.println("ERROR: could not read SAM header from file " + samfileheaderfilename);
        System.out.println("exception was: " + e.toString());
    }

    try {
        Base64 codec = new Base64();
        Properties p = UDFContext.getUDFContext().getUDFProperties(this.getClass());

        ByteArrayOutputStream bstream = new ByteArrayOutputStream();
        ObjectOutputStream ostream = new ObjectOutputStream(bstream);
        ostream.writeObject(this.samfileheader);
        ostream.close();

        String datastr = codec.encodeBase64String(bstream.toByteArray());
        p.setProperty("samfileheader", datastr);
    } catch (Exception e) {
        System.out.println("ERROR: Unable to store SAMFileHeader in BamStorer!");
    }

    this.samfileheader_decoded = getSAMFileHeader();
}

From source file:mx.bigdata.sat.cfd.CFDv2.java

public void verificar() throws Exception {
    String certStr = document.getCertificado();
    Base64 b64 = new Base64();
    byte[] cbs = b64.decode(certStr);

    X509Certificate cert = KeyLoaderFactory
            .createInstance(KeyLoaderEnumeration.PUBLIC_KEY_LOADER, new ByteArrayInputStream(cbs)).getKey();

    verificar(cert);//from ww  w .  j  ava 2 s .  co m
}

From source file:com.beetle.framework.util.OtherUtil.java

public static String strBase64Decode(String base64EncodeStr) {
    Base64 b64 = new Base64();
    byte[] b = b64.decode(base64EncodeStr.getBytes());
    return new String(b);
}

From source file:com.ge.apm.service.asset.AttachmentFileService.java

public Integer uploadBase64File(String fileString, String fileName) {
    fileString = fileString.substring(fileString.indexOf("base64,") + 7);
    Base64 decoder = new Base64();
    InputStream is = null;/*from w w  w.  ja v  a 2 s . c  o  m*/
    Integer returnId = 0;
    try {
        byte[] bytes = decoder.decode(fileString);
        for (int i = 0; i < bytes.length; ++i) {
            if (bytes[i] < 0) {// ?
                bytes[i] += 256;
            }
        }
        is = new ByteArrayInputStream(bytes);
        returnId = fileUploaddao.saveUploadFile(is, bytes.length, fileName);

    } catch (SQLException ex) {
        Logger.getLogger(AttachmentFileService.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException ex) {
                Logger.getLogger(CoreService.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    return returnId;
}

From source file:jlib.xml.XMLUtil.java

public static byte[] encode64(byte[] arrBytes) {
    Base64 base64 = new Base64();
    return base64.encode(arrBytes);
}

From source file:net.sf.smbt.touchosc.utils.TouchOSCUtils.java

public TouchOSCUtils() {
    base64Ref = new Base64();
}

From source file:com.viettel.hqmc.DAO.FilesExpandDAO.java

public String actionSignCA() throws IOException {
    boolean result = true;
    String base64Hash = "";
    String base64Hash0 = "";
    String certSerial = "";
    String fileId = "";
    String outPutFileFinal = "";
    String outPutFileFinal2 = "";
    String fileName = "";
    String fileToSign = "";
    String errorCode = "";
    SignPdfFile pdfSig = new SignPdfFile();
    try {// w  w w  .jav  a2  s. c om
        fileId = getRequest().getParameter("fileId");
        String rootCert = null, base64Certificate = null, certChain;
        Base64 decoder = new Base64();
        certChain = new String(decoder.decode(getRequest().getParameter("cert").replace("_", "+").getBytes()),
                "UTF-8");
        String sToFind = getRequest().getParameter("signType");
        String path = getRequest().getParameter("path");
        String[] pathArr = path.split(";");
        fileToSign = pathArr[0];
        fileName = pathArr[1];
        String[] chain;
        try {
            chain = certChain.split(",");
            rootCert = chain[1];
            base64Certificate = chain[0];
        } catch (Exception ex) {
            LogUtil.addLog(ex);//binhnt sonar a160901
            errorCode = "SI_001";
            result = false;
        }
        // hieptq update 150615
        if (base64Certificate == null) {
            errorCode = "SI_002";
            result = false;
        }
        X509Certificate x509Cert = null;
        X509Certificate x509CertChain = null;
        try {
            x509Cert = CertUtils.getX509Cert(base64Certificate);
            x509CertChain = CertUtils.getX509Cert(rootCert);
        } catch (Exception ex) {
            LogUtil.addLog(ex);//binhnt sonar a160901
            errorCode = "SI_003";
            result = false;
        }

        PDFServerClientSignature pdfSCS = new PDFServerClientSignature();
        ResourceBundle rb = ResourceBundle.getBundle("config");
        String TSA_LINK = rb.getString("tsaUrl");
        pdfSCS.setTSA_LINK(TSA_LINK);
        String checkOcspStr = rb.getString("checkOCSP");
        Long checkOCSP = Long.parseLong(checkOcspStr);
        try {
            certSerial = x509Cert.getSerialNumber().toString(16);
        } catch (Exception ex) {
            LogUtil.addLog(ex);//binhnt sonar a160901
            errorCode = "SI_004";
            result = false;
        }
        // hieptq update 160615 - check serial        
        String filePath = rb.getString("sign_temp_plugin");
        File f = new File(filePath);
        if (!f.exists()) {
            f.mkdirs();
        }
        outPutFileFinal = filePath + fileName;
        CaUserDAOHE ca = new CaUserDAOHE();
        boolean checkCaUser = true;
        if (!ca.checkCaSerial("SerialNumber:[" + certSerial + "]")) {
            errorCode = "SI_005";
            result = false;
        }
        try {
            if (checkOCSP == 1l) {
                OCSP.RevocationStatus.CertStatus status = checkRevocationStatus((X509Certificate) x509Cert,
                        (X509Certificate) x509CertChain);
                if (status != OCSP.RevocationStatus.CertStatus.GOOD) {
                    errorCode = "SI_006";
                    result = false;
                }
            }
        } catch (Exception ex) {
            LogUtil.addLog(ex);//binhnt sonar a160901
            errorCode = "SI_007";
            result = false;
        }
        if (checkCaUser) {
            String folderPath = ResourceBundleUtil.getString("sign_image");
            String linkImageSign = folderPath + getUserId() + ".png";
            String linkImageStamp = folderPath + "attpStamp.png";
            if ((linkImageSign == null && "".equals(linkImageSign))
                    || (linkImageStamp == null && "".equals(linkImageStamp))) {
                errorCode = "SI_008";
                result = false;
            }
            try {
                if ("PDHS".equals(sToFind)) {
                    // ky lanh dao
                    if (fileToSign == null && "".equals(fileToSign)) {
                        errorCode = "SI_009";
                        result = false;
                    }
                    sToFind = "<SI>";
                    SearchTextLocations ptl = new SearchTextLocations();
                    List local = ptl.searchLocation(sToFind, fileToSign, SearchTextLocations.SEARCH_TOPDOWN,
                            SearchTextLocations.FIND_ONE);
                    String location = "0;0;0";
                    int pageNumber, lx, ly;
                    if (local != null && local.size() > 0) {
                        location = local.get(0).toString();
                    }
                    String[] parts = location.split(";");
                    pageNumber = Integer.parseInt(parts[0]);
                    lx = (int) Float.parseFloat(parts[1]);
                    ly = (int) Float.parseFloat(parts[2]);
                    ly = convertLocation(ly);
                    base64Hash = pdfSig.createHash(fileToSign, outPutFileFinal, new Certificate[] { x509Cert },
                            pageNumber, linkImageSign, lx + 70, ly + 130, 120, 70, "LD");
                }
                if ("PDHS_VT".equals(sToFind)) {
                    // ky van thu
                    if (fileToSign == null && "".equals(fileToSign)) {
                        errorCode = "SI_010";
                        result = false;
                    }
                    String sToFindtemp = "<SI>";
                    SearchTextLocations ptl = new SearchTextLocations();
                    List local = ptl.searchLocation(sToFindtemp, fileToSign, SearchTextLocations.SEARCH_TOPDOWN,
                            SearchTextLocations.FIND_ONE);
                    String location = "0;0;0";
                    int pageNumber, lx, ly;
                    if (local != null && local.size() > 0) {
                        location = local.get(0).toString();
                    }
                    String[] parts = location.split(";");
                    pageNumber = Integer.parseInt(parts[0]);
                    lx = (int) Float.parseFloat(parts[1]);
                    ly = (int) Float.parseFloat(parts[2]);
                    ly = convertLocation(ly);
                    base64Hash = pdfSig.createHash(fileToSign, outPutFileFinal, new Certificate[] { x509Cert },
                            pageNumber, linkImageStamp, lx + 23, ly + 115, 90, 90, "VT");
                }
            } catch (Exception ex) {
                LogUtil.addLog(ex);//binhnt sonar a160901
                System.out.println("ERROR SI_012|" + ex.getMessage());
                errorCode = "SI_012";
                result = false;
            }

        } else {
            errorCode = "SI_013";
            result = false;
        }
    } catch (JsonSyntaxException ex) {
        LogUtil.addLog(ex);//binhnt sonar a160901
        errorCode = "SI_014";
        result = false;
    } catch (Exception ex) {
        LogUtil.addLog(ex);//binhnt sonar a160901
        errorCode = "SI_015";
        result = false;
    } finally {

    }
    List resultMessage = new ArrayList();
    if (result) {
        HttpServletRequest req = getRequest();
        HttpSession session = req.getSession();
        session.setAttribute("PDFSignature", pdfSig);
        resultMessage.add("1");
        resultMessage.add("Lu d liu thnh cng");
        resultMessage.add(base64Hash);
        resultMessage.add(certSerial);
        resultMessage.add(fileId);
        resultMessage.add(outPutFileFinal);
        resultMessage.add(fileName);
        resultMessage.add(base64Hash0);
        resultMessage.add(outPutFileFinal2);
    } else {
        resultMessage.add("0");
        resultMessage.add("Lu d liu khng thnh cng " + errorCode);
    }
    jsonDataGrid.setItems(resultMessage);
    return GRID_DATA;
}