List of usage examples for org.apache.commons.codec.binary Base64 Base64
public Base64()
From source file:fi.aalto.seqpig.io.SamStorer.java
@Override public void checkSchema(ResourceSchema s) throws IOException { selectedSAMAttributes = new HashMap<String, Integer>(); allSAMFieldNames = new HashMap<String, Integer>(); String[] fieldNames = s.fieldNames(); for (int i = 0; i < fieldNames.length; i++) { System.out.println("field: " + fieldNames[i]); allSAMFieldNames.put(fieldNames[i], new Integer(i)); if (fieldNames[i].equalsIgnoreCase("RG") || fieldNames[i].equalsIgnoreCase("LB") || fieldNames[i].equalsIgnoreCase("PU") || fieldNames[i].equalsIgnoreCase("PG") || fieldNames[i].equalsIgnoreCase("AS") || fieldNames[i].equalsIgnoreCase("SQ") || fieldNames[i].equalsIgnoreCase("MQ") || fieldNames[i].equalsIgnoreCase("NM") || fieldNames[i].equalsIgnoreCase("H0") || fieldNames[i].equalsIgnoreCase("H1") || fieldNames[i].equalsIgnoreCase("H2") || fieldNames[i].equalsIgnoreCase("UQ") || fieldNames[i].equalsIgnoreCase("PQ") || fieldNames[i].equalsIgnoreCase("NH") || fieldNames[i].equalsIgnoreCase("IH") || fieldNames[i].equalsIgnoreCase("HI") || fieldNames[i].equalsIgnoreCase("MD") || fieldNames[i].equalsIgnoreCase("CS") || fieldNames[i].equalsIgnoreCase("CQ") || fieldNames[i].equalsIgnoreCase("CM") || fieldNames[i].equalsIgnoreCase("R2") || fieldNames[i].equalsIgnoreCase("Q2") || fieldNames[i].equalsIgnoreCase("S2") || fieldNames[i].equalsIgnoreCase("CC") || fieldNames[i].equalsIgnoreCase("CP") || fieldNames[i].equalsIgnoreCase("SM") || fieldNames[i].equalsIgnoreCase("AM") || fieldNames[i].equalsIgnoreCase("MF") || fieldNames[i].equalsIgnoreCase("E2") || fieldNames[i].equalsIgnoreCase("U2") || fieldNames[i].equalsIgnoreCase("OQ")) { System.out.println("selected attribute: " + fieldNames[i] + " i: " + i); selectedSAMAttributes.put(fieldNames[i], new Integer(i)); }// ww w. j av a 2 s . c o m } if (!(allSAMFieldNames.containsKey("name") && allSAMFieldNames.containsKey("start") && allSAMFieldNames.containsKey("end") && allSAMFieldNames.containsKey("read") && allSAMFieldNames.containsKey("cigar") && allSAMFieldNames.containsKey("basequal") && allSAMFieldNames.containsKey("flags") && allSAMFieldNames.containsKey("insertsize") && allSAMFieldNames.containsKey("mapqual") && allSAMFieldNames.containsKey("matestart") && allSAMFieldNames.containsKey("materefindex") && allSAMFieldNames.containsKey("refindex"))) throw new IOException("Error: Incorrect SAM tuple-field name or compulsory field missing"); Base64 codec = new Base64(); Properties p = UDFContext.getUDFContext().getUDFProperties(this.getClass()); String datastr; ByteArrayOutputStream bstream = new ByteArrayOutputStream(); ObjectOutputStream ostream = new ObjectOutputStream(bstream); ostream.writeObject(selectedSAMAttributes); ostream.close(); datastr = codec.encodeBase64String(bstream.toByteArray()); p.setProperty("selectedSAMAttributes", datastr); bstream = new ByteArrayOutputStream(); ostream = new ObjectOutputStream(bstream); ostream.writeObject(allSAMFieldNames); ostream.close(); datastr = codec.encodeBase64String(bstream.toByteArray()); p.setProperty("allSAMFieldNames", datastr); }
From source file:com.zeroio.webdav.WebdavServlet.java
/** * Description of the Method//from ww w .j a v a 2s .co m * * @param argHeader Description of the Parameter * @param context Description of the Parameter * @return Description of the Return Value * @throws IOException Description of the Exception */ protected boolean allowUser(ActionContext context, String argHeader) throws IOException { if (argHeader == null) { return false; } else { //If the Authorization header user is not the user requesting a resource the //force the user to authenticate again if (context.getRequest().getParameter("user") != null) { if (!context.getRequest().getParameter("user").equals(this.getUser(context))) { //System.out.println("User: " + this.getUser(context)); //System.out.println("Req User: " + context.getRequest().getParameter("user")); return false; } } } boolean status = false; if (System.getProperty("DEBUG") != null) { //System.out.println("USERAGENT: " + context.getRequest().getHeader("user-agent")); } if (context.getRequest().getHeader("user-agent").toLowerCase().startsWith("microsoft") || context.getRequest().getHeader("user-agent").toLowerCase().indexOf("windows") > -1) { //BASIC AUTHENTICATION if (!argHeader.toUpperCase().startsWith("BASIC")) { return false; // we only do BASIC } // Get encoded user and password, comes after "BASIC " String userpassEncoded = argHeader.substring(6); // Decode it, using any base 64 decoder (we use com.oreilly.servlet) Base64 dec = new Base64(); String userpassDecoded = new String(dec.decode(userpassEncoded.getBytes())); if (System.getProperty("DEBUG") != null) { //System.out.println("USER (BASIC): " + userpassDecoded); } // Check our user list to see if that user and password are "allowed" String username = userpassDecoded.substring(0, userpassDecoded.indexOf(":")); String password = userpassDecoded.substring(username.length() + 1); Connection db = null; try { db = this.getConnection(context); WebdavManager manager = this.getWebdavManager(context); //System.out.println("username: " + username); if (manager.hasUser(username)) { status = true; } else if (manager.allowUser(db, username, password)) { String nonce = ""; status = manager.addUser(db, username, nonce); } } catch (SQLException e) { e.printStackTrace(System.out); //TODO: set error message in the response } finally { this.freeConnection(db, context); } } else { //DIGEST AUTHENTICATION if (!argHeader.startsWith("Digest")) { return false; } HashMap params = getAuthenticationParams(context, argHeader); //System.out.println("client digest : " + (String) params.get("response")); Connection db = null; String username = (String) params.get("username"); if (System.getProperty("DEBUG") != null) { //System.out.println("USER (DIGEST): " + username); } try { WebdavManager manager = this.getWebdavManager(context); if (manager.hasUser(username)) { // user already logged in. calculate the digest value and validate the user String digest = md5Encoder.encode(md5Helper.digest((manager.getUser(username).getDigest() + ":" + (String) params.get("nonce") + ":" + getA2(context, params)).getBytes())); if (digest.equals((String) params.get("response"))) { // user has been authenticated earlier and is still valid status = true; } else { // user is no longer valid. manager.removeUser(username); status = false; } //System.out.println("server digest : " + digest); } else { // Try to authenticate the user db = this.getConnection(context); String digest = md5Encoder.encode(md5Helper.digest((manager.getWebdavPassword(db, username) + ":" + (String) params.get("nonce") + ":" + getA2(context, params)).getBytes())); //System.out.println("server digest : " + digest); String nonce = (String) params.get("nonce"); if (digest.equals((String) params.get("response"))) { status = manager.addUser(db, username, nonce); } } } catch (SQLException e) { e.printStackTrace(System.out); //TODO: set error message in the response } finally { this.freeConnection(db, context); } } return status; }
From source file:com.microsoft.azure.oidc.filter.helper.impl.SimpleAuthenticationHelper.java
private String getAuthenticationEndPoint(final HttpServletRequest httpRequest, final Token token, final Boolean isError) { if (httpRequest == null) { throw new PreconditionException("Required parameter is null"); }// w ww.j a va2s . c om try { final String requestURI = httpRequest.getRequestURI(); final String queryString = httpRequest.getQueryString(); final ApplicationSettings applicationSettings = applicationSettingsLoader.load(); final Configuration configuration = configurationCache.load(); if (configuration == null) { throw new GeneralException("Error loading configuration"); } final HttpSession session = httpRequest.getSession(false); final String sessionName = session == null ? "" : session.getId(); final StringBuilder uriStringBuilder = new StringBuilder(); Base64 encoder = new Base64(); if (isError) { final State previousState = getState(httpRequest); uriStringBuilder.append(previousState.getRequestURI()); } else { uriStringBuilder.append(requestURI); if (queryString != null && !"".equals(queryString.trim())) { uriStringBuilder.append("?"); uriStringBuilder.append(queryString); } } final String userID = token == null ? "" : token.getUserID().getValue(); final State state = stateFactory.createState(userID, sessionName, uriStringBuilder.toString()); final ObjectMapper mapper = new ObjectMapper(); final String stateString = mapper.writeValueAsString(state); final String urlString = String.format( "%s%sclient_Id=%s&state=%s&nonce=defaultNonce&redirect_uri=%s&scope=openid%%20offline_access&response_type=code+id_token&prompt=%s&response_mode=form_post", configuration.getAuthenticationEndPoint(), configuration.getAuthenticationEndPoint().getName().contains("?") ? "&" : "?", applicationSettings.getApplicationId(), new String(encoder.encode(stateString.getBytes()), "UTF-8"), URLEncoder.encode(applicationSettings.getRedirectURL().getValue(), "UTF-8"), token == null ? "login" : "none"); return urlString; } catch (IOException e) { throw new GeneralException("IO Exception", e); } }
From source file:com.viettel.hqmc.DAO.FilesExpandDAO.java
public String onSignPlugin() { boolean result = true; String errorCode = ""; Calendar cal = Calendar.getInstance(); try {//ww w. j a v a2s . c o m String signType = getRequest().getParameter("signType"); String fileName = getRequest().getParameter("fileName"); String fileName0 = getRequest().getParameter("fileName0"); //hieptq update vi tri luu file ResourceBundle rb = ResourceBundle.getBundle("config"); String uploadPath = rb.getString("PERMIT_path");//160629 binhnt update duong dan luu file cong bo String subDir = String.valueOf(cal.getTime().getYear() + 1900) + separatorFile + String.valueOf(cal.getTime().getMonth() + 1) + separatorFile + String.valueOf(cal.getTime().getDate()) + separatorFile;//ex: 2016\6\29\ String strPath = rb.getString("PERMIT_upload") + subDir; String copyPath = rb.getString("file_sign_link"); String paperOnly = ""; File folderExisting = new File(strPath); if (!folderExisting.isDirectory()) { folderExisting.mkdir(); } if (folderExisting.isDirectory()) { //tao folder theo ngay thang File temp = new File(strPath); if (!temp.isDirectory()) { temp.mkdirs(); } } String[] parts = fileName.split("_"); if (parts.length != 4 && parts.length != 5 && parts.length != 6) { errorCode = "SI_015"; result = false; } if (parts.length == 5 && "LD".equals(parts[0])) { paperOnly = parts[0] + "_" + parts[1] + "_" + parts[2] + "_" + parts[3] + "_" + "2" + ".pdf"; } if (parts.length == 6 && "VT".equals(parts[0])) { paperOnly = parts[0] + "_" + parts[1] + "_" + parts[2] + "_" + parts[3] + "_" + parts[4] + "_" + "2" + ".pdf"; } //hieptq update 106015 String outputFile = strPath + fileName; String outputFileOriginal = strPath + fileName0; String signature; String signatureOriginal = null; Base64 decoder = new Base64(); signature = new String( decoder.decode(getRequest().getParameter("signData").replace("_", "+").getBytes()), "UTF-8"); SignPdfFile pdfSig = new SignPdfFile(); SignPdfFile pdfSig0 = new SignPdfFile(); String checkTsaStr = rb.getString("checkTSA"); Long checkTSA = Long.parseLong(checkTsaStr); pdfSig = (SignPdfFile) getRequest().getSession().getAttribute("PDFSignature"); //Hiepvv hoso SDBS sau cong bo khong can cai nay if (fileName0 != null && fileName0.length() > 0 && ("PDHS".equals(signType) || "PDHS_VT".equals(signType))) { signatureOriginal = new String( decoder.decode(getRequest().getParameter("signDataOriginal").replace("_", "+").getBytes()), "UTF-8"); pdfSig0 = (SignPdfFile) getRequest().getSession().getAttribute("PDFSignature2"); } //hieptq update 110615 String fileSignOutLink = getRequest().getParameter("outPutPath"); String fileSignOutLink2 = getRequest().getParameter("outPutPath2"); try { if (checkTSA == 1l) { pdfSig.insertSignatureFinal(signature, fileSignOutLink, outputFile, true); if ("PDHS".equals(signType) || "PDHS_VT".equals(signType)) { pdfSig0.insertSignatureFinal(signatureOriginal, fileSignOutLink2, outputFileOriginal, true); } } else { pdfSig.insertSignatureFinal(signature, fileSignOutLink, outputFile, false); //Hiepvv hoso SDBS sau cong bo khong can cai nay if (fileSignOutLink2 != null && fileSignOutLink2.length() > 0 && ("PDHS".equals(signType) || "PDHS_VT".equals(signType))) { pdfSig0.insertSignatureFinal(signatureOriginal, fileSignOutLink2, outputFileOriginal, false); } } } catch (IOException ex) { errorCode = "SI_016"; System.out.println("IOException " + ex.toString()); LogUtil.addLog(ex);//binhnt sonar a160901 result = false; } catch (Exception ex) { LogUtil.addLog(ex);//binhnt sonar a160901 errorCode = "SI_017"; System.out.println("Exception " + ex.getMessage()); result = false; } finally { try { if (deleteFile(fileSignOutLink)) { System.out.println("Deleted file: " + fileSignOutLink); } else { errorCode = "SI_018"; result = false; } //Hiepvv SDBS sau cong bo khong co file 2 if (("PDHS".equals(signType) || "PDHS_VT".equals(signType)) && fileSignOutLink2 != null && fileSignOutLink2.length() > 0) { if (deleteFile(copyPath + paperOnly)) { System.out.println("Deleted file: " + copyPath + paperOnly); } else { errorCode = "SI_020"; result = false; } if (deleteFile(fileSignOutLink2)) { System.out.println("Deleted file: " + fileSignOutLink2); } else { errorCode = "SI_019"; result = false; } } if (deleteFile(copyPath + fileName)) { System.out.println("Deleted file: " + copyPath + fileName); } else { errorCode = "SI_021"; result = false; } } catch (Exception ex) { LogUtil.addLog(ex);//binhnt sonar a160901 System.out.println("Delete file fail ! " + ex.toString()); } } System.out.println("Signed file: " + outputFile); try { if (updateSignPlugin(fileName, subDir, uploadPath) == false) { errorCode = "SI_022"; result = false; } if (("PDHS".equals(signType) || "PDHS_VT".equals(signType)) //Hiepvv && fileSignOutLink2 != null && fileSignOutLink2.length() > 0) { if (updateSignPlugin(paperOnly, subDir, uploadPath) == false) { errorCode = "SI_023"; result = false; } } } catch (Exception ex) { LogUtil.addLog(ex);//binhnt sonar a160901 errorCode = "SI_024"; result = false; } } catch (Exception ex) { LogUtil.addLog(ex);//binhnt sonar a160901 errorCode = "SI_025"; result = false; } List resultMessage = new ArrayList(); if (result) { resultMessage.add("1"); } else { resultMessage.add("0"); resultMessage.add(errorCode); } jsonDataGrid.setItems(resultMessage); return GRID_DATA; }
From source file:fi.hoski.web.forms.RaceEntryServlet.java
private JSONObject fromCookie(HttpServletRequest request) throws JSONException { if (useCookies) { Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (COOKIENAME.equals(cookie.getName())) { Base64 decoder = new Base64(); try { return new JSONObject(new String(decoder.decode(cookie.getValue()), "UTF-8")); } catch (UnsupportedEncodingException ex) { log(ex.getMessage(), ex); return new JSONObject(); }/*from w w w . java2 s .c om*/ } } } } return new JSONObject(); }
From source file:com.abm.mainet.water.ui.model.PlumberLicenseFormModel.java
/** * This method is used for generating byte code for uploaded files * /*from www.j a v a 2 s .co m*/ * @param docs * is list of uploaded file * @return uploaded file name and byte code */ @SuppressWarnings("static-access") private List<DocumentDetailsVO> setFileUploadMethod(List<DocumentDetailsVO> docs) { Map<Long, String> listOfString = new HashMap<Long, String>(); Map<Long, String> fileName = new HashMap<Long, String>(); if (fileupload.getCurrent().getFileMap() != null && !fileupload.getCurrent().getFileMap().isEmpty()) { for (Iterator<Entry<Long, Set<File>>> it = FileUploadUtility.getCurrent().getFileMap().entrySet() .iterator(); it.hasNext();) { Entry<Long, Set<File>> entry = it.next(); if (entry.getKey().longValue() == 0) { it.remove(); break; } } for (Map.Entry<Long, Set<File>> entry : fileupload.getCurrent().getFileMap().entrySet()) { List<File> list = new ArrayList<File>(entry.getValue()); for (File file : list) { try { Base64 base64 = new Base64(); String bytestring = base64.encodeToString(FileUtils.readFileToByteArray(file)); fileName.put(entry.getKey(), file.getName()); listOfString.put(entry.getKey(), bytestring); } catch (IOException e) { logger.error("Exception has been occurred in file byte to string conversions", e); } } } } if (!docs.isEmpty() && !listOfString.isEmpty()) { for (DocumentDetailsVO d : docs) { long count = d.getDocumentSerialNo(); if (listOfString.containsKey(count) && fileName.containsKey(count)) { d.setDocumentByteCode(listOfString.get(count)); d.setDocumentName(fileName.get(count)); } } } return docs; }
From source file:com.comcast.magicwand.spells.saucelabs.SauceProvider.java
/** * Upload files to sauce storage and return response of file uploads as SauceResponse * * @return SauceResponse holding response of file uploads */// w w w.j a va 2 s.c o m public SauceResponse uploadFilesToSauceStorage() { SauceResponse sauceResponse = new SauceResponse(); StringBuilder failureReason = new StringBuilder(); Map<String, Boolean> fileUploadStatus = new HashMap<String, Boolean>(); for (Object filePath : this.filesToUpload) { if (filePath instanceof String) { File file = new File((String) filePath); if (file.isFile() && file.exists()) { // Reset upload status to false each time before upload boolean uploadStatus = false; try { String authString = username + ":" + apiKey; /* Encoding authentication string */ String authStringEnc = new Base64().encodeAsString(new String(authString).getBytes()); LOG.debug("Base64 encoded auth string: " + authStringEnc); // Setting request headers Map<String, String> headers = new HashMap<String, String>(); headers.put("Accept", "application/octet-stream"); headers.put("Authorization", "Basic " + authStringEnc); headers.put("Content-type", "application/json"); // Converts file content to byte data byte[] data = IOUtils.toByteArray(new FileInputStream(file)); // Uploading file to sauce storage by sending multi-part encoded HTTP POST request to SauceLabs Builder builder = new HTTPRequestManager.Builder(); HTTPRequestManager helper = builder .url(this.sauceStorageUrlStr + "/" + username + "/" + file.getName() + "?overwrite=true") .method(METHOD.POST).contentType("multipart/form-data").headers(headers).data(data) .build(); LOG.info("Uploading file {} to sauce storage", file.getName()); ResponseContainer response = doSendRequest(helper); LOG.info("Response - {}", response.getResponseBody()); if (ServerStatusCodes.OK == response.getStatusCode()) { String responseBody = response.getResponseBody(); if (null != responseBody) { JSONObject jsonResponse = new JSONObject(responseBody); int size = (Integer) jsonResponse.get("size"); if (ZERO_FILE_UPLOAD_SIZE < size) { uploadStatus = true; } } } } catch (JSONException | IOException e) { failureReason.append(String.format("Exception while uploading file %s to sauce storage", file.getName())); LOG.error("Exception while uploading file {} to sauce storage", file.getName()); } fileUploadStatus.put(file.getName(), uploadStatus); if (!uploadStatus) { failureReason.append(String.format("Failed uploading file %s", file.getName())); } } else { failureReason.append(String.format( "Either the given file is a directory or file does not exist %s \n", file.getName())); LOG.error("Either the given file is a directory or file does not exist {}", file.getName()); fileUploadStatus.put(file.getName(), false); } } else { failureReason.append( String.format("Invalid data type: %s not a file name \n", filePath.getClass().getName())); LOG.error("Invalid data type: {} not a file name", filePath.getClass().getName()); } } if (this.filesToUpload.size() > 0 && failureReason.length() <= 0) { sauceResponse.setSuccess(true); } sauceResponse.setResponseObject(fileUploadStatus); sauceResponse.setFailureReason(failureReason.toString()); return sauceResponse; }
From source file:com.apifest.oauth20.AuthorizationServer.java
protected String getBasicAuthorizationClientId(HttpRequest req) { // extract Basic Authorization header String authHeader = req.headers().get(HttpHeaders.Names.AUTHORIZATION); String clientId = null;/*from w ww. j a va 2 s . c o m*/ if (authHeader != null && authHeader.contains(BASIC)) { String value = authHeader.replace(BASIC, ""); Base64 decoder = new Base64(); byte[] decodedBytes = decoder.decode(value); String decoded = new String(decodedBytes, Charset.forName("UTF-8")); // client_id:client_secret - should be changed by client password String[] str = decoded.split(":"); if (str.length == 2) { String authClientId = str[0]; String authClientSecret = str[1]; // check valid - DB call if (db.validClient(authClientId, authClientSecret)) { clientId = authClientId; } } } return clientId; }
From source file:dbf.parser.pkg2.handler.java
private void sendPost(String json) throws Exception { System.out.println("Adding url .."); String url = "http://shorewindowcleaning:withwindows@ironside.ddns.net:5984/shorewindowcleaning/_bulk_docs"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); //add reuqest header con.setRequestMethod("POST"); //con.setRequestProperty("User-Agent", USER_AGENT); con.setRequestProperty("Accept", "application/json"); con.setRequestProperty("Content-Type", "application/json"); String basicAuth = "Basic " + new String(new Base64().encode(obj.getUserInfo().getBytes())); con.setRequestProperty("Authorization", basicAuth); //String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345"; System.out.println("Adding output .."); // Send post request con.setDoOutput(true);/*from ww w . ja v a 2 s. com*/ OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream()); wr.write(json); wr.flush(); wr.close(); System.out.println("geting content .."); // System.out.println(con.getResponseMessage()); int responseCode = con.getResponseCode(); System.out.println("Adding checking response .."); System.out.println("\nSending 'POST' request to URL : " + url); System.out.println("Post parameters : " + json); System.out.println("Response Code : " + responseCode); System.out.println(con.getResponseMessage()); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); //print result System.out.println(response.toString()); }
From source file:edu.tsinghua.lumaqq.ui.config.user.UserInfoWindow.java
/** * ?????logins.xml/* www. j ava 2 s . c om*/ */ public void saveNewPassword() { if (mip.getOldPassword() == null) return; // ? File loginHistory = new File(LumaQQ.LOGIN_HISTORY); Logins logins = LoginUtil.load(loginHistory); if (logins == null) return; // Login Login login = LoginUtil.findLogin(logins, String.valueOf(main.getMyModel().qq)); if (login == null) return; // ??? if (!login.isRememberPassword()) return; // ?? login.setPassword(new String(new Base64().encode(md5(md5(mip.getNewPassword().getBytes()))))); // LoginUtil.save(loginHistory, logins); }