List of usage examples for org.apache.commons.codec.binary Base64InputStream Base64InputStream
public Base64InputStream(InputStream in)
From source file:com.asakusafw.runtime.stage.input.StageInputDriver.java
@SuppressWarnings("rawtypes") private static List<StageInput> decode(Configuration conf, String encoded) throws IOException, ClassNotFoundException { assert conf != null; assert encoded != null; ByteArrayInputStream source = new ByteArrayInputStream(encoded.getBytes(ASCII)); DataInputStream input = new DataInputStream(new GZIPInputStream(new Base64InputStream(source))); long version = WritableUtils.readVLong(input); if (version != SERIAL_VERSION) { throw new IOException(MessageFormat.format("Invalid StageInput version: framework={0}, saw={1}", SERIAL_VERSION, version)); }//from w w w .ja va2s . co m String[] dictionary = WritableUtils.readStringArray(input); int inputListSize = WritableUtils.readVInt(input); List<StageInput> results = new ArrayList<>(); for (int inputListIndex = 0; inputListIndex < inputListSize; inputListIndex++) { String pathString = readEncoded(input, dictionary); String formatName = readEncoded(input, dictionary); String mapperName = readEncoded(input, dictionary); int attributeCount = WritableUtils.readVInt(input); Map<String, String> attributes = new HashMap<>(); for (int attributeIndex = 0; attributeIndex < attributeCount; attributeIndex++) { String keyString = readEncoded(input, dictionary); String valueString = readEncoded(input, dictionary); attributes.put(keyString, valueString); } Class<? extends InputFormat> formatClass = conf.getClassByName(formatName) .asSubclass(InputFormat.class); Class<? extends Mapper> mapperClass = conf.getClassByName(mapperName).asSubclass(Mapper.class); results.add(new StageInput(pathString, formatClass, mapperClass, attributes)); } return results; }
From source file:cloudeventbus.pki.CertificateUtils.java
private static void loadCertificates(Path path, Collection<Certificate> certificates) throws IOException { try (final InputStream fileIn = Files.newInputStream(path); final InputStream in = new Base64InputStream(fileIn)) { CertificateStoreLoader.load(in, certificates); }/*from w w w . j a v a2s .com*/ }
From source file:com.ibm.amc.demo.provider.AmcDemoCommands.java
@Override public void setFirmware(DeviceContext deviceContext, InputStream inputStream) throws InvalidCredentialsException, DeviceExecutionException, AMPIOException, AMPException { if (logger.isEntryEnabled()) logger.entry("setFirmware", deviceContext, inputStream); final Device device = getDevice(deviceContext); String contents = null;//from w w w. j ava 2 s .co m String tagname = "firmwareRev"; InputStreamReader inputStreamReader = null; BufferedReader bufferedReader = null; try { try { String openTag = "<" + tagname + ">"; String closeTag = "</" + tagname + ">"; inputStreamReader = new InputStreamReader(new Base64InputStream(inputStream), "ISO-8859-1"); bufferedReader = new BufferedReader(inputStreamReader); while (bufferedReader.ready() && (contents == null)) { String line = bufferedReader.readLine(); if (line != null) { if (line.indexOf("-----BEGIN ") > -1) { break; } int openTagIndex = line.indexOf(openTag); if (openTagIndex > -1) { int closeTagIndex = line.lastIndexOf(closeTag); int beginIndex = openTagIndex + openTag.length(); int endIndex = closeTagIndex; contents = line.substring(beginIndex, endIndex); } } } } finally { if (bufferedReader != null) { bufferedReader.close(); } else if (inputStreamReader != null) { inputStreamReader.close(); } else if (inputStream != null) { inputStream.close(); } } } catch (Throwable e) { throw new AMPException(e); } if (contents == null) { throw new AMPException(); } int periodIndex = contents.indexOf("."); String version = contents.substring(periodIndex + 1); device.setFirmwareLevel(version); unquiesceDevice(deviceContext); if (logger.isEntryEnabled()) logger.exit("setFirmware"); }
From source file:net.solarnetwork.node.setup.impl.DefaultSetupService.java
@Override public NetworkAssociationDetails decodeVerificationCode(String verificationCode) throws InvalidVerificationCodeException { log.debug("Decoding verification code {}", verificationCode); NetworkAssociationDetails details = new NetworkAssociationDetails(); try {// www . ja va 2s .co m JavaBeanXmlSerializer helper = new JavaBeanXmlSerializer(); InputStream in = new GZIPInputStream( new Base64InputStream(new ByteArrayInputStream(verificationCode.getBytes()))); Map<String, Object> result = helper.parseXml(in); // Get the host server String hostName = (String) result.get(VERIFICATION_CODE_HOST_NAME); if (hostName == null) { // Use the default log.debug("Property {} not found in verfication code", VERIFICATION_CODE_HOST_NAME); throw new InvalidVerificationCodeException("Missing host"); } details.setHost(hostName); // Get the host port String hostPort = (String) result.get(VERIFICATION_CODE_HOST_PORT); if (hostPort == null) { log.debug("Property {} not found in verfication code", VERIFICATION_CODE_HOST_PORT); throw new InvalidVerificationCodeException("Missing port"); } try { details.setPort(Integer.valueOf(hostPort)); } catch (NumberFormatException e) { throw new InvalidVerificationCodeException("Invalid host port value: " + hostPort, e); } // Get the confirmation Key String confirmationKey = (String) result.get(VERIFICATION_CODE_CONFIRMATION_KEY); if (confirmationKey == null) { throw new InvalidVerificationCodeException("Missing confirmation code"); } details.setConfirmationKey(confirmationKey); // Get the identity key String identityKey = (String) result.get(VERIFICATION_CODE_IDENTITY_KEY); if (identityKey == null) { throw new InvalidVerificationCodeException("Missing identity key"); } details.setIdentityKey(identityKey); // Get the user name String userName = (String) result.get(VERIFICATION_CODE_USER_NAME_KEY); if (userName == null) { throw new InvalidVerificationCodeException("Missing username"); } details.setUsername(userName); // Get the expiration String expiration = (String) result.get(VERIFICATION_CODE_EXPIRATION_KEY); if (expiration == null) { throw new InvalidVerificationCodeException( VERIFICATION_CODE_EXPIRATION_KEY + " not found in verification code: " + verificationCode); } try { DateTimeFormatter fmt = ISODateTimeFormat.dateTime(); DateTime expirationDate = fmt.parseDateTime(expiration); details.setExpiration(expirationDate.toDate()); } catch (IllegalArgumentException e) { throw new InvalidVerificationCodeException("Invalid expiration date value", e); } // Get the TLS setting String forceSSL = (String) result.get(VERIFICATION_CODE_FORCE_TLS); details.setForceTLS(forceSSL == null ? false : Boolean.valueOf(forceSSL)); return details; } catch (InvalidVerificationCodeException e) { throw e; } catch (Exception e) { // Runtime/IO errors can come from webFormGetForBean throw new InvalidVerificationCodeException( "Error while trying to decode verfication code: " + verificationCode, e); } }
From source file:de.zib.gndms.kit.monitor.GroovyMonitor.java
private static @NotNull InputStream getDecodedValStream(boolean b64, final @NotNull InputStream val) throws IOException { final @NotNull InputStream val1; if (b64) {//w ww . j a v a 2 s. c o m val1 = new Base64InputStream(val); } else val1 = val; return val1; }
From source file:com.persistent.cloudninja.controller.AuthFilterUtils.java
/** * Get Certificate thumb print and Issuer Name from the ACS token. * @param acsToken the acs token//from w ww . j a va2s .com * @return returnData the Map containing Thumb print and issuer name of X509Certiificate * @throws NoSuchAlgorithmException * @throws CertificateEncodingException */ public static Map<String, String> getCertificateThumbPrintAndIssuerName(String acsToken) throws NoSuchAlgorithmException, CertificateEncodingException { byte[] acsTokenByteArray = null; Map<String, String> returnData = new HashMap<String, String>(); try { acsTokenByteArray = acsToken.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { return null; } DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setNamespaceAware(true); DocumentBuilder docBuilder; String issuerName = null; StringBuffer thumbprint = null; try { docBuilder = builderFactory.newDocumentBuilder(); Document resultDoc = docBuilder.parse(new ByteArrayInputStream(acsTokenByteArray)); Element keyInfo = (Element) resultDoc.getDocumentElement() .getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "KeyInfo").item(0); NodeList x509CertNodeList = keyInfo.getElementsByTagName("X509Certificate"); Element x509CertNode = (Element) x509CertNodeList.item(0); if (x509CertNode == null) { return null; } //generating Certificate to retrieve its detail. String x509CertificateData = x509CertNode.getTextContent(); InputStream inStream = new Base64InputStream(new ByteArrayInputStream(x509CertificateData.getBytes())); CertificateFactory x509CertificateFactory = CertificateFactory.getInstance("X.509"); X509Certificate x509Certificate = (X509Certificate) x509CertificateFactory .generateCertificate(inStream); String issuerDN = x509Certificate.getIssuerDN().toString(); String[] issuerDNData = issuerDN.split("="); issuerName = issuerDNData[1]; MessageDigest md = MessageDigest.getInstance("SHA-1"); byte[] der = x509Certificate.getEncoded(); md.update(der); thumbprint = new StringBuffer(); thumbprint.append(Hex.encodeHex(md.digest())); } catch (Exception e) { e.printStackTrace(); } returnData.put("IssuerName", issuerName); returnData.put("Thumbprint", thumbprint.toString().toUpperCase()); return returnData; }
From source file:net.gbmb.collector.RecordController.java
public CollectionRecord convertFromB64(InputStream body) throws IOException { CollectionRecord cr = new CollectionRecord(); Base64InputStream is = new Base64InputStream(body); Map<String, Object> content = MAPPER.readValue(is, Map.class); cr.setContent(content);// w ww . ja v a 2s . c o m return cr; }
From source file:ee.sk.digidoc.DataFile.java
/** * Accessor for body attribute. /*w ww . ja v a 2s . c o m*/ * Returns the body as an input stream. If body contains * embedded base64 data then this is decoded first * and decoded actual payload data returned. * @return body as a byte array */ public InputStream getBodyAsStream() throws DigiDocException { InputStream strm = null; if (m_logger.isDebugEnabled()) m_logger.debug("get body as stream f-cache: " + ((m_fDfCache != null) ? m_fDfCache.getAbsolutePath() : "NULL") + " file: " + ((m_fileName != null) ? m_fileName : "NULL") + " content: " + m_contentType + " body: " + ((m_body != null) ? m_body.length : 0) + " is-b64: " + m_bodyIsBase64); if (m_fDfCache != null || m_fileName != null) { try { if (m_contentType.equals(CONTENT_EMBEDDED_BASE64)) { //strm = new iaik.utils.Base64InputStream(new FileInputStream(m_fDfCache)); if (m_fDfCache != null) strm = new Base64InputStream(new FileInputStream(m_fDfCache)); else if (m_body != null) { if (m_logger.isDebugEnabled()) m_logger.debug(" body: " + ((m_body != null) ? m_body.length : 0) + " data: \n---\n" + new String(m_body) + "\n--\n"); strm = new Base64InputStream(new ByteArrayInputStream(m_body)); } } else if (m_contentType.equals(CONTENT_BINARY)) { if (m_fDfCache != null) strm = new FileInputStream(m_fDfCache); else if (m_body != null) strm = new ByteArrayInputStream(m_body); else if (m_fileName != null) strm = new FileInputStream(m_fileName); } } catch (Exception ex) { DigiDocException.handleException(ex, DigiDocException.ERR_READ_FILE); } } else if (m_body != null) { } return strm; }
From source file:nl.nn.adapterframework.jdbc.JdbcQuerySenderBase.java
protected String getResult(ResultSet resultset, Object blobSessionVar, Object clobSessionVar, HttpServletResponse response, String contentType, String contentDisposition) throws JdbcException, SQLException, IOException, JMSException { String result = null;/*from w w w. jav a 2 s . c o m*/ if (isScalar()) { if (resultset.next()) { //result = resultset.getString(1); ResultSetMetaData rsmeta = resultset.getMetaData(); if (JdbcUtil.isBlobType(resultset, 1, rsmeta)) { if (response == null) { if (blobSessionVar != null) { JdbcUtil.streamBlob(resultset, 1, getBlobCharset(), isBlobsCompressed(), getBlobBase64Direction(), blobSessionVar, isCloseOutputstreamOnExit()); return ""; } } else { InputStream inputStream = JdbcUtil.getBlobInputStream(resultset, 1, isBlobsCompressed()); if (StringUtils.isNotEmpty(contentType)) { response.setHeader("Content-Type", contentType); } if (StringUtils.isNotEmpty(contentDisposition)) { response.setHeader("Content-Disposition", contentDisposition); } if (getBlobBase64Direction() != null) { if ("decode".equalsIgnoreCase(getBlobBase64Direction())) { inputStream = new Base64InputStream(inputStream); } else if ("encode".equalsIgnoreCase(getBlobBase64Direction())) { inputStream = new Base64InputStream(inputStream, true); } } OutputStream outputStream = response.getOutputStream(); Misc.streamToStream(inputStream, outputStream); log.debug(getLogPrefix() + "copied blob input stream [" + inputStream + "] to output stream [" + outputStream + "]"); return ""; } } if (clobSessionVar != null && JdbcUtil.isClobType(resultset, 1, rsmeta)) { JdbcUtil.streamClob(resultset, 1, clobSessionVar, isCloseOutputstreamOnExit()); return ""; } result = JdbcUtil.getValue(resultset, 1, rsmeta, getBlobCharset(), isBlobsCompressed(), getNullValue(), isTrimSpaces(), isBlobSmartGet(), StringUtils.isEmpty(getBlobCharset())); if (resultset.wasNull()) { if (isScalarExtended()) { result = "[null]"; } else { result = null; } } else { if (result.length() == 0) { if (isScalarExtended()) { result = "[empty]"; } } } } else { if (isScalarExtended()) { result = "[absent]"; } } } else { // Create XML and give the maxlength as a parameter DB2XMLWriter db2xml = new DB2XMLWriter(); db2xml.setNullValue(getNullValue()); db2xml.setTrimSpaces(isTrimSpaces()); db2xml.setBlobCharset(getBlobCharset()); db2xml.setDecompressBlobs(isBlobsCompressed()); db2xml.setGetBlobSmart(isBlobSmartGet()); result = db2xml.getXML(resultset, getMaxRows(), isIncludeFieldDefinition()); } return result; }
From source file:nl.nn.adapterframework.util.JdbcUtil.java
public static void streamBlob(Blob blob, String column, String charset, boolean blobIsCompressed, String blobBase64Direction, Object target, boolean close) throws JdbcException, SQLException, IOException { if (target == null) { throw new JdbcException("cannot stream Blob to null object"); }/* ww w . j a v a 2 s. com*/ OutputStream outputStream = StreamUtil.getOutputStream(target); if (outputStream != null) { InputStream inputStream = JdbcUtil.getBlobInputStream(blob, column, blobIsCompressed); if ("decode".equalsIgnoreCase(blobBase64Direction)) { Base64InputStream base64DecodedStream = new Base64InputStream(inputStream); StreamUtil.copyStream(base64DecodedStream, outputStream, 50000); } else if ("encode".equalsIgnoreCase(blobBase64Direction)) { Base64InputStream base64EncodedStream = new Base64InputStream(inputStream, true); StreamUtil.copyStream(base64EncodedStream, outputStream, 50000); } else { StreamUtil.copyStream(inputStream, outputStream, 50000); } if (close) { outputStream.close(); } return; } Writer writer = StreamUtil.getWriter(target); if (writer != null) { Reader reader = JdbcUtil.getBlobReader(blob, column, charset, blobIsCompressed); StreamUtil.copyReaderToWriter(reader, writer, 50000, false, false); if (close) { writer.close(); } return; } throw new IOException("cannot stream Blob to [" + target.getClass().getName() + "]"); }