List of usage examples for javax.xml.bind DatatypeConverter printBase64Binary
public static String printBase64Binary(byte[] val)
Converts an array of bytes into a string.
From source file:com.testlinkrestapi.restclient.RestClient.java
private HttpUriRequest auth(HttpUriRequest request, String username, String password) { String encoding;/*from w ww . j a va2s . co m*/ try { encoding = DatatypeConverter.printBase64Binary((username + ":" + password).getBytes("UTF-8")); request.setHeader("Authorization", "Basic " + encoding); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return request; }
From source file:com.axibase.tsd.client.PlainSender.java
@Override public void run() { if (messages == null) { messages = new LinkedBlockingQueue<String>(); }/*from ww w . j ava 2 s . co m*/ HttpPost httpPost = null; try { SslConfigurator sslConfig = SslConfigurator.newInstance().securityProtocol("SSL"); connectionManager = HttpClient.createConnectionManager(clientConfiguration, sslConfig); connectionManager.setDefaultConnectionConfig(ConnectionConfig.custom().setBufferSize(SMALL).build()); httpClient = HttpClients.custom().setConnectionManager(connectionManager).build(); httpPost = new HttpPost(fullUrl()); httpPost.setHeader("Authorization", "Basic " + DatatypeConverter.printBase64Binary( (clientConfiguration.getUsername() + ":" + clientConfiguration.getPassword()).getBytes())); httpPost.setEntity(new BufferedHttpEntity(this)); } catch (Throwable e) { log.error("Could not create http client: ", e); latch.countDown(); close(); return; } try { log.info("Start writing commands to {}", fullUrl()); state = SenderState.WORKING; latch.countDown(); response = httpClient.execute(httpPost); } catch (Throwable e) { log.error("Could not execute HTTP POST: {}", httpPost, e); } finally { log.warn("Http post execution is finished, close sender"); close(); } }
From source file:com.aurel.track.admin.user.avatar.AvatarAction.java
/** * This method returns the requested personID's avatar image into JSON format. * At client side it is necessary to convert each image string to BASE64 array. * @return//from ww w. j a va2s. c o m */ public String downloadPersonIDsAvatar() { StringBuilder sb = new StringBuilder(); sb.append("{"); JSONUtility.appendBooleanValue(sb, "success", true); sb.append("\"data\":"); sb.append("["); if (personIDs != null && personIDs.length() > 0) { String[] personIDsArray = personIDs.split(","); for (int i = 0; i < personIDsArray.length; i++) { int id = Integer.parseInt(personIDsArray[i]); byte[] oneAvatar = AvatarBL.getAvatarInByteArray(id, iconKey); String oneAvatarString = DatatypeConverter.printBase64Binary(oneAvatar); sb.append("{"); JSONUtility.appendStringValue(sb, Integer.toString(id), oneAvatarString); try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] thedigest = md.digest(oneAvatar); JSONUtility.appendStringValue(sb, "checkSum", DatatypeConverter.printBase64Binary(thedigest), true); } catch (Exception ex) { JSONUtility.appendStringValue(sb, "checkSum", "", true); LOGGER.error(ExceptionUtils.getStackTrace(ex)); } if (i == personIDsArray.length - 1) { sb.append("}"); } else { sb.append("},"); } } } sb.append("]"); sb.append("}"); JSONUtility.encodeJSON(servletResponse, sb.toString()); return null; }
From source file:com.webpagebytes.wpbsample.controllers.NotificationLastDayContentController.java
public void handleRequest1(HttpServletRequest request, HttpServletResponse response, WPBModel model, WPBForward forward) {/*from ww w . ja va2 s. c om*/ OutputStream os = null; ByteArrayOutputStream baos = new ByteArrayOutputStream(10000); ByteArrayInputStream bis = null; ByteArrayOutputStream baos_users_fo = new ByteArrayOutputStream(10000); ByteArrayOutputStream baos_transactions_fo = new ByteArrayOutputStream(10000); ByteArrayOutputStream baos_deposits_fo = new ByteArrayOutputStream(10000); ByteArrayOutputStream baos_withdrawals_fo = new ByteArrayOutputStream(10000); ByteArrayOutputStream baos_users = new ByteArrayOutputStream(10000); ByteArrayOutputStream baos_transactions = new ByteArrayOutputStream(10000); ByteArrayOutputStream baos_deposits = new ByteArrayOutputStream(10000); ByteArrayOutputStream baos_withdrawals = new ByteArrayOutputStream(10000); String fopTransactionsGuid = model.getCmsModel().get(WPBModel.URI_PARAMETERS_KEY) .get("pageTransactionsGuid"); String fopUsersGuid = model.getCmsModel().get(WPBModel.URI_PARAMETERS_KEY).get("pageUsersGuid"); String fopDepositsGuid = model.getCmsModel().get(WPBModel.URI_PARAMETERS_KEY).get("pageDepositsGuid"); String fopWithdrawalsGuid = model.getCmsModel().get(WPBModel.URI_PARAMETERS_KEY).get("pageWithdrawalsGuid"); contentProvider.writePageContent(fopUsersGuid, model, baos_users_fo); model.getCmsApplicationModel().put("type", "tx"); contentProvider.writePageContent(fopTransactionsGuid, model, baos_transactions_fo); model.getCmsApplicationModel().put("type", "d"); contentProvider.writePageContent(fopDepositsGuid, model, baos_deposits_fo); model.getCmsApplicationModel().put("type", "w"); contentProvider.writePageContent(fopWithdrawalsGuid, model, baos_withdrawals_fo); ByteArrayInputStream bis_users = new ByteArrayInputStream(baos_users_fo.toByteArray()); ; ByteArrayInputStream bis_transactions = new ByteArrayInputStream(baos_transactions_fo.toByteArray()); ; ByteArrayInputStream bis_deposits = new ByteArrayInputStream(baos_deposits_fo.toByteArray()); ; ByteArrayInputStream bis_withdrawals = new ByteArrayInputStream(baos_withdrawals_fo.toByteArray()); ; try { SampleFopService fopService = SampleFopService.getInstance(); fopService.getContent(bis_users, MimeConstants.MIME_PNG, baos_users); fopService.getContent(bis_transactions, MimeConstants.MIME_PNG, baos_transactions); fopService.getContent(bis_deposits, MimeConstants.MIME_PNG, baos_deposits); fopService.getContent(bis_withdrawals, MimeConstants.MIME_PNG, baos_withdrawals); String base64Users = DatatypeConverter.printBase64Binary(baos_users.toByteArray()); String base64Transactions = DatatypeConverter.printBase64Binary(baos_transactions.toByteArray()); String base64Deposits = DatatypeConverter.printBase64Binary(baos_deposits.toByteArray()); String base64Withdrawals = DatatypeConverter.printBase64Binary(baos_withdrawals.toByteArray()); model.getCmsApplicationModel().put("users_img", base64Users); model.getCmsApplicationModel().put("transactions_img", base64Transactions); model.getCmsApplicationModel().put("deposits_img", base64Deposits); model.getCmsApplicationModel().put("withdrawals_img", base64Withdrawals); String fopPageGuid = model.getCmsModel().get(WPBModel.URI_PARAMETERS_KEY).get("pageGuid"); contentProvider.writePageContent(fopPageGuid, model, baos); bis = new ByteArrayInputStream(baos.toByteArray()); baos.close(); String contentType = model.getCmsModel().get(WPBModel.URI_PARAMETERS_KEY).get("contentType"); if (contentType.equalsIgnoreCase("pdf")) { response.setContentType("application/pdf"); os = response.getOutputStream(); fopService.getContent(bis, MimeConstants.MIME_PDF, os); } else { response.setContentType("text/html"); os = response.getOutputStream(); IOUtils.copy(bis, os); } } catch (Exception e) { e.printStackTrace(System.out); } finally { IOUtils.closeQuietly(os); IOUtils.closeQuietly(baos); IOUtils.closeQuietly(bis); IOUtils.closeQuietly(baos_users_fo); IOUtils.closeQuietly(baos_transactions_fo); IOUtils.closeQuietly(baos_deposits_fo); IOUtils.closeQuietly(baos_withdrawals_fo); IOUtils.closeQuietly(baos_users); IOUtils.closeQuietly(baos_transactions); IOUtils.closeQuietly(baos_deposits); IOUtils.closeQuietly(baos_withdrawals); } }
From source file:io.kyligence.benchmark.loadtest.client.RestClient.java
private void addHttpHeaders(HttpRequestBase method) { method.addHeader("Accept", "application/json, text/plain, */*"); method.addHeader("Content-Type", "application/json"); String basicAuth = DatatypeConverter.printBase64Binary((this.userName + ":" + this.password).getBytes()); method.addHeader("Authorization", "Basic " + basicAuth); }
From source file:com.webpagebytes.cms.local.WPBLocalFileStorage.java
public void storeFile(InputStream is, WPBFilePath file) throws IOException { String fullFilePath = getLocalFullDataPath(file); OutputStream fos = createStorageOutputStream(fullFilePath); byte[] buffer = new byte[4096]; CRC32 crc = new CRC32(); MessageDigest md = null;/* w ww . ja va 2 s . com*/ try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { IOUtils.closeQuietly(fos); throw new IOException("Cannot calculate md5 to store the file", e); } int count = 0; int size = 0; while ((count = is.read(buffer)) != -1) { size += count; fos.write(buffer, 0, count); crc.update(buffer, 0, count); md.update(buffer, 0, count); } IOUtils.closeQuietly(fos); Properties props = new Properties(); props.put("path", file.getPath()); props.put("contentType", "application/octet-stream"); props.put("crc32", String.valueOf(crc.getValue())); props.put("md5", DatatypeConverter.printBase64Binary(md.digest())); props.put("creationTime", String.valueOf(Calendar.getInstance(TimeZone.getTimeZone("GMT")).getTime().getTime())); props.put("size", String.valueOf(size)); String metaPath = getLocalFullMetaPath(file); storeFileProperties(props, metaPath); }
From source file:com.denimgroup.threadfix.service.defects.utils.RestUtilsImpl.java
private void setupAuthorization(HttpURLConnection connection, String username, String password) { String login = username + ":" + password; String encodedLogin = DatatypeConverter.printBase64Binary(login.getBytes()); connection.setRequestProperty("Authorization", "Basic " + encodedLogin); }
From source file:com.ibm.devops.dra.PublishSQ.java
@Override public void perform(@Nonnull Run build, @Nonnull FilePath workspace, @Nonnull Launcher launcher, @Nonnull TaskListener listener) throws InterruptedException, IOException { printStream = listener.getLogger();// w ww. j a v a2 s . com printPluginVersion(this.getClass().getClassLoader(), printStream); // Get the project name and build id from environment EnvVars envVars = build.getEnvironment(listener); // verify if user chooses advanced option to input customized DLMS String env = getDescriptor().getEnvironment(); String targetAPI = chooseTargetAPI(env); String url = chooseDLMSUrl(env) + API_PART; // expand to support env vars this.orgName = envVars.expand(this.orgName); this.applicationName = envVars.expand(this.applicationName); this.toolchainName = envVars.expand(this.toolchainName); if (this.isDeploy || !Util.isNullOrEmpty(this.envName)) { this.environmentName = envVars.expand(this.envName); } String buildNumber; // if user does not specify the build number if (Util.isNullOrEmpty(this.buildNumber)) { // locate the build job that triggers current build Run triggeredBuild = getTriggeredBuild(build, buildJobName, envVars, printStream); if (triggeredBuild == null) { //failed to find the build job return; } else { if (Util.isNullOrEmpty(this.buildJobName)) { // handle the case which the build job name left empty, and the pipeline case this.buildJobName = envVars.get("JOB_NAME"); } buildNumber = getBuildNumber(buildJobName, triggeredBuild); } } else { buildNumber = envVars.expand(this.buildNumber); } url = url.replace("{org_name}", URLEncoder.encode(this.orgName, "UTF-8").replaceAll("\\+", "%20")); url = url.replace("{toolchain_id}", URLEncoder.encode(this.toolchainName, "UTF-8").replaceAll("\\+", "%20")); url = url.replace("{build_artifact}", URLEncoder.encode(this.applicationName, "UTF-8").replaceAll("\\+", "%20")); url = url.replace("{build_id}", URLEncoder.encode(buildNumber, "UTF-8").replaceAll("\\+", "%20")); this.dlmsUrl = url; String bluemixToken; // get the Bluemix token try { if (Util.isNullOrEmpty(this.credentialsId)) { bluemixToken = getBluemixToken(IBMusername, IBMpassword, targetAPI); } else { bluemixToken = getBluemixToken(build.getParent(), this.credentialsId, targetAPI); } printStream.println("[IBM Cloud DevOps] Log in successfully, got the Bluemix token"); } catch (Exception e) { printStream.println( "[IBM Cloud DevOps] Username/Password is not correct, fail to authenticate with Bluemix"); printStream.println("[IBM Cloud DevOps]" + e.toString()); return; } Map<String, String> headers = new HashMap<String, String>(); // ':' needs to be added so the SQ api knows an auth token is being used String SQAuthToken = DatatypeConverter.printBase64Binary((this.SQAuthToken + ":").getBytes("UTF-8")); headers.put("Authorization", "Basic " + SQAuthToken); try { JsonObject SQqualityGate = sendGETRequest( this.SQHostName + "/api/qualitygates/project_status?projectKey=" + this.SQProjectKey, headers); printStream.println("[IBM Cloud DevOps] Successfully queried SonarQube for quality gate information"); JsonObject SQissues = sendGETRequest( this.SQHostName + "/api/issues/search?statuses=OPEN&componentKeys=" + this.SQProjectKey, headers); printStream.println("[IBM Cloud DevOps] Successfully queried SonarQube for issue information"); JsonObject SQratings = sendGETRequest(this.SQHostName + "/api/measures/component?metricKeys=reliability_rating,security_rating,sqale_rating&componentKey=" + this.SQProjectKey, headers); printStream.println("[IBM Cloud DevOps] Successfully queried SonarQube for metric information"); JsonObject payload = createDLMSPayload(SQqualityGate, SQissues, SQratings); JsonArray urls = createPayloadUrls(this.SQHostName, this.SQProjectKey); sendPayloadToDLMS(bluemixToken, payload, urls); } catch (Exception e) { printStream.println( "[IBM Cloud DevOps] Error: Unable to upload results. Please make sure all parameters are valid"); e.printStackTrace(); } }
From source file:org.davidmendoza.fileUpload.web.VideoController.java
private String base64EncodePolicy(JsonElement jsonElement) throws UnsupportedEncodingException { String policyJsonStr = jsonElement.toString(); String base64Encoded = DatatypeConverter.printBase64Binary(policyJsonStr.getBytes("UTF-8")) .replaceAll("\n", "").replaceAll("\r", ""); return base64Encoded; }
From source file:fr.inria.oak.paxquery.translation.Logical2Pact.java
private static final Operator<Record>[] translate(Selection sel) { Operator<Record>[] childPlan = translate(sel.getChild()); // create MapOperator for selecting some records MapOperator selection = MapOperator.builder(SelectionOperator.class).input(childPlan).name("Select") .build();/*from ww w .j a v a 2s. c o m*/ // selection configuration final String encodedNRSMD = DatatypeConverter .printBase64Binary(SerializationUtils.serialize(sel.getNRSMD())); selection.setParameter(PACTOperatorsConfiguration.NRSMD1_BINARY.toString(), encodedNRSMD); final String encodedPredicate = DatatypeConverter .printBase64Binary(SerializationUtils.serialize(sel.getPred())); selection.setParameter(PACTOperatorsConfiguration.PRED_BINARY.toString(), encodedPredicate); return new Operator[] { selection }; }