List of usage examples for java.util Base64 getEncoder
public static Encoder getEncoder()
From source file:Main.java
private static void traverseNode(Node parentNode, JsonObject parentJson, JsonObject upperJson) { NodeList childList = parentNode.getChildNodes(); for (int i = 0; i < childList.getLength(); i++) { JsonObject childJson = new JsonObject(); Node childNode = childList.item(i); if (childNode.getNodeType() == Node.TEXT_NODE) { if (childNode.getNodeValue().trim().length() != 0) { // non empty text node reached, so add to the parent processTextNode(parentNode, upperJson, childJson, childNode); }/*from w ww . j av a 2s . c o m*/ } else if (childNode.getNodeType() == Node.ELEMENT_NODE) { if (childNode.hasAttributes()) { // attributes exist, so go thru them traverseAttributes(childJson, childNode); } if (childNode.hasChildNodes()) { // child nodes exist, so go into them traverseNode(childNode, childJson, parentJson); } if (childNode.getNodeType() != Node.TEXT_NODE) { // non text node element if (ADDED_BY_VALUE.contains(childNode)) { // already added as a value if (parentJson.has(childNode.getNodeName())) { // there is already such an element as expected JsonElement existing = parentJson.get(childNode.getNodeName()); if (existing instanceof JsonPrimitive) { // it is a primitive as expected Iterator attrs = childJson.entrySet().iterator(); if (attrs.hasNext()) { // there are attributes, so reorganize the element to include the attributes and the // value as property - #text reorganizeForAttributes(parentJson, childNode, existing, attrs); } } else if (existing instanceof JsonArray) { // already added and reorganized as an array, so take the last element of this type and // add the attributes Iterator attrs = childJson.entrySet().iterator(); if (attrs.hasNext()) { reorganizeAddAttributes(childNode, attrs); } } else if (existing instanceof JsonObject) { System.err.println("ERROR: found object, but expected primitive or array"); } } else { System.err.println("ERROR: expected element, but it does not exist"); } // remove it from the list ADDED_BY_VALUE.remove(childNode); } else { if (parentJson.has(childNode.getNodeName())) { // parent already has such an element JsonElement existing = parentJson.get(childNode.getNodeName()); if (existing instanceof JsonArray) { // and it is already an array, so just add the child to the array ((JsonArray) existing).add(childJson); } else if (existing instanceof JsonObject) { // and it not an array, so reorganize the element reorganizeElement(parentNode, parentJson, childJson, childNode, existing); } } else { // no such an element yet, so add it to the parent parentJson.add(childNode.getNodeName(), childJson); } } } } else if (childNode.getNodeType() == Node.CDATA_SECTION_NODE) { // processTextNode(parentNode, upperJson, childJson, childNode); String base64 = Base64.getEncoder().encodeToString(childNode.getNodeValue().getBytes()); parentJson.addProperty(childNode.getNodeName(), base64); } else { System.err.println("ERROR: unsupported node type: " + childNode.getNodeType()); } } }
From source file:org.flowable.ui.admin.service.engine.FlowableClientService.java
public CloseableHttpClient getHttpClient(String userName, String password) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password)); SSLConnectionSocketFactory sslsf = null; try {//from w w w . jav a2s. c o m SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); sslsf = new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslSession) { return true; } }); } catch (Exception e) { LOGGER.warn("Could not configure HTTP client to use SSL", e); } HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); if (preemptiveBasicAuthentication) { String auth = userName + ":" + password; httpClientBuilder.setDefaultHeaders(Collections.singletonList(new BasicHeader(AUTH.WWW_AUTH_RESP, "Basic " + Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8))))); } if (sslsf != null) { httpClientBuilder.setSSLSocketFactory(sslsf); } return httpClientBuilder.build(); }
From source file:ste.web.http.BugFreeHttpUtils.java
@Test public void parse_basic_auth_ko() throws Exception { Encoder b64 = Base64.getEncoder(); final String[] PAIRS = new String[] { null, "", "Basic ", "Basic " + b64.encodeToString("".getBytes("UTF-8")), "Basic " + b64.encodeToString(":onlypassword".getBytes("UTF-8")), "something " + b64.encodeToString("abc:123".getBytes("UTF-8")), "somethingsimple" }; for (String P : PAIRS) { then(HttpUtils.parseBasicAuth(new BasicHeader(HttpHeaders.AUTHORIZATION, P))).isNull(); }// w w w.ja v a 2s . co m }
From source file:org.apache.pulsar.websocket.ReaderHandler.java
private void receiveMessage() { if (log.isDebugEnabled()) { log.debug("[{}:{}] [{}] [{}] Receive next message", request.getRemoteAddr(), request.getRemotePort(), topic, subscription);//w w w .j a v a2s .co m } reader.readNextAsync().thenAccept(msg -> { if (log.isDebugEnabled()) { log.debug("[{}] [{}] [{}] Got message {}", getSession().getRemoteAddress(), topic, subscription, msg.getMessageId()); } ConsumerMessage dm = new ConsumerMessage(); dm.messageId = Base64.getEncoder().encodeToString(msg.getMessageId().toByteArray()); dm.payload = Base64.getEncoder().encodeToString(msg.getData()); dm.properties = msg.getProperties(); dm.publishTime = DateFormatter.format(msg.getPublishTime()); if (msg.getEventTime() != 0) { dm.eventTime = DateFormatter.format(msg.getEventTime()); } if (msg.hasKey()) { dm.key = msg.getKey(); } final long msgSize = msg.getData().length; try { getSession().getRemote().sendString(ObjectMapperFactory.getThreadLocal().writeValueAsString(dm), new WriteCallback() { @Override public void writeFailed(Throwable th) { log.warn("[{}/{}] Failed to deliver msg to {} {}", reader.getTopic(), subscription, getRemote().getInetSocketAddress().toString(), th.getMessage()); pendingMessages.decrementAndGet(); // schedule receive as one of the delivery failed service.getExecutor().execute(() -> receiveMessage()); } @Override public void writeSuccess() { if (log.isDebugEnabled()) { log.debug("[{}/{}] message is delivered successfully to {} ", reader.getTopic(), subscription, getRemote().getInetSocketAddress().toString()); } updateDeliverMsgStat(msgSize); } }); } catch (JsonProcessingException e) { close(WebSocketError.FailedToSerializeToJSON); } int pending = pendingMessages.incrementAndGet(); if (pending < maxPendingMessages) { // Start next read in a separate thread to avoid recursion service.getExecutor().execute(() -> receiveMessage()); } }).exceptionally(exception -> { if (exception.getCause() instanceof AlreadyClosedException) { log.info("[{}/{}] Reader was closed while receiving msg from broker", reader.getTopic(), subscription); } else { log.warn("[{}/{}] Error occurred while reader handler was delivering msg to {}: {}", reader.getTopic(), subscription, getRemote().getInetSocketAddress().toString(), exception.getMessage()); } return null; }); }
From source file:org.wso2.carbon.apimgt.core.impl.AMDefaultKeyManagerImpl.java
/** * Create the oauth2 application with calling DCR endpoint of WSO2 IS * * @param oauthAppRequest - this object contains values of oAuth app properties. * @return OAuthApplicationInfo -this object contains oauth2 app details * @throws KeyManagementException throws KeyManagerException *//*from ww w. ja v a 2 s .c om*/ @Override public OAuthApplicationInfo createApplication(OAuthAppRequest oauthAppRequest) throws KeyManagementException { // OAuthApplications are created by calling to DCR endpoint of WSO2 IS OAuthApplicationInfo oAuthApplicationInfo = oauthAppRequest.getOAuthApplicationInfo(); String applicationName = oAuthApplicationInfo.getClientName(); String keyType = (String) oAuthApplicationInfo.getParameter(KeyManagerConstants.APP_KEY_TYPE); if (keyType != null) { //Derive oauth2 app name based on key type and user input for app name applicationName = applicationName + "_" + keyType; } APIUtils.logDebug("Trying to create OAuth application :", log); //Create json payload for DCR endpoint JsonObject json = new JsonObject(); JsonArray callbackArray = new JsonArray(); callbackArray.add(oAuthApplicationInfo.getCallbackUrl()); json.add(KeyManagerConstants.OAUTH_REDIRECT_URIS, callbackArray); json.addProperty(KeyManagerConstants.OAUTH_CLIENT_NAME, oAuthApplicationInfo.getClientName()); json.addProperty(KeyManagerConstants.OAUTH_CLIENT_OWNER, oAuthApplicationInfo.getAppOwner()); JsonArray grantArray = new JsonArray(); for (String grantType : oAuthApplicationInfo.getGrantTypes()) { grantArray.add(grantType); } json.add(KeyManagerConstants.OAUTH_CLIENT_GRANTS, grantArray); URL url; HttpURLConnection urlConn = null; try { createSSLConnection(); // Calling DCR endpoint of IS String dcrEndpoint = System.getProperty("dcrEndpoint", "https://localhost:9443/identity/connect/register"); url = new URL(dcrEndpoint); urlConn = (HttpURLConnection) url.openConnection(); urlConn.setDoOutput(true); urlConn.setRequestMethod("POST"); urlConn.setRequestProperty("content-type", "application/json"); String clientEncoded = Base64.getEncoder().encodeToString((System.getProperty("systemUsername", "admin") + ":" + System.getProperty("systemUserPwd", "admin")).getBytes(StandardCharsets.UTF_8)); log.info("client encodeddd" + clientEncoded); urlConn.setRequestProperty("Authorization", "Basic " + clientEncoded); //temp fix urlConn.getOutputStream().write((json.toString()).getBytes("UTF-8")); log.info("payload" + json.toString()); int responseCode = urlConn.getResponseCode(); if (responseCode == 201) { //If the DCR call is success String responseStr = new String(IOUtils.toByteArray(urlConn.getInputStream()), "UTF-8"); JsonParser parser = new JsonParser(); JsonObject jObj = parser.parse(responseStr).getAsJsonObject(); String consumerKey = jObj.getAsJsonPrimitive(KeyManagerConstants.OAUTH_CLIENT_ID).getAsString(); String consumerSecret = jObj.getAsJsonPrimitive(KeyManagerConstants.OAUTH_CLIENT_SECRET) .getAsString(); String clientName = jObj.getAsJsonPrimitive(KeyManagerConstants.OAUTH_CLIENT_NAME).getAsString(); String grantTypes = jObj.getAsJsonArray(KeyManagerConstants.OAUTH_CLIENT_GRANTS).getAsString(); oAuthApplicationInfo.setClientName(clientName); oAuthApplicationInfo.setClientId(consumerKey); oAuthApplicationInfo.setClientSecret(consumerSecret); oAuthApplicationInfo.setGrantTypes(Arrays.asList(grantTypes.split(","))); } else { //If DCR call fails throw new KeyManagementException("OAuth app does not contains required data : " + applicationName); } } catch (IOException e) { String errorMsg = "Can not create OAuth application : " + applicationName; log.error(errorMsg, e); throw new KeyManagementException(errorMsg, e, ExceptionCodes.OAUTH2_APP_CREATION_FAILED); } catch (JsonSyntaxException e) { String errorMsg = "Error while processing the response returned from DCR endpoint.Can not create" + " OAuth application : " + applicationName; log.error(errorMsg, e, ExceptionCodes.OAUTH2_APP_CREATION_FAILED); throw new KeyManagementException(errorMsg, ExceptionCodes.OAUTH2_APP_CREATION_FAILED); } catch (NoSuchAlgorithmException | java.security.KeyManagementException e) { String errorMsg = "Error while connecting to the DCR endpoint.Can not create" + " OAuth application : " + applicationName; log.error(errorMsg, e, ExceptionCodes.OAUTH2_APP_CREATION_FAILED); throw new KeyManagementException(errorMsg, ExceptionCodes.OAUTH2_APP_CREATION_FAILED); } finally { if (urlConn != null) { urlConn.disconnect(); } } return oAuthApplicationInfo; }
From source file:com.jeremydyer.nifi.processors.google.GoogleSpeechProcessor.java
@Override public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException { FlowFile flowFile = session.get();/* ww w . j a v a 2 s .c o m*/ if (flowFile == null) { return; } try { AtomicReference<String> image = new AtomicReference<>(); session.read(flowFile, new InputStreamCallback() { @Override public void process(InputStream inputStream) throws IOException { byte[] bytes = IOUtils.toByteArray(inputStream); byte[] encImage = Base64.getEncoder().encode(bytes); image.set(new String(encImage)); } }); AnnotateImageRequest request = new AnnotateImageRequest() .setImage(new Image().setContent(new String(image.get()))).setFeatures(ImmutableList .of(new Feature().setType("LANDMARK_DETECTION").setMaxResults(MAX_RESULTS))); Vision.Images.Annotate annotate = vision.images() .annotate(new BatchAnnotateImagesRequest().setRequests(ImmutableList.of(request))); BatchAnnotateImagesResponse batchResponse = annotate.execute(); assert batchResponse.getResponses().size() == 1; AnnotateImageResponse response = batchResponse.getResponses().get(0); if (response.getLandmarkAnnotations() == null) { throw new IOException(response.getError() != null ? response.getError().getMessage() : "Unknown error getting image annotations"); } StringBuilder lndMarks = new StringBuilder(); List<EntityAnnotation> landmarks = response.getLandmarkAnnotations(); System.out.printf("Found %d landmark%s\n", landmarks.size(), landmarks.size() == 1 ? "" : "s"); for (EntityAnnotation annotation : landmarks) { System.out.printf("\t%s\n", annotation.getDescription()); lndMarks.append(annotation.getDescription()); lndMarks.append(", "); } flowFile = session.putAttribute(flowFile, "landmarks", lndMarks.toString()); session.transfer(flowFile, REL_SUCCESS); } catch (Exception ex) { ex.printStackTrace(); } }
From source file:org.apache.syncope.client.console.PreferenceManager.java
public void set(final Request request, final Response response, final String key, final String value) { String prefString = COOKIE_UTILS.load(COOKIE_NAME); final Map<String, String> current = new HashMap<>(); if (prefString != null) { current.putAll(getPrefs(new String(Base64.getDecoder().decode(prefString.getBytes())))); }/*from www .j a v a 2 s. c o m*/ // after retrieved previous setting in order to overwrite the key ... current.put(key, value); try { COOKIE_UTILS.save(COOKIE_NAME, Base64.getEncoder().encodeToString(setPrefs(current).getBytes())); } catch (IOException e) { LOG.error("Could not save {} info: {}", getClass().getSimpleName(), current, e); } }
From source file:com.flipkart.poseidon.handlers.http.impl.oauth.OAuthTokenGenerator.java
/** * get request headers for making call to Oauth end point * @return//w w w .j ava 2 s. co m */ private Map<String, String> getRequestHeaders() { Map<String, String> requestHeaders = new HashMap<String, String>(); String credentials = clientId + ":" + secret; String encodedCredentials = Base64.getEncoder().encodeToString(credentials.getBytes()); requestHeaders.put("Authorization", "Basic " + encodedCredentials); return requestHeaders; }
From source file:com.srotya.sidewinder.cluster.storage.ClusteredMemStorageEngine.java
/** * Encode proxy hops to the dbname so that recursion information can be * communicated to the smaller caller.//from ww w .java2 s . c o m * * This approach is used break recursion cycles when sending proxied * commands through the cluster. * * @param dbName * @param selfWorker * @return encodedDbName */ public static String encodeDbAndProxyName(String dbName, String selfWorker) { List<String> proxies = new ArrayList<>(); dbName = decodeDbAndProxyNames(proxies, dbName); proxies.add(selfWorker); ByteArrayOutputStream os = new ByteArrayOutputStream(); Output output = new Output(os); kryoThreadLocal.get().writeObject(output, proxies); output.close(); String proxyString = Base64.getEncoder().encodeToString(os.toByteArray()); StringBuilder builder = new StringBuilder(proxyString.length() + 1 + dbName.length()); builder.append(proxyString).append("|").append(dbName); return builder.toString(); }
From source file:fr.pilato.elasticsearch.crawler.fs.tika.TikaDocParser.java
public static void generate(FsSettings fsSettings, InputStream inputStream, String filename, Doc doc, MessageDigest messageDigest, long filesize) throws IOException { logger.trace("Generating document [{}]", filename); // Extracting content with Tika // See #38: https://github.com/dadoonet/fscrawler/issues/38 int indexedChars = 100000; if (fsSettings.getFs().getIndexedChars() != null) { if (fsSettings.getFs().getIndexedChars().percentage()) { indexedChars = (int) Math.round(filesize * fsSettings.getFs().getIndexedChars().asDouble()); logger.trace("using percentage [{}] to define indexed chars: [{}]", fsSettings.getFs().getIndexedChars(), indexedChars); } else {/* w w w .j a v a 2 s . c om*/ indexedChars = (int) fsSettings.getFs().getIndexedChars().value(); logger.trace("indexed chars [{}]", indexedChars == -1 ? "has been disabled. All text will be extracted" : indexedChars); } } Metadata metadata = new Metadata(); String parsedContent = null; if (messageDigest != null) { logger.trace("Generating hash with [{}]", messageDigest.getAlgorithm()); inputStream = new DigestInputStream(inputStream, messageDigest); } ByteArrayOutputStream bos = null; if (fsSettings.getFs().isStoreSource()) { logger.debug("Using a TeeInputStream as we need to store the source"); bos = new ByteArrayOutputStream(); inputStream = new TeeInputStream(inputStream, bos); } try { // Set the maximum length of strings returned by the parseToString method, -1 sets no limit logger.trace("Beginning Tika extraction"); parsedContent = tika().parseToString(inputStream, metadata, indexedChars); logger.trace("End of Tika extraction"); } catch (Throwable e) { logger.debug("Failed to extract [" + indexedChars + "] characters of text for [" + filename + "]", e); } // Adding what we found to the document we want to index // File doc.getFile().setContentType(metadata.get(Metadata.CONTENT_TYPE)); doc.getFile().setExtension(FilenameUtils.getExtension(filename)); // We only add `indexed_chars` if we have other value than default or -1 if (fsSettings.getFs().getIndexedChars() != null && fsSettings.getFs().getIndexedChars().value() != -1) { doc.getFile().setIndexedChars(indexedChars); } if (fsSettings.getFs().isAddFilesize()) { if (metadata.get(Metadata.CONTENT_LENGTH) != null) { // We try to get CONTENT_LENGTH from Tika first doc.getFile().setFilesize(Long.parseLong(metadata.get(Metadata.CONTENT_LENGTH))); } } if (messageDigest != null) { byte[] digest = messageDigest.digest(); String result = ""; // Convert to Hexa for (int i = 0; i < digest.length; i++) { result += Integer.toString((digest[i] & 0xff) + 0x100, 16).substring(1); } doc.getFile().setChecksum(result); } // File // Meta doc.getMeta().setAuthor(metadata.get(TikaCoreProperties.CREATOR)); doc.getMeta().setTitle(metadata.get(TikaCoreProperties.TITLE)); String sDate = metadata.get(TikaCoreProperties.MODIFIED); if (sDate != null) { try { LocalDateTime date = LocalDateTime.parse(sDate, DateTimeFormatter.ISO_DATE_TIME); doc.getMeta().setDate(date); } catch (DateTimeParseException e) { logger.warn("Can not parse date [{}] for [{}]. Skipping date field...", sDate, filename); } } doc.getMeta().setKeywords(commaDelimitedListToStringArray(metadata.get(TikaCoreProperties.KEYWORDS))); if (fsSettings.getFs().isRawMetadata()) { logger.trace("Listing all available metadata:"); for (String metadataName : metadata.names()) { String value = metadata.get(metadataName); // This is a logger trick which helps to generate our unit tests // You need to change test/resources/log4j2.xml fr.pilato.elasticsearch.crawler.fs.tika level to trace logger.trace(" assertThat(raw, hasEntry(\"{}\", \"{}\"));", metadataName, value); doc.getMeta().addRaw(metadataName, value); } } // Meta // Doc content doc.setContent(parsedContent); // Doc as binary attachment if (fsSettings.getFs().isStoreSource()) { doc.setAttachment(Base64.getEncoder().encodeToString(bos.toByteArray())); } logger.trace("End document generation"); // End of our document }