List of usage examples for org.apache.commons.net.util Base64 encodeBase64
public static byte[] encodeBase64(byte[] binaryData)
From source file:com.cloudera.nav.sdk.client.writer.MetadataWriterFactory.java
private HttpURLConnection createHttpStream() throws IOException { String apiUrl = joinUrlPath(/*from w w w .j a v a 2s . c o m*/ joinUrlPath(config.getNavigatorUrl(), "api/v" + String.valueOf(config.getApiVersion())), "metadata/plugin"); HttpURLConnection conn = openConnection(new URL(apiUrl)); conn.setRequestMethod("POST"); String userpass = config.getUsername() + ":" + config.getPassword(); String basicAuth = "Basic " + new String(Base64.encodeBase64(userpass.getBytes())); conn.addRequestProperty("Authorization", basicAuth); conn.addRequestProperty("Content-Type", "application/json"); conn.setDoOutput(true); return conn; }
From source file:com.ibm.iotf.client.api.DeviceFactory.java
private String connect(String httpOperation, String url, String jsonPacket) { final String METHOD = "connect"; BufferedReader br = null;/* w w w . j a va 2 s . c o m*/ br = new BufferedReader(new InputStreamReader(System.in)); StringEntity input = null; try { if (jsonPacket != null) { input = new StringEntity(jsonPacket); } } catch (UnsupportedEncodingException e) { LoggerUtility.warn(CLASS_NAME, METHOD, "Unable to carry out the ReST request"); return null; } byte[] encoding = Base64.encodeBase64(new String(authKey + ":" + authToken).getBytes()); String encodedString = new String(encoding); switch (httpOperation) { case "post": HttpPost post = new HttpPost(url); post.setEntity(input); post.addHeader("Content-Type", "application/json"); post.addHeader("Accept", "application/json"); post.addHeader("Authorization", "Basic " + encodedString); try { HttpClient client = HttpClientBuilder.create().build(); HttpResponse response = client.execute(post); br = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); } catch (IOException e) { LoggerUtility.warn(CLASS_NAME, METHOD, e.getMessage()); return null; } finally { } break; case "get": HttpGet get = new HttpGet(url); get.addHeader("Content-Type", "application/json"); get.addHeader("Accept", "application/json"); get.addHeader("Authorization", "Basic " + encodedString); try { HttpClient client = HttpClientBuilder.create().build(); HttpResponse response = client.execute(get); br = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); } catch (IOException e) { LoggerUtility.warn(CLASS_NAME, METHOD, e.getMessage()); return null; } break; case "delete": HttpDelete delete = new HttpDelete(url); delete.addHeader("Content-Type", "application/json"); delete.addHeader("Accept", "application/json"); delete.addHeader("Authorization", "Basic " + encodedString); try { HttpClient client = HttpClientBuilder.create().build(); HttpResponse response = client.execute(delete); int httpCode = response.getStatusLine().getStatusCode(); if (httpCode == 202 || httpCode == 200 || httpCode == 204) { return SUCCESSFULLY_DELETED; } else if (httpCode == 400 || httpCode == 404) { return RESOURCE_NOT_FOUND; } } catch (IOException e) { LoggerUtility.warn(CLASS_NAME, METHOD, e.getMessage()); return UNKNOWN_ERROR; } finally { } break; } String line = null; try { line = br.readLine(); } catch (IOException e) { LoggerUtility.warn(CLASS_NAME, METHOD, e.getMessage()); return null; } LoggerUtility.info(CLASS_NAME, METHOD, line); try { if (br != null) br.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return line; }
From source file:cycronix.ctlib.CThttp.java
/** * login by providing user name, password * @param user user name/*from ww w . j a v a2 s. c om*/ * @param pw password * @throws Exception on error */ public void login(String user, String pw) throws Exception { userpass = new String(Base64.encodeBase64((user + ":" + pw).getBytes())); // userpass = DatatypeConverter.printBase64Binary((user + ":" + pw).getBytes("UTF-8")); }
From source file:com.ibm.iotf.sample.devicemgmt.device.HTTPFirmwareDownload.java
public String downloadFirmware() { System.out.println(CLASS_NAME + ": Firmware Download start..."); boolean success = false; URL firmwareURL = null;/*from w ww.j a v a 2s.com*/ URLConnection urlConnection = null; String downloadedFirmwareName = null; Properties props = new Properties(); try { props.load(HTTPFirmwareDownload.class.getResourceAsStream(PROPERTIES_FILE_NAME)); } catch (IOException e1) { System.err.println("Not able to read the properties file, exiting.."); System.exit(-1); } String username = trimedValue(props.getProperty("User-Name")); String password = trimedValue(props.getProperty("Password")); String dbName = trimedValue(props.getProperty("Repository-DB")); /** * start downloading the firmware image */ try { System.out.println(CLASS_NAME + ": Downloading Firmware from URL " + deviceFirmware.getUrl()); firmwareURL = new URL(deviceFirmware.getUrl()); urlConnection = firmwareURL.openConnection(); byte[] encoding = Base64.encodeBase64(new String(username + ":" + password).getBytes()); String encodedString = "Basic " + new String(encoding); urlConnection.setRequestProperty("Authorization", encodedString); int fileSize = urlConnection.getContentLength(); if (deviceFirmware.getName() != null && !"".equals(deviceFirmware.getName())) { downloadedFirmwareName = deviceFirmware.getName(); } else { // use the timestamp as the name downloadedFirmwareName = "firmware_" + new Date().getTime() + ".deb"; } File file = new File(downloadedFirmwareName); BufferedInputStream bis = new BufferedInputStream(urlConnection.getInputStream()); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file.getName())); // count the download size to send the progress report as DiagLog to Watson IoT Platform int downloadedSize = 0; int data = bis.read(); downloadedSize += 1; if (data != -1) { bos.write(data); byte[] block = new byte[1024 * 10]; int previousProgress = 0; while (true) { int len = bis.read(block, 0, block.length); downloadedSize = downloadedSize + len; if (len != -1) { // Send the progress update if (fileSize > 0) { int progress = (int) (((float) downloadedSize / fileSize) * 100); if (progress > previousProgress) { String message = "Firmware Download progress: " + progress + "%"; addDiagLog(message, new Date(), LogSeverity.informational); System.out.println(message); } } else { // If we can't retrieve the filesize, let us update how much we have download so far String message = "Downloaded : " + downloadedSize + " bytes so far"; addDiagLog(message, new Date(), LogSeverity.informational); System.out.println(message); } bos.write(block, 0, len); } else { break; } } bos.close(); bis.close(); success = true; } else { //There is no data to read, so throw an exception if (requirePlatformUpdate) { deviceFirmware.setUpdateStatus(FirmwareUpdateStatus.INVALID_URI); } } // Verify the firmware image if verifier is set if (deviceFirmware.getVerifier() != null && !deviceFirmware.getVerifier().equals("")) { success = verifyFirmware(file, deviceFirmware.getVerifier()); /** * As per the documentation, If a firmware verifier has been set, the device should * attempt to verify the firmware image. * * If the image verification fails, mgmt.firmware.state should be set to 0 (Idle) * and mgmt.firmware.updateStatus should be set to the error status value 4 (Verification Failed). */ if (success == false) { if (requirePlatformUpdate) { deviceFirmware.setUpdateStatus(FirmwareUpdateStatus.VERIFICATION_FAILED); } // the firmware state is updated to IDLE below } } } catch (MalformedURLException me) { // Invalid URL, so set the status to reflect the same, if (requirePlatformUpdate) { deviceFirmware.setUpdateStatus(FirmwareUpdateStatus.INVALID_URI); } me.printStackTrace(); } catch (IOException e) { if (requirePlatformUpdate) { deviceFirmware.setUpdateStatus(FirmwareUpdateStatus.CONNECTION_LOST); } e.printStackTrace(); } catch (OutOfMemoryError oom) { if (requirePlatformUpdate) { deviceFirmware.setUpdateStatus(FirmwareUpdateStatus.OUT_OF_MEMORY); } } /** * Set the firmware download and possibly the firmware update status * (will be sent later) accordingly */ if (success == true) { if (requirePlatformUpdate) { deviceFirmware.setUpdateStatus(FirmwareUpdateStatus.SUCCESS); deviceFirmware.setState(FirmwareState.DOWNLOADED); } } else { if (requirePlatformUpdate) { deviceFirmware.setState(FirmwareState.IDLE); } return null; } System.out.println(CLASS_NAME + ": Firmware Download END...(" + success + ")"); return downloadedFirmwareName; }
From source file:com.cloudera.nav.plugin.client.writer.MetadataWriterFactory.java
private HttpURLConnection createHttpStream(PluginConfigurations config) throws IOException { URL url = new URL(config.getMetadataParentUri().toASCIIString()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); String userpass = config.getUsername() + ":" + config.getPassword(); String basicAuth = "Basic " + new String(Base64.encodeBase64(userpass.getBytes())); conn.addRequestProperty("Authorization", basicAuth); conn.addRequestProperty("Content-Type", "application/json"); conn.setDoOutput(true);// w w w . j a va 2 s .c o m config.setProperty("conn", conn); return conn; }
From source file:API.WESTBR.WestBrRESTClient.java
public Response makeSimpleRequest(String bbEla, String body, String type) { HttpBasicAuthFilter auth = new HttpBasicAuthFilter(this.userName, this.password); ClientConfig config = new ClientConfig(); Client client = ClientBuilder.newClient(config); WebTarget target;//from ww w. j av a2s .co m client.register(auth); target = client.target(getBaseURI(bbEla)); Invocation.Builder invocationBuilder = target.request(); MultivaluedHashMap<String, Object> mm = new MultivaluedHashMap<String, Object>(); mm.add("content-type", "application/json"); mm.add("Accept", "application/json"); mm.add("charsets", "utf-8"); String auth1 = this.getUserName() + ":" + this.getPassword(); byte[] encodedAuth = Base64.encodeBase64(auth1.getBytes(Charset.forName("ISO-8859-1"))); String authHeader = "Basic " + new String(encodedAuth); mm.add("Authorization", authHeader); invocationBuilder.headers(mm); Response plainAnswer = null; switch (type) { case "post": { plainAnswer = invocationBuilder.post(Entity.entity(body, MediaType.APPLICATION_JSON)); break; } case "put": { plainAnswer = invocationBuilder.put(Entity.entity(body, MediaType.APPLICATION_JSON)); break; } case "delete": { plainAnswer = invocationBuilder.delete(); break; } case "get": { plainAnswer = invocationBuilder.get(); break; } default: { //nothing to do } } return plainAnswer; }
From source file:API.EASTAPI.Clients.EastBrRESTClient.java
public Response makeSimpleRequest(String urlFEDSDN, String body, String type) { HttpBasicAuthFilter auth = new HttpBasicAuthFilter(this.userName, this.password); //HttpAuthenticationFeature feature = HttpAuthenticationFeature.universal(this.getUserName(), this.getPassword()); ClientConfig config = new ClientConfig(); Client client = ClientBuilder.newClient(config); WebTarget target;//from ww w. j a va 2 s . c om client.register(auth); target = client.target(getBaseURI(urlFEDSDN)); Invocation.Builder invocationBuilder = target.request(); MultivaluedHashMap<String, Object> mm = new MultivaluedHashMap<String, Object>(); mm.add("content-type", "application/json"); mm.add("Accept", "application/json"); mm.add("charsets", "utf-8"); String auth1 = this.getUserName() + ":" + this.getPassword(); byte[] encodedAuth = Base64.encodeBase64(auth1.getBytes(Charset.forName("ISO-8859-1"))); String authHeader = "Basic " + new String(encodedAuth); mm.add("Authorization", authHeader); invocationBuilder.headers(mm); Response plainAnswer = null; switch (type) { case "post": { plainAnswer = invocationBuilder.post(Entity.entity(body, MediaType.APPLICATION_JSON)); break; } case "put": { plainAnswer = invocationBuilder.put(Entity.entity(body, MediaType.APPLICATION_JSON)); break; } case "delete": { plainAnswer = invocationBuilder.delete(); break; } case "get": { plainAnswer = invocationBuilder.get(); break; } default: { //nothing to do } } return plainAnswer; }
From source file:com.mss.msp.util.DataUtility.java
/** * *************************************/*from www . j a va 2 s. c o m*/ * * @encrypted() * * @Author:Jagan Chukkala<jchukkala@miraclesoft.com> * * @Created Date:11/18/2015 * * For USe:To encrypt the string entered by user * * ************************************* */ public static String encrypted(String texto) { return new String(Base64.encodeBase64(texto.getBytes())); }
From source file:eionet.webq.converter.CdrRequestConverterTest.java
private String getBasicAuthHeader() { return "Basic " + new String(Base64.encodeBase64("username:password".getBytes())); }
From source file:com.cloudera.nav.sdk.examples.lineage3.LineageExport.java
private HttpURLConnection createHttpConnection(ClientConfig config, Set<String> entityIds) throws IOException { String navUrl = config.getNavigatorUrl(); String serverUrl = navUrl + (navUrl.endsWith("/") ? LINEAGE_EXPORT_API : "/" + LINEAGE_EXPORT_API); String queryParamString = String.format(LINEAGE_EXPORT_API_QUERY_PARAMS, URLEncoder.encode(direction, charset), // direction of lineage URLEncoder.encode(length, charset), // length of lineage URLEncoder.encode(lineageOptions, charset)); // Apply all filters URL url = new URL(serverUrl + queryParamString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); String userpass = config.getUsername() + ":" + config.getPassword(); String basicAuth = "Basic " + new String(Base64.encodeBase64(userpass.getBytes())); conn.addRequestProperty("Authorization", basicAuth); conn.addRequestProperty("Content-Type", "application/json"); conn.addRequestProperty("Accept", "application/json"); conn.setReadTimeout(0);//www . j ava 2 s .c om conn.setRequestMethod("POST"); // entityIds to pass in the request body String postData = constructEntityIdsAsCSV(entityIds); postData = "[" + postData + "]"; byte[] postDataBytes = postData.toString().getBytes("UTF-8"); conn.addRequestProperty("Content-Length", "" + Integer.toString(postData.getBytes().length)); conn.setDoOutput(true); conn.getOutputStream().write(postDataBytes); return conn; }