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

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

Introduction

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

Prototype

public Base64InputStream(InputStream in) 

Source Link

Usage

From source file:org.n52.wps.io.test.datahandler.parser.GTBinZippedWKT64ParserTest.java

public void testParser() {

    if (!isDataHandlerActive()) {
        return;/* w  ww .  j av  a  2s  .  c om*/
    }

    String testFilePath = projectRoot + "/52n-wps-io-geotools/src/test/resources/wktgeometries.base64.zip";

    try {
        testFilePath = URLDecoder.decode(testFilePath, "UTF-8");
    } catch (UnsupportedEncodingException e1) {
        fail(e1.getMessage());
    }

    String[] mimetypes = dataHandler.getSupportedFormats();

    InputStream input = null;

    for (String mimetype : mimetypes) {

        try {

            input = new Base64InputStream(new FileInputStream(new File(testFilePath)));
        } catch (FileNotFoundException e) {
            fail(e.getMessage());
        }

        GTVectorDataBinding theBinding = dataHandler.parse(input, mimetype, "");

        assertNotNull(theBinding.getPayload());
        assertTrue(!theBinding.getPayload().isEmpty());

        FeatureCollection<?, ?> collection = theBinding.getPayload();

        FeatureIterator<?> featureIterator = collection.features();

        while (featureIterator.hasNext()) {
            Feature f = featureIterator.next();

            System.out.println(f.getDefaultGeometryProperty());
        }

        assertTrue(theBinding.getPayloadAsShpFile().exists());

    }

}

From source file:org.n52.wps.server.request.strategy.WCS111XMLEmbeddedBase64OutputReferenceStrategy.java

@Override
public ReferenceInputStream fetchData(InputType input) throws ExceptionReport {

    String dataURLString = input.getReference().getHref();

    String schema = input.getReference().getSchema();
    String encoding = input.getReference().getEncoding();
    String mimeType = input.getReference().getMimeType();

    try {/*from w w  w.  j  av a 2  s  .  c o  m*/
        URL dataURL = new URL(dataURLString);
        // Do not give a direct inputstream.
        // The XML handlers cannot handle slow connections
        URLConnection conn = dataURL.openConnection();
        conn.setRequestProperty("Accept-Encoding", "gzip");
        conn.setRequestProperty("Content-type", "multipart/mixed");
        //Handling POST with referenced document
        if (input.getReference().isSetBodyReference()) {
            String bodyReference = input.getReference().getBodyReference().getHref();
            URL bodyReferenceURL = new URL(bodyReference);
            URLConnection bodyReferenceConn = bodyReferenceURL.openConnection();
            bodyReferenceConn.setRequestProperty("Accept-Encoding", "gzip");
            InputStream referenceInputStream = retrievingZippedContent(bodyReferenceConn);
            IOUtils.copy(referenceInputStream, conn.getOutputStream());
        }
        //Handling POST with inline message
        else if (input.getReference().isSetBody()) {
            conn.setDoOutput(true);

            input.getReference().getBody().save(conn.getOutputStream());
        }
        InputStream inputStream = retrievingZippedContent(conn);

        BufferedReader bRead = new BufferedReader(new InputStreamReader(inputStream));

        String line = "";

        //boundary between different content types
        String boundary = "";

        boolean boundaryFound = false;

        boolean encodedImagepart = false;

        String encodedImage = "";

        //e.g. base64
        String contentTransferEncoding = "";

        String imageContentType = "";

        int boundaryCount = 0;

        while ((line = bRead.readLine()) != null) {

            if (line.contains("boundary")) {
                boundary = line.substring(line.indexOf("\"") + 1, line.lastIndexOf("\""));
                boundaryFound = true;
                continue;
            }
            if (boundaryFound) {
                if (line.contains(boundary)) {
                    boundaryCount++;
                    continue;
                }
            }

            if (encodedImagepart) {
                encodedImage = encodedImage.concat(line);
            }
            //is the image always the third part?!
            else if (boundaryCount == 2) {
                if (line.contains("Content-Type")) {
                    imageContentType = line.substring(line.indexOf(":") + 1).trim();
                } else if (line.contains("Content-Transfer-Encoding")) {
                    contentTransferEncoding = line.substring(line.indexOf(":") + 1).trim();
                } else if (line.contains("Content-ID")) {
                    /*   just move further one line (which is hopefully empty)
                     *    and start parsing the encoded image             
                     */
                    line = bRead.readLine();
                    encodedImagepart = true;
                }
            }

        }

        return new ReferenceInputStream(
                new Base64InputStream(new ByteArrayInputStream(encodedImage.getBytes())), imageContentType,
                null); // encoding is null since encoding was removed
    } catch (RuntimeException e) {
        throw new ExceptionReport("Error occured while parsing XML", ExceptionReport.NO_APPLICABLE_CODE, e);
    } catch (MalformedURLException e) {
        String inputID = input.getIdentifier().getStringValue();
        throw new ExceptionReport(
                "The inputURL of the execute is wrong: inputID: " + inputID + " | dataURL: " + dataURLString,
                ExceptionReport.INVALID_PARAMETER_VALUE);
    } catch (IOException e) {
        String inputID = input.getIdentifier().getStringValue();
        throw new ExceptionReport("Error occured while receiving the complexReferenceURL: inputID: " + inputID
                + " | dataURL: " + dataURLString, ExceptionReport.INVALID_PARAMETER_VALUE);
    }
}

From source file:org.obm.push.mail.mime.MimePartImpl.java

@Override
public InputStream decodeMimeStream(InputStream rawStream) {
    if (QUOTED_PRINTABLE.equalsIgnoreCase(getContentTransfertEncoding())) {
        return new QuotedPrintableInputStream(rawStream);
    } else if (BASE64.equalsIgnoreCase(getContentTransfertEncoding())) {
        return new Base64InputStream(rawStream);
    } else {/*from   w w w .  j a v  a2 s  . co m*/
        return rawStream;
    }
}

From source file:org.sonatype.sisu.encryptor.RsaAesEncryptor.java

protected PublicKey readPublicKey(InputStream keyInput) throws IOException, GeneralSecurityException {
    InputStream input = new Base64InputStream(keyInput);
    byte[] encKey = IOUtil.toByteArray(input);
    IOUtil.close(input);/*www.  j a va  2s  .  c  om*/

    X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(encKey);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);

    return pubKey;
}

From source file:org.sonatype.sisu.encryptor.RsaAesEncryptor.java

protected PrivateKey readPrivateKey(InputStream keyInput) throws IOException, GeneralSecurityException {
    InputStream input = new Base64InputStream(keyInput);
    byte[] encKey = IOUtil.toByteArray(input);
    IOUtil.close(input);//from  w ww  .  ja va2 s. com

    PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encKey);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);

    return privateKey;
}

From source file:org.sonatype.sisu.encryptor.RsaAesEncryptor.java

public void decrypt(InputStream encryptedInput, OutputStream plainOutput, PrivateKey key)
        throws IOException, GeneralSecurityException {
    byte[] encryptedKey = new byte[KEY_SIZE];
    Base64InputStream input = new Base64InputStream(encryptedInput);
    input.read(encryptedKey);//from   w w w  .  ja  v a 2s  .  c  o m

    byte[] encryptedData = IOUtil.toByteArray(input);
    IOUtil.close(input);

    byte[] raw = getCipher("RSA/ECB/PKCS1Padding", key, javax.crypto.Cipher.DECRYPT_MODE).doFinal(encryptedKey);

    // useful when debugging but can't be left uncommented due to NEXUS-2530
    // if ( getLogger().isDebugEnabled() )
    // {
    // log.debug( "enc key: " + new String( Base64.encodeBase64( encryptedKey ) ) );
    // log.debug( "enc data: " + new String( Base64.encodeBase64( encryptedData ) ) );
    // log.debug( "after decrypt: " + new String( Base64.encodeBase64( raw ) ) );
    // }

    SecretKeySpec aesKey = new SecretKeySpec(raw, "AES");

    byte[] data = getCipher("AES", aesKey, Cipher.DECRYPT_MODE).doFinal(encryptedData);

    IOUtil.copy(data, plainOutput);
    plainOutput.flush();
}

From source file:org.springfield.lou.servlet.LouServlet.java

private String handleFileUpload(HttpServletRequest request) {
    System.out.println("HANDLE FILE UPLOAD");
    try {/*from www .j  av a  2  s .  c o  m*/
        String targetid = request.getParameter("targetid");
        System.out.println("TARGETID UPLOAD=" + targetid);
        String screenid = request.getParameter("screenid");
        String cfilename = request.getParameter("cfilename");
        System.out.println("CFILENAME=" + cfilename);
        String cfilesize = request.getParameter("cfilesize");
        System.out.println("CFILESIZE=" + cfilesize);

        Html5ApplicationInterface app = null;
        String url = request.getRequestURI();
        int pos = url.indexOf("/domain/");
        if (pos != -1) {
            String tappname = url.substring(pos);
            app = ApplicationManager.instance().getApplication(tappname);
        }
        Screen eventscreen = app.getScreen(screenid);

        if (eventscreen == null)
            return null;

        String method = eventscreen.getModel()
                .getProperty("/screen['upload']/target['" + targetid + "']/method");
        System.out.println("METHOD=" + method);

        String destpath = eventscreen.getModel()
                .getProperty("/screen['upload']/target['" + targetid + "']/destpath");
        System.out.println("DESTPATH=" + destpath + " T=" + targetid);
        if (destpath == null || destpath.equals("")) {
            setUploadError(eventscreen, targetid, "destpath not set");
            return null;
        }

        String destname_prefix = eventscreen.getModel()
                .getProperty("/screen['upload']/target['" + targetid + "']/destname_prefix");
        if (destname_prefix == null || destname_prefix.equals("")) {
            setUploadError(eventscreen, targetid, "destname_prefix not set");
            return null;
        }

        String filetype = eventscreen.getModel()
                .getProperty("/screen['upload']/target['" + targetid + "']/filetype");
        if (filetype == null || filetype.equals("")) {
            setUploadError(eventscreen, targetid, "filetype not set");
            return null;
        }

        String fileext = eventscreen.getModel()
                .getProperty("/screen['upload']/target['" + targetid + "']/fileext");
        if (fileext == null || fileext.equals("")) {
            setUploadError(eventscreen, targetid, "fileext not set");
            return null;
        }

        String checkupload = eventscreen.getModel()
                .getProperty("/screen['upload']/target['" + targetid + "']/checkupload");
        if (checkupload == null || checkupload.equals("")) {
            setUploadError(eventscreen, targetid, "checkupload not set");
            return null;
        }

        String storagehost = eventscreen.getModel()
                .getProperty("/screen['upload']/target['" + targetid + "']/storagehost");
        if (storagehost == null || storagehost.equals("")) {
            setUploadError(eventscreen, targetid, "storagehost not set");
            return null;
        }

        String destname_type = eventscreen.getModel()
                .getProperty("/screen['upload']/target['" + targetid + "']/destname_type");
        if (destname_type == null || destname_type.equals("")) {
            setUploadError(eventscreen, targetid, "destname_type not set");
            return null;
        }

        String publicpath = eventscreen.getModel()
                .getProperty("/screen['upload']/target['" + targetid + "']/publicpath");
        if (publicpath == null || publicpath.equals("")) {
            setUploadError(eventscreen, targetid, "publicpath not set");
            return null;
        }

        // here we can check if its a valid upload based on filename and other specs and kill if needed, also map real extension 

        fileext = getValidExtension(fileext, cfilename);
        if (fileext == null)
            return null; // kill the request its not a valid format

        if (method.equals("s3amazon")) {
            String bucketname = eventscreen.getModel()
                    .getProperty("/screen['upload']/target['" + targetid + "']/bucketname");
            if (bucketname == null || bucketname.equals("")) {
                setUploadError(eventscreen, targetid, "bucketname not set");
                return null;
            }

            AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
                    .withCredentials(new EnvironmentVariableCredentialsProvider()).build();
            String filename = "unknown";
            int storageport = 22;

            if (destname_type.equals("epoch")) {
                filename = destpath + destname_prefix + "" + new Date().getTime();
            }

            String publicurl = publicpath + bucketname + "/" + filename + "." + fileext;

            FsPropertySet ps = new FsPropertySet(); // we will use this to send status reports back
            ps.setProperty("action", "start");
            ps.setProperty("progress", "0");
            ps.setProperty("cfilename", cfilename);
            ps.setProperty("url", publicurl);
            eventscreen.getModel().setProperties("/screen/upload/" + targetid, ps);

            try {
                InputStream inst = request.getInputStream();
                int read = 0;
                int readtotal = 0;
                int b;
                while ((b = inst.read()) != 44) {
                    // skip the base64 tagline, not sure how todo this better
                }

                Base64InputStream b64i = new Base64InputStream(inst);

                //System.out.println("Uploading a new object to S3 from a stream "+bucketname+"/"+filename+"."+fileext);

                ObjectMetadata metadata = new ObjectMetadata();
                metadata.setContentType(filetype + "/" + fileext);

                PutObjectRequest or = new PutObjectRequest(bucketname, filename + "." + fileext, b64i,
                        metadata);

                or.setGeneralProgressListener(new UploadProgressListener(eventscreen.getModel(), publicurl,
                        cfilename, cfilesize, targetid));
                s3Client.putObject(or);

            } catch (AmazonServiceException ase) {
                ase.printStackTrace();
            }
            ps.setProperty("action", "done");
            ps.setProperty("progress", "100");
            ps.setProperty("cfilename", cfilename);
            ps.setProperty("url", publicurl);

            eventscreen.getModel().setProperties("/screen/upload/" + targetid, ps);
            return bucketname + "/" + filename + "." + fileext;

        } else if (method.equals("scp")) {
            String pemfile = eventscreen.getModel()
                    .getProperty("/screen['upload']/target['" + targetid + "']/pemfile");
            if (destpath == null || destpath.equals("")) {
                setUploadError(eventscreen, targetid, "destpath not set");
                return null;
            }

            String storagename = eventscreen.getModel()
                    .getProperty("/screen['upload']/target['" + targetid + "']/storagename");
            if (storagename == null || storagehost.equals("")) {
                setUploadError(eventscreen, targetid, "storagename not set");
                return null;
            }

            String filename = "unknown";
            int storageport = 22;

            if (destname_type.equals("epoch")) {
                filename = destname_prefix + "" + new Date().getTime();
            }

            String publicurl = publicpath + filename + "." + fileext;

            FsPropertySet ps = new FsPropertySet(); // we will use this to send status reports back
            ps.setProperty("action", "start");
            ps.setProperty("progress", "0");
            ps.setProperty("url", publicurl);
            eventscreen.getModel().setProperties("/screen/upload/" + targetid, ps);

            JSch jsch = new JSch();
            jsch.addIdentity(pemfile);
            jsch.setConfig("StrictHostKeyChecking", "no");
            Session session = jsch.getSession(storagename, storagehost, storageport);
            session.connect();
            Channel channel = session.openChannel("sftp");

            channel.connect();
            ChannelSftp channelSftp = (ChannelSftp) channel;
            channelSftp.cd(destpath);

            InputStream inst = request.getInputStream();
            int read = 0;
            int readtotal = 0;
            int b;
            while ((b = inst.read()) != 44) {
                // skip the base64 tagline, not sure how todo this better
            }
            Base64InputStream b64i = new Base64InputStream(inst);

            channelSftp.put(b64i, filename + "." + fileext);

            ps.setProperty("action", "done");
            ps.setProperty("progress", "100");
            ps.setProperty("url", publicurl);
            eventscreen.getModel().setProperties("/screen/upload/" + targetid, ps);
            return filename + "." + fileext;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.springframework.cloud.aws.messaging.support.converter.ObjectMessageConverter.java

@Override
public Object convertFromInternal(Message<?> message, Class<?> targetClass) {
    String messagePayload = message.getPayload().toString();
    byte[] rawContent = messagePayload.getBytes(this.encoding);
    if (!(Base64.isBase64(rawContent))) {
        throw new MessageConversionException("Error converting payload '" + messagePayload
                + "' because it is not a valid base64 encoded stream!", null);
    }// www. ja  v  a2s  .  c o  m
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(rawContent);
    Base64InputStream base64InputStream = new Base64InputStream(byteArrayInputStream);
    Serializable result = null;
    ObjectInputStream objectInputStream = null;
    try {
        objectInputStream = new ObjectInputStream(base64InputStream);
        result = (Serializable) objectInputStream.readObject();
    } catch (ClassNotFoundException e) {
        throw new MessageConversionException(
                "Error loading class from message payload, make sure class is in classpath!", e);
    } catch (IOException e) {
        throw new MessageConversionException("Error reading payload from binary representation", e);
    } finally {
        if (objectInputStream != null) {
            try {
                objectInputStream.close();
            } catch (IOException e) {
                LOGGER.warn("Error closing object output stream while reading message payload", e);
            }
        }
    }

    return result;
}

From source file:org.talend.designer.runprocess.java.JavaProcessor.java

@Override
public void generateEsbFiles() throws ProcessorException {
    List<? extends INode> graphicalNodes = process.getGraphicalNodes(); // process.getGeneratingNodes();

    try {/*from w w w . j  ava 2 s  .c o  m*/
        IPath jobPackagePath = getSrcCodePath().removeLastSegments(1);
        IFolder jobPackageFolder = this.getCodeProject().getFolder(jobPackagePath);
        IFolder wsdlsPackageFolder = jobPackageFolder.getFolder("wsdl"); //$NON-NLS-1$
        if (wsdlsPackageFolder.exists()) {
            wsdlsPackageFolder.delete(true, null);
        }

        for (INode node : graphicalNodes) {
            if ("tESBConsumer".equals(node.getComponent().getName()) && node.isActivate()) { //$NON-NLS-1$
                // retrieve WSDL content (compressed-n-encoded) -> zip-content.-> wsdls.(first named main.wsdl)
                String wsdlContent = (String) node.getPropertyValue("WSDL_CONTENT"); //$NON-NLS-1$
                String uniqueName = node.getUniqueName();
                if (null != uniqueName && null != wsdlContent && !wsdlContent.trim().isEmpty()) {

                    // configure decoding and uncompressing
                    InputStream wsdlStream = new BufferedInputStream(new InflaterInputStream(
                            new Base64InputStream(new ByteArrayInputStream(wsdlContent.getBytes()))));

                    if (!wsdlsPackageFolder.exists()) {
                        wsdlsPackageFolder.create(true, true, null);
                    }
                    // generate WSDL file
                    if (checkIsZipStream(wsdlStream)) {

                        ZipInputStream zipIn = new ZipInputStream(wsdlStream);
                        ZipEntry zipEntry = null;

                        while ((zipEntry = zipIn.getNextEntry()) != null) {
                            String outputName = zipEntry.getName();
                            if ("main.wsdl".equals(outputName)) { //$NON-NLS-1$
                                outputName = uniqueName + ".wsdl"; //$NON-NLS-1$
                            }
                            IFile wsdlFile = wsdlsPackageFolder.getFile(outputName);
                            if (!wsdlFile.exists()) {
                                // cause create file will do a close. add a warp to ignore close.
                                InputStream unCloseIn = new FilterInputStream(zipIn) {

                                    @Override
                                    public void close() throws IOException {
                                    };
                                };

                                wsdlFile.create(unCloseIn, true, null);
                            }
                            zipIn.closeEntry();
                        }
                        zipIn.close();
                    } else {
                        IFile wsdlFile = wsdlsPackageFolder.getFile(uniqueName + ".wsdl"); //$NON-NLS-1$
                        wsdlFile.create(wsdlStream, true, null);
                    }
                }
            }
        }
    } catch (CoreException e) {
        if (e.getStatus() != null && e.getStatus().getException() != null) {
            ExceptionHandler.process(e.getStatus().getException());
        }
        throw new ProcessorException(Messages.getString("Processor.tempFailed"), e); //$NON-NLS-1$
    } catch (IOException e) {
        throw new ProcessorException(Messages.getString("Processor.tempFailed"), e); //$NON-NLS-1$
    }

    boolean samEnabled = false;
    boolean slEnabled = false;
    for (INode node : graphicalNodes) {
        if (node.isActivate()) {
            final String nodeName = node.getComponent().getName();
            Object slValue = null, samValue = null;
            if ("tESBConsumer".equals(nodeName) //$NON-NLS-1$
                    || "tRESTClient".equals(nodeName) //$NON-NLS-1$
                    || "tRESTRequest".equals(nodeName) //$NON-NLS-1$
                    || "cCXFRS".equals(nodeName)) { //$NON-NLS-1$
                if (!slEnabled) {
                    slValue = node.getPropertyValue("SERVICE_LOCATOR"); //$NON-NLS-1$
                }
                if (!samEnabled) {
                    samValue = node.getPropertyValue("SERVICE_ACTIVITY_MONITOR"); //$NON-NLS-1$
                }
            } else if ("cCXF".equals(nodeName)) { //$NON-NLS-1$
                if (!slEnabled) {
                    slValue = node.getPropertyValue("ENABLE_SL"); //$NON-NLS-1$
                }
                if (!samEnabled) {
                    samValue = node.getPropertyValue("ENABLE_SAM"); //$NON-NLS-1$
                }
            }
            if (null != slValue) {
                slEnabled = (Boolean) slValue;
            }
            if (null != samValue) {
                samEnabled = (Boolean) samValue;
            }
            if (samEnabled && slEnabled) {
                break;
            }
        }
    }

    if (samEnabled || slEnabled) {
        File esbConfigsSourceFolder = EsbConfigUtils.getEclipseEsbFolder();
        if (!esbConfigsSourceFolder.exists()) {
            RunProcessPlugin.getDefault().getLog()
                    .log(new Status(IStatus.WARNING,
                            RunProcessPlugin.getDefault().getBundle().getSymbolicName(),
                            "ESB configuration folder does not exists - " + esbConfigsSourceFolder.toURI())); //$NON-NLS-1$
            return;
        }
        ITalendProcessJavaProject tProcessJvaProject = this.getTalendJavaProject();
        if (tProcessJvaProject == null) {
            return;
        }
        IFolder esbConfigsTargetFolder = tProcessJvaProject.getResourcesFolder();

        // add SAM config file to classpath
        if (samEnabled) {
            copyEsbConfigFile(esbConfigsSourceFolder, esbConfigsTargetFolder, "agent.properties"); //$NON-NLS-1$
        }

        // add SL config file to classpath
        if (slEnabled) {
            copyEsbConfigFile(esbConfigsSourceFolder, esbConfigsTargetFolder, "locator.properties"); //$NON-NLS-1$
        }
    }
}

From source file:org.woodwardbernsteinprotocol.protocol.DirectTransfer.java

@Override
public Tip parse() throws IOException, ClassNotFoundException {
    InputStream data = new Base64InputStream(reader);
    Tip tip = new Tip();
    tip.parse(data);// w  w  w . j a  v  a 2  s  .  c o  m
    return tip;
}