List of usage examples for java.security NoSuchAlgorithmException printStackTrace
public void printStackTrace()
From source file:com.sdcs.courierbooking.service.UserServiceImpl.java
@Override public JSONObject christmasSales(String selectedItem, String senderName, String senderPhone, String recieverName, String recieverAddress, String recieverPhone, String pincode, String surpriceNametoController, String surpriceDatetoController, String surpriceTimetoController, String photo, String totalAmount, String cod) { // TODO Auto-generated method stub String online = "online_payment"; String cash = "cod_payment"; JSONObject responceJson = new JSONObject(); String response = userDao.christmasSales(selectedItem, senderName, senderPhone, recieverName, recieverAddress, recieverPhone, pincode, surpriceNametoController, surpriceDatetoController, surpriceTimetoController, photo, totalAmount, cod); if (response != null) { responceJson.put("tracking_number", response); responceJson.put("totalamount", totalAmount); responceJson.put("cod", cod); responceJson.put("status", true); if (cod != cash) { Date date = new Date(); String strHomeaddrss = recieverAddress; String referenceNo = "00" + response + date.getTime(); responceJson.put("account_id", SdcsPaymentGatewayConstants.ACCOUNT_ID); responceJson.put("address", recieverAddress); responceJson.put("amount", totalAmount); //couriersObject.put("amount", "13.0"); responceJson.put("channel", SdcsPaymentGatewayConstants.CHANNEL); responceJson.put("city", "Bangalore"); responceJson.put("country", SdcsPaymentGatewayConstants.COUNTRY); responceJson.put("currency", SdcsPaymentGatewayConstants.CURRENCY); responceJson.put("description", "Make payment for new courier"); responceJson.put("email", "sdcs.info24@gmail.com"); responceJson.put("mode", SdcsPaymentGatewayConstants.MODE); responceJson.put("name", senderName); responceJson.put("page_id", "2197"); responceJson.put("phone", senderPhone); responceJson.put("postal_code", "000000"); responceJson.put("reference_no", referenceNo); responceJson.put("return_url", SdcsPaymentGatewayConstants.RETURN_URL); responceJson.put("state", "Karnataka"); String md5HashData = SdcsPaymentGatewayConstants.SECRET_KEY + "|" + SdcsPaymentGatewayConstants.ACCOUNT_ID + "|" + strHomeaddrss + "|" + totalAmount //+ "|" + "13.0" + "|" + SdcsPaymentGatewayConstants.CHANNEL + "|" + "Bangalore" + "|" + SdcsPaymentGatewayConstants.COUNTRY + "|" + SdcsPaymentGatewayConstants.CURRENCY + "|" + "Make payment for new courier" + "|" + "sdcs.info24@gmail.com" + "|" + SdcsPaymentGatewayConstants.MODE + "|" + senderName + "|" + "2197" + "|" + senderPhone + "|" + "000000" + "|" + referenceNo + "|" + SdcsPaymentGatewayConstants.RETURN_URL + "|" + "Karnataka"; System.out.println("Values Before Hashing:" + md5HashData); SdcsPersistantValues.setPersistantValues(senderName, "sdcs.info24@gmail.com", senderPhone, response + "", "SANTA"); responceJson.put("hash_values", md5HashData); String hasedValue;// ww w . j a v a 2 s. co m try { hasedValue = SdcsHashProvider.generateMd5Hash(md5HashData); responceJson.put("secure_hash", hasedValue); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (cod != online) { String strSmsText = "Dear%20" + senderName + ",your%20santaclause%20booking%20has%20been%20confirmed%20and%20your%20reference%20number%20is%20" + response + ".%20Your%20order%20will%20be%20delivered%20soon.Thank%20you.%20"; SdcsSMSComponent.sendSms(senderPhone, strSmsText); String strSmsTexta = "A%20new%20santaclause%20booking%20done%20done%20from%20" + senderName + ".%20Reference%20id%20is%20" + response + ".Contact%20number%20is%20" + senderPhone + ""; SdcsSMSComponent.sendSms("9535337626", strSmsTexta); DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); String body = "<div>" + "<h4 style='color:navy'>Dear admin.,<h4><br><br>" + "<p>A new Santa claus booking from the following details</p>" + "<table style='border:1px solid blue;border-collapse: collapse;'>" + "<tr style='border:1px solid blue'>" + "<th style='border:1px solid blue;color:red;'>" + "Date" + "</th>" + "<th style='border:1px solid blue;color:red;'>" + "Item" + "</th>" + "<th style='border:1px solid blue;color:red;'>" + "Oreder Id" + "</th>" + "<th style='border:1px solid blue;color:red;'>" + "Sender Name" + "</th>" + "<th style='border:1px solid blue;color:red;'>" + "Sender Contact Number" + "</th>" + "<th style='border:1px solid blue;color:red;'>" + "Reciever Name" + "</th>" + "<th style='border:1px solid blue;color:red;'>" + "Reciever Address" + "</th>" + "<th style='border:1px solid blue;color:red;'>" + "Reciever Contact Number" + "</th>" + "</th>" + "<th style='border:1px solid blue;color:red;'>" + "Surprice Delivery Name" + "</th>" + "</th>" + "<th style='border:1px solid blue;color:red;'>" + "Surprice Delivery Date" + "</th>" + "</th>" + "<th style='border:1px solid blue;color:red;'>" + "Surprice Delivery time" + "</th>" + "</th>" + "<th style='border:1px solid blue;color:red;'>" + "Photo" + "</th>" + "</th>" + "<th style='border:1px solid blue;color:red;'>" + "Payment Mode" + "</th>" + "</th>" + "<th style='border:1px solid blue;color:red;'>" + "Total Amount" + "</th>" + "</tr>" + "<tr>" + "<td style='border:1px solid blue;color:blue;'>" + dateFormat.format(date) + "</td>" + "<td style='border:1px solid blue;color:blue;'>" + selectedItem + "</td>" + "<td style='border:1px solid blue;color:blue;'>" + response + "</td>" + "<td style='border:1px solid blue;color:blue;'>" + senderName + "</td>" + "<td style='border:1px solid blue;color:blue;'>" + senderPhone + "</td>" + "<td style='border:1px solid blue;color:blue;'>" + recieverName + "</td>" + "<td style='border:1px solid blue;color:blue;'>" + recieverAddress + " " + pincode + "</td>" + "<td style='border:1px solid blue;color:blue;'>" + recieverPhone + "</td>" + "<td style='border:1px solid blue;color:blue;'>" + surpriceNametoController + "</td>" + "<td style='border:1px solid blue;color:blue;'>" + surpriceDatetoController + "</td>" + "<td style='border:1px solid blue;color:blue;'>" + surpriceTimetoController + "</td>" + "<td style='border:1px solid blue;color:blue;'>" + photo + "</td>" + "<td style='border:1px solid blue;color:blue;'>" + cod + "</td>" + "<td style='border:1px solid blue;color:blue;'>" + totalAmount + "</td>" + "</tr>" + "</table>" + "<br>" + "<p>Thank you.</p>" + "</div>"; SdcsEmailComponent.sendMail("sdcs2me@gmail.com", "SANTA CLAUS BOOKING", body, BigInteger.ZERO); } } else { responceJson.put("status", false); } return responceJson; }
From source file:com.sdcs.courierbooking.service.UserServiceImpl.java
@Override public String paymentUpdate(String restaurantId) { // TODO Auto-generated method stub JSONObject deliveredList = new JSONObject(); ResultSet updatePaymentDetails = userDao.paymentUpdate(restaurantId); Timestamp name = null;/*from www. j a v a2s . com*/ String name2 = "0"; int number = 0; double damount = 0.00; double totalamount = 0.00; double tamount1 = 0.00; String address = "0"; String lastbookingid = ""; String rest_name = ""; String phone = "0"; int trackingId = 0; String date = ""; if (updatePaymentDetails != null) { try { JSONArray couriersArray = new JSONArray(); while (updatePaymentDetails.next()) { JSONObject couriersObject = new JSONObject(); name = updatePaymentDetails.getTimestamp("time_of_booking"); String amounta = updatePaymentDetails.getString("total_amount"); address = updatePaymentDetails.getString("restaurant_address"); phone = updatePaymentDetails.getString("restaurant_contact"); trackingId = updatePaymentDetails.getInt("booking_id"); lastbookingid = "" + trackingId; rest_name = updatePaymentDetails.getString("restaurant_name"); damount = Double.parseDouble(amounta); /* extraDistance = updatePaymentDetails.getDouble("extra_distance"); */ String DATE_FORMAT = "yyyy/MM/dd"; SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); date = sdf.format(name); if (date.equals(name2)) { tamount1 = damount + tamount1; number = number + 1; } else if (name2 != "0") { couriersObject.put("time_of_booking", name2); couriersObject.put("number_of_couriers", number); couriersObject.put("amount", totalamount); couriersObject.put("tracking_number", lastbookingid); couriersArray.put(couriersObject); totalamount += tamount1; tamount1 = damount; number = 1; name2 = date; } else { tamount1 = damount; number = 1; name2 = date; } } JSONObject couriersObject = new JSONObject(); couriersObject.put("time_of_booking", rest_name); couriersObject.put("number_of_couriers", number); double roundOff1 = Math.round(tamount1 * 100.0) / 100.0; couriersObject.put("amount", roundOff1); couriersArray.put(couriersObject); totalamount += tamount1; String referenceNumber = "" + trackingId; deliveredList.put("result", true); deliveredList.put("all_couriers", couriersArray); Date date1 = new Date(); String referenceNo = "00" + trackingId + date1.getTime(); deliveredList.put("account_id", SdcsPaymentGatewayConstants.ACCOUNT_ID); deliveredList.put("address", address); double roundOff = Math.round(totalamount * 100.0) / 100.0; deliveredList.put("amount", roundOff); //newBookingJsonData.put("amount", "13.0"); deliveredList.put("channel", SdcsPaymentGatewayConstants.CHANNEL); deliveredList.put("city", lastbookingid); deliveredList.put("country", SdcsPaymentGatewayConstants.COUNTRY); deliveredList.put("currency", SdcsPaymentGatewayConstants.CURRENCY); deliveredList.put("description", "Make payment for new courier"); deliveredList.put("email", "manjunathdl@gmail.com"); deliveredList.put("mode", SdcsPaymentGatewayConstants.MODE); deliveredList.put("name", rest_name); deliveredList.put("page_id", "2197"); deliveredList.put("phone", phone); deliveredList.put("postal_code", "560072"); deliveredList.put("reference_no", referenceNo); deliveredList.put("return_url", SdcsPaymentGatewayConstants.RETURN_URL); deliveredList.put("state", "Karnataka"); String md5HashData = SdcsPaymentGatewayConstants.SECRET_KEY + "|" + SdcsPaymentGatewayConstants.ACCOUNT_ID + "|" + address + "|" + roundOff //+ "|" + "13.0" + "|" + SdcsPaymentGatewayConstants.CHANNEL + "|" + lastbookingid + "|" + SdcsPaymentGatewayConstants.COUNTRY + "|" + SdcsPaymentGatewayConstants.CURRENCY + "|" + "Make payment for new courier" + "|" + "manjunathdl@gmail.com" + "|" + SdcsPaymentGatewayConstants.MODE + "|" + rest_name + "|" + "2197" + "|" + phone + "|" + "560072" + "|" + referenceNo + "|" + SdcsPaymentGatewayConstants.RETURN_URL + "|" + "Karnataka"; String UserId = "ff"; System.out.println("Values Before Hashing:" + md5HashData); SdcsPersistantValues.setPersistantValues(rest_name, "manjunathdl@gmail.com", phone, trackingId + "", UserId); deliveredList.put("hash_values", md5HashData); String hasedValue; try { hasedValue = SdcsHashProvider.generateMd5Hash(md5HashData); deliveredList.put("secure_hash", hasedValue); System.out.println("Values After Hashing:" + hasedValue); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } /*String referenceNo = "00"+ trackingId+ date1.getTime(); deliveredList.put("account_id", SdcsPaymentGatewayConstants.ACCOUNT_ID); deliveredList.put("address",address ); //deliveredList.put("amount", ""+tamount); couriersObject.put("amount", "130.0"); deliveredList.put("channel", SdcsPaymentGatewayConstants.CHANNEL); deliveredList.put("city","bangalore"); deliveredList.put("country", SdcsPaymentGatewayConstants.COUNTRY); deliveredList.put("currency", SdcsPaymentGatewayConstants.CURRENCY); deliveredList.put("description", "Make payment for new courier"); deliveredList.put("email", "manjunathdl@gmail.com"); deliveredList.put("mode", SdcsPaymentGatewayConstants.MODE); deliveredList.put("name", rest_name); deliveredList.put("page_id", "2197"); deliveredList.put("phone", phone); deliveredList.put("postal_code", "560072"); deliveredList.put("reference_no", referenceNo); deliveredList.put("return_url", SdcsPaymentGatewayConstants.RETURN_URL); deliveredList.put("state", "temple"); String md5HashData = SdcsPaymentGatewayConstants.SECRET_KEY + "|" + SdcsPaymentGatewayConstants.ACCOUNT_ID + "|" + address + "|" + "130.0" + "|" + SdcsPaymentGatewayConstants.CHANNEL + "|" + "temple" + "|" + SdcsPaymentGatewayConstants.COUNTRY + "|" + SdcsPaymentGatewayConstants.CURRENCY + "|" + "Make payment for new courier" + "|" + "manjunathdl@gmail.com" + "|" + SdcsPaymentGatewayConstants.MODE + "|" + rest_name + "|" + "2197" + "|" + phone + "|" + "560072" + "|" + referenceNo + "|" + SdcsPaymentGatewayConstants.RETURN_URL + "|" + "temple"; SdcsPersistantValues.setPersistantValues(rest_name,"sdcs.info24@gmail.com", phone,trackingId+"", "Courier"); deliveredList.put("hash_values", md5HashData); String hasedValue; try { hasedValue = SdcsHashProvider.generateMd5Hash(md5HashData); deliveredList.put("secure_hash", hasedValue); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ System.out.println(md5HashData); DecimalFormat df = new DecimalFormat("#.##"); df.setRoundingMode(RoundingMode.HALF_UP); String tamount2 = df.format(totalamount); // 0.91239 deliveredList.put("total_Amount", tamount2); deliveredList.put("refferenceId", referenceNumber); } catch (SQLException e) { deliveredList.put("result", false); try { updatePaymentDetails.close(); } catch (SQLException sqlEx) { System.out.println("Exception in QuickHistoryServerImpl"); } } finally { try { updatePaymentDetails.close(); } catch (SQLException e) { System.out.println("Exception in QuickHistoryServerImpl"); } } } else { deliveredList.put("result", false); } return deliveredList.toString(); }
From source file:cx.fbn.nevernote.gui.BrowserWindow.java
private Resource createResource(String url, int sequence, String mime, boolean attachment) { logger.log(logger.EXTREME, "Inside create resource"); QFile resourceFile;//from w w w . j a v a2s .c o m //These two lines are added to handle odd characters in the name like #. Without it // toLocalFile() chokes and returns the wrong name. logger.log(logger.EXTREME, "File URL:" + url); String whichOS = System.getProperty("os.name"); if (whichOS.contains("Windows")) url = url.replace("file:///", ""); else url = url.replace("file://", ""); String urlTest = new QUrl(url).toLocalFile(); logger.log(logger.EXTREME, "File URL toLocalFile():" + urlTest); urlTest = url; if (!urlTest.equals("")) url = urlTest; // url = url.replace("/", File.separator); logger.log(logger.EXTREME, "Reading from file to create resource:" + url); resourceFile = new QFile(url); resourceFile.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly)); logger.log(logger.EXTREME, "Error opening file " + url.toString() + ": " + resourceFile.errorString()); byte[] fileData = resourceFile.readAll().toByteArray(); resourceFile.close(); logger.log(logger.EXTREME, "File Length: " + fileData.length); if (fileData.length == 0) return null; MessageDigest md; try { logger.log(logger.EXTREME, "Generating MD5"); md = MessageDigest.getInstance("MD5"); md.update(fileData); byte[] hash = md.digest(); Resource r = new Resource(); Calendar time = new GregorianCalendar(); long prevTime = time.getTimeInMillis(); while (prevTime == time.getTimeInMillis()) { time = new GregorianCalendar(); } r.setGuid(time.getTimeInMillis() + new Integer(sequence).toString()); r.setNoteGuid(currentNote.getGuid()); r.setMime(mime); r.setActive(true); r.setUpdateSequenceNum(0); r.setWidth((short) 0); r.setHeight((short) 0); r.setDuration((short) 0); Data d = new Data(); d.setBody(fileData); d.setBodyIsSet(true); d.setBodyHash(hash); d.setBodyHashIsSet(true); r.setData(d); d.setSize(fileData.length); int fileNamePos = url.lastIndexOf(File.separator); if (fileNamePos == -1) fileNamePos = url.lastIndexOf("/"); String fileName = url.substring(fileNamePos + 1); ResourceAttributes a = new ResourceAttributes(); a.setAltitude(0); a.setAltitudeIsSet(false); a.setLongitude(0); a.setLongitudeIsSet(false); a.setLatitude(0); a.setLatitudeIsSet(false); a.setCameraMake(""); a.setCameraMakeIsSet(false); a.setCameraModel(""); a.setCameraModelIsSet(false); a.setAttachment(attachment); a.setAttachmentIsSet(true); a.setClientWillIndex(false); a.setClientWillIndexIsSet(true); a.setRecoType(""); a.setRecoTypeIsSet(false); a.setSourceURL(url); a.setSourceURLIsSet(true); a.setTimestamp(0); a.setTimestampIsSet(false); a.setFileName(fileName); a.setFileNameIsSet(true); r.setAttributes(a); conn.getNoteTable().noteResourceTable.saveNoteResource(r, true); logger.log(logger.EXTREME, "Resource created"); return r; } catch (NoSuchAlgorithmException e1) { e1.printStackTrace(); } return null; }
From source file:cx.fbn.nevernote.gui.BrowserWindow.java
public void insertLatexImageReady(QNetworkReply reply) { logger.log(logger.EXTREME, "Response received from CodeCogs"); if (reply.error() != NetworkError.NoError) return;// w w w. ja va2 s . c o m unblockTime = -1; if (!awaitingHttpResponse) return; awaitingHttpResponse = false; QUrl replyUrl = reply.url(); QByteArray image = reply.readAll(); reply.close(); logger.log(logger.EXTREME, "New image size: " + image.size()); Resource newRes = null; QFile tfile; String path; if (latexGuid == null) { logger.log(logger.EXTREME, "Creating temporary gif"); path = Global.getFileManager().getResDirPath("latex-temp.gif"); tfile = new QFile(path); tfile.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.WriteOnly)); logger.log(logger.EXTREME, "File Open: " + tfile.errorString()); tfile.write(image); logger.log(logger.EXTREME, "Bytes writtes: " + tfile.size()); tfile.close(); logger.log(logger.EXTREME, "Creating resource"); int sequence = 0; if (currentNote.getResources() != null || currentNote.getResources().size() > 0) sequence = currentNote.getResources().size(); newRes = createResource(path, sequence, "image/gif", false); QImage pix = new QImage(); pix.loadFromData(image); newRes.setHeight(new Integer(pix.height()).shortValue()); newRes.setWidth(new Integer(pix.width()).shortValue()); logger.log(logger.EXTREME, "Renaming temporary file to " + newRes.getGuid() + ".gif"); path = Global.getFileManager().getResDirPath(newRes.getGuid() + ".gif"); tfile.rename(path); } else { newRes = conn.getNoteTable().noteResourceTable.getNoteResource(latexGuid, false); path = Global.getFileManager().getResDirPath(newRes.getGuid() + ".gif"); tfile = new QFile(path); tfile.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.WriteOnly)); tfile.write(image); tfile.close(); newRes.getData().setBody(image.toByteArray()); // Calculate the new hash value MessageDigest md; logger.log(logger.EXTREME, "Generating MD5"); try { md = MessageDigest.getInstance("MD5"); md.update(image.toByteArray()); byte[] hash = md.digest(); newRes.getData().setBodyHash(hash); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } QImage pix = new QImage(); pix.loadFromData(image); newRes.setHeight(new Integer(pix.height()).shortValue()); newRes.setWidth(new Integer(pix.width()).shortValue()); conn.getNoteTable().noteResourceTable.updateNoteResource(newRes, true); } logger.log(logger.EXTREME, "Setting source: " + replyUrl.toString()); newRes.getAttributes().setSourceURL(replyUrl.toString()); conn.getNoteTable().noteResourceTable.updateNoteSourceUrl(newRes.getGuid(), replyUrl.toString(), true); for (int i = 0; i < currentNote.getResourcesSize(); i++) { if (currentNote.getResources().get(i).getGuid().equals(newRes.getGuid())) { currentNote.getResources().remove(i); i = currentNote.getResourcesSize(); } } currentNote.getResources().add(newRes); // do the actual insert into the note. We only do this on new formulas. if (latexGuid == null) { StringBuffer buffer = new StringBuffer(100); String formula = replyUrl.toString().toLowerCase().replace("http://latex.codecogs.com/gif.latex?", ""); buffer.append("<a href=\"latex://" + path.replace("\\", "/") + "\" title=\"" + formula + "\"" + "><img src=\""); buffer.append(path.replace("\\", "/")); buffer.append("\" en-tag=\"en-latex\" type=\"image/gif\"" + " hash=\"" + Global.byteArrayToHexString(newRes.getData().getBodyHash()) + "\"" + " guid=\"" + newRes.getGuid() + "\"" + " /></a>"); String script_start = new String("document.execCommand('insertHTML', false, '"); String script_end = new String("');"); browser.page().mainFrame().evaluateJavaScript(script_start + buffer + script_end); } else { HtmlTagModifier modifier = new HtmlTagModifier(getContent()); modifier.modifyLatexTagHash(newRes); String newContent = modifier.getHtml(); setContent(new QByteArray(newContent)); } logger.log(logger.EXTREME, "New HTML set\n" + browser.page().currentFrame().toHtml()); QWebSettings.setMaximumPagesInCache(0); QWebSettings.setObjectCacheCapacities(0, 0, 0); browser.page().mainFrame().setHtml(browser.page().mainFrame().toHtml()); browser.reload(); contentChanged(); // resourceSignal.contentChanged.emit(path); unblockTime = -1; unblockApplication.emit(); return; }
From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java
public String HashFile(String fileName) { String sTmpFileName = fixFileName(fileName); String sRet = sErrorPrefix + "Couldn't calculate hash for file " + sTmpFileName; byte[] buffer = new byte[4096]; int nRead = 0; long lTotalRead = 0; MessageDigest digest = null;//www . ja v a 2 s . c o m try { digest = java.security.MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } if (sTmpFileName.contains("org.mozilla.fennec") || sTmpFileName.contains("org.mozilla.firefox")) { ContentResolver cr = contextWrapper.getContentResolver(); Uri ffxFiles = null; ffxFiles = Uri .parse("content://" + (sTmpFileName.contains("fennec") ? fenProvider : ffxProvider) + "/file"); String[] columns = new String[] { "_id", "chunk" }; Cursor myCursor = cr.query(ffxFiles, columns, // Which columns to return sTmpFileName, // Which rows to return (all rows) null, // Selection arguments (none) null); // Order clause (none) if (myCursor != null) { int nRows = myCursor.getCount(); int nBytesRecvd = 0; for (int lcv = 0; lcv < nRows; lcv++) { if (myCursor.moveToPosition(lcv)) { byte[] buf = myCursor.getBlob(1); if (buf != null) { nBytesRecvd += buf.length; digest.update(buf, 0, buf.length); lTotalRead += nRead; buf = null; } } } myCursor.close(); byte[] hash = digest.digest(); sRet = getHex(hash); } } else { try { FileInputStream srcFile = new FileInputStream(sTmpFileName); while ((nRead = srcFile.read(buffer)) != -1) { digest.update(buffer, 0, nRead); lTotalRead += nRead; } srcFile.close(); byte[] hash = digest.digest(); sRet = getHex(hash); } catch (FileNotFoundException e) { sRet += " file not found"; } catch (IOException e) { sRet += " io exception"; e.printStackTrace(); } } return (sRet); }
From source file:org.sakaiproject.dav.DavServlet.java
/** * Initialize this servlet.// w w w. ja v a 2 s . c o m */ public void init() throws ServletException { contentHostingService = (ContentHostingService) ComponentManager.get(ContentHostingService.class.getName()); aliasService = ComponentManager.get(AliasService.class); // Set our properties from the initialization parameters String value = null; try { value = getServletConfig().getInitParameter("readonly"); if (value != null) readOnly = (new Boolean(value)).booleanValue(); } catch (Throwable t) { ; } try { value = getServletConfig().getInitParameter("secret"); if (value != null) secret = value; } catch (Throwable t) { ; } try { value = getServletConfig().getInitParameter("doprotected"); if (value != null) doProtected = (new Boolean(value)).booleanValue(); } catch (Throwable t) { ; } // load up the ignorePatterns from properties ignorePatterns = ServerConfigurationService.getStrings("webdav.ignore"); if (ignorePatterns != null) { String outVal = ""; for (int i = 0; i < ignorePatterns.length; i++) { if (outVal.length() > 0) outVal = outVal + " : "; outVal = outVal + ignorePatterns[i]; } M_log.info("ignore patterns:" + outVal); } // Load the MD5 helper used to calculate signatures. try { md5Helper = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new IllegalStateException(); } // Check cookie configuration useCookies = ServerConfigurationService.getBoolean("webdav.cookies", false); nonDavUserAgent = ServerConfigurationService.getStrings("webdav.nonDavUserAgent"); if (nonDavUserAgent == null) { nonDavUserAgent = new String[] { "Mozilla", "Opera", "BlackBerry" }; } }
From source file:org.ops4j.pax.web.service.jetty.internal.JettyFactoryImpl.java
/** * {@inheritDoc}/* w w w. j a va 2s.c om*/ */ @Override public ServerConnector createSecureConnector(Server server, String name, int port, String sslKeystore, String sslKeystorePassword, String sslKeyPassword, String host, String sslKeystoreType, String sslKeyAlias, String trustStore, String trustStorePassword, String trustStoreType, boolean isClientAuthNeeded, boolean isClientAuthWanted, List<String> cipherSuitesIncluded, List<String> cipherSuitesExcluded, List<String> protocolsIncluded, List<String> protocolsExcluded, Boolean sslRenegotiationAllowed, String crlPath, Boolean enableCRLDP, Boolean validateCerts, Boolean validatePeerCerts, Boolean enableOCSP, String ocspResponderURL) { // SSL Context Factory for HTTPS and SPDY SslContextFactory sslContextFactory = new SslContextFactory(); sslContextFactory.setKeyStorePath(sslKeystore); sslContextFactory.setKeyStorePassword(sslKeystorePassword); sslContextFactory.setKeyManagerPassword(sslKeyPassword); sslContextFactory.setNeedClientAuth(isClientAuthNeeded); sslContextFactory.setWantClientAuth(isClientAuthWanted); sslContextFactory.setEnableCRLDP(enableCRLDP); sslContextFactory.setValidateCerts(validateCerts); sslContextFactory.setValidatePeerCerts(validatePeerCerts); sslContextFactory.setEnableOCSP(enableOCSP); if ((null != crlPath) && (!"".equals(crlPath))) { sslContextFactory.setCrlPath(crlPath); } if ((null != ocspResponderURL) && (!"".equals(ocspResponderURL))) { sslContextFactory.setOcspResponderURL(ocspResponderURL); } if (sslKeystoreType != null) { sslContextFactory.setKeyStoreType(sslKeystoreType); } // Java key stores may contain more than one private key entry. // Specifying the alias tells jetty which one to use. if ((null != sslKeyAlias) && (!"".equals(sslKeyAlias))) { sslContextFactory.setCertAlias(sslKeyAlias); } // Quite often it is useful to use a certificate trust store other than the JVM default. if ((null != trustStore) && (!"".equals(trustStore))) { sslContextFactory.setTrustStorePath(trustStore); } if ((null != trustStorePassword) && (!"".equals(trustStorePassword))) { sslContextFactory.setTrustStorePassword(trustStorePassword); } if ((null != trustStoreType) && (!"".equals(trustStoreType))) { sslContextFactory.setTrustStoreType(trustStoreType); } // In light of well-known attacks against weak encryption algorithms such as RC4, // it is usefull to be able to include or exclude certain ciphersuites. // Due to the overwhelming number of cipher suites using regex to specify inclusions // and exclusions greatly simplifies configuration. final String[] cipherSuites; try { SSLContext context = SSLContext.getDefault(); SSLSocketFactory sf = context.getSocketFactory(); cipherSuites = sf.getSupportedCipherSuites(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Failed to get supported cipher suites.", e); } if (cipherSuitesIncluded != null && !cipherSuitesIncluded.isEmpty()) { final List<String> cipherSuitesToInclude = new ArrayList<>(); for (final String cipherSuite : cipherSuites) { for (final String includeRegex : cipherSuitesIncluded) { if (cipherSuite.matches(includeRegex)) { cipherSuitesToInclude.add(cipherSuite); } } } sslContextFactory.setIncludeCipherSuites( cipherSuitesToInclude.toArray(new String[cipherSuitesToInclude.size()])); } if (cipherSuitesExcluded != null && !cipherSuitesExcluded.isEmpty()) { final List<String> cipherSuitesToExclude = new ArrayList<>(); for (final String cipherSuite : cipherSuites) { for (final String excludeRegex : cipherSuitesExcluded) { if (cipherSuite.matches(excludeRegex)) { cipherSuitesToExclude.add(cipherSuite); } } } sslContextFactory.setExcludeCipherSuites( cipherSuitesToExclude.toArray(new String[cipherSuitesToExclude.size()])); } // In light of attacks against SSL 3.0 as "POODLE" it is useful to include or exclude // SSL/TLS protocols as needed. if ((null != protocolsIncluded) && (!protocolsIncluded.isEmpty())) { sslContextFactory.setIncludeProtocols(protocolsIncluded.toArray(new String[protocolsIncluded.size()])); } if ((null != protocolsExcluded) && (!protocolsExcluded.isEmpty())) { sslContextFactory.setExcludeProtocols(protocolsExcluded.toArray(new String[protocolsExcluded.size()])); } if (sslRenegotiationAllowed != null) { sslContextFactory.setRenegotiationAllowed(sslRenegotiationAllowed); } // HTTP Configuration HttpConfiguration httpConfig = new HttpConfiguration(); httpConfig.setSecureScheme(HttpScheme.HTTPS.asString()); httpConfig.setSecurePort(port); httpConfig.setOutputBufferSize(32768); // HTTPS Configuration HttpConfiguration httpsConfig = new HttpConfiguration(httpConfig); httpsConfig.addCustomizer(new SecureRequestCustomizer()); List<AbstractConnectionFactory> connectionFactories = new ArrayList<>(); HttpConnectionFactory httpConFactory = new HttpConnectionFactory(httpsConfig); SslConnectionFactory sslFactory = null; AbstractConnectionFactory http2Factory = null; NegotiatingServerConnectionFactory alpnFactory = null; if (alpnCLassesAvailable()) { log.info("HTTP/2 available, creating HttpSpdyServerConnector for Https"); // SPDY connector try { Class<?> comparatorClass = bundle.loadClass("org.eclipse.jetty.http2.HTTP2Cipher"); Comparator<String> cipherComparator = (Comparator<String>) FieldUtils .readDeclaredStaticField(comparatorClass, "COMPARATOR"); sslContextFactory.setCipherComparator(cipherComparator); sslFactory = new SslConnectionFactory(sslContextFactory, "h2"); connectionFactories.add(sslFactory); //org.eclipse.jetty.alpn.server.ALPNServerConnectionFactory Class<?> loadClass = bundle .loadClass("org.eclipse.jetty.http2.server.HTTP2ServerConnectionFactory"); // // //ALPNServerConnectionFactory alpn = new ALPNServerConnectionFactory("spdy/3", "http/1.1"); // alpnFactory = (NegotiatingServerConnectionFactory) ConstructorUtils.invokeConstructor(loadClass, (Object) new String[] {"ssl", "http/2", "http/1.1"}); // alpnFactory.setDefaultProtocol("http/1.1"); // connectionFactories.add(alpnFactory); //HTTPSPDYServerConnectionFactory spdy = new HTTPSPDYServerConnectionFactory(SPDY.V3, httpConfig); // loadClass = bundle.loadClass("org.eclipse.jetty.spdy.server.http.HTTPSPDYServerConnectionFactory"); // loadClass = bundle.loadClass("org.eclipse.jetty.http2.server.HTTP2ServerConnectionFactory"); http2Factory = (AbstractConnectionFactory) ConstructorUtils.invokeConstructor(loadClass, httpsConfig); connectionFactories.add(http2Factory); } catch (ClassNotFoundException | NoSuchMethodException | InvocationTargetException | IllegalArgumentException | IllegalAccessException | InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { log.info("SPDY not available, creating standard ServerConnector for Https"); sslFactory = new SslConnectionFactory(sslContextFactory, "http/1.1"); } // HttpConnectionFactory httpFactory = new HttpConnectionFactory(httpConfig); // // ServerConnector https = new ServerConnector(server); // HTTPS connector ServerConnector https = new ServerConnector(server, sslFactory, httpConFactory); for (AbstractConnectionFactory factory : connectionFactories) { https.addConnectionFactory(factory); } https.setPort(port); https.setName(name); https.setHost(host); https.setIdleTimeout(500000); /* SslContextFactory sslContextFactory = new SslContextFactory(); HttpConfiguration httpConfig = new HttpConfiguration(); SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory, "alpn"); ALPNServerConnectionFactory alpn = new ALPNServerConnectionFactory("spdy/3", "http/1.1"); alpn.setDefaultProtocol("http/1.1"); HTTPSPDYServerConnectionFactory spdy = new HTTPSPDYServerConnectionFactory(SPDY.V3, httpConfig); HttpConnectionFactory http = new HttpConnectionFactory(httpConfig); Server server = new Server(); ServerConnector connector = new ServerConnector(server, new ConnectionFactory[]{ssl, alpn, spdy, http}); */ return https; }
From source file:tv.acfun.video.player.resolver.SinaResolver.java
private static String getKey(String str) { try {//from ww w . j av a2 s . c om MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(str.getBytes()); byte[] bs = digest.digest(); StringBuilder builder = new StringBuilder(); for (int i = 0; i < bs.length; i++) { Byte b = Byte.valueOf(bs[i]); builder.append(String.format("%02x", b)); } return builder.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ""; }