List of usage examples for javax.xml.bind DatatypeConverter printHexBinary
public static String printHexBinary(byte[] val)
Converts an array of bytes into a string.
From source file:org.openhab.binding.powermax.internal.message.PowerMaxCommDriver.java
/** * Send a message or delay the sending if time frame for receiving response is not ended * * @param msg/*from ww w . ja va2 s.com*/ * the message to be sent * @param immediate * true if the message has to be send without considering timing * @param waitTime * the delay in seconds to wait * * @return true if the message was sent or the sending is delayed; false in other cases */ private synchronized boolean sendMessage(PowerMaxBaseMessage msg, boolean immediate, int waitTime) { if ((waitTime > 0) && (msg != null)) { logger.debug("sendMessage(): delay ({} s) sending message (type {})", waitTime, msg.getSendType().toString()); Timer timer = new Timer(); // Don't queue the message timer.schedule(new DelayedSendTask(msg), waitTime * 1000); return true; } if (msg == null) { msg = msgQueue.peek(); if (msg == null) { logger.debug("sendMessage(): nothing to send"); return false; } } // Delay sending if time frame for receiving response is not ended long delay = WAITING_DELAY_FOR_RESPONSE - (System.currentTimeMillis() - connector.getWaitingForResponse()); PowerMaxBaseMessage msgToSend = msg; if (!immediate) { msgToSend = msgQueue.peek(); if (msgToSend != msg) { logger.debug("sendMessage(): add message in queue (type {})", msg.getSendType().toString()); msgQueue.offer(msg); msgToSend = msgQueue.peek(); } if ((msgToSend != msg) && (delay > 0)) { return true; } else if ((msgToSend == msg) && (delay > 0)) { if (delay < 100) { delay = 100; } logger.debug("sendMessage(): delay ({} ms) sending message (type {})", delay, msgToSend.getSendType().toString()); Timer timer = new Timer(); timer.schedule(new DelayedSendTask(null), delay); return true; } else { msgToSend = msgQueue.poll(); } } if (logger.isDebugEnabled()) { logger.debug("sendMessage(): sending {} message {}", msgToSend.getSendType().toString(), DatatypeConverter.printHexBinary(msgToSend.getRawData())); } boolean done = sendMessage(msgToSend.getRawData()); if (done) { lastSendMsg = msgToSend; connector.setWaitingForResponse(System.currentTimeMillis()); if (!immediate && (msgQueue.peek() != null)) { logger.debug("sendMessage(): delay sending next message (type {})", msgQueue.peek().getSendType().toString()); Timer timer = new Timer(); timer.schedule(new DelayedSendTask(null), WAITING_DELAY_FOR_RESPONSE); } } else { logger.debug("sendMessage(): failed"); } return done; }
From source file:org.openhab.binding.rflink.connector.RfLinkSerialConnector.java
@Override public void sendMessage(byte[] data) throws IOException { if (output == null) { throw new IOException("Not connected, sending messages is not possible"); }//from w ww.j a v a 2 s. c o m synchronized (this) { long towait = SEND_DELAY - (System.currentTimeMillis() - lastSend); towait = Math.min(Math.max(towait, 0), SEND_DELAY); logger.debug("Send data (after {}ms, len={}): {}", towait, data.length, DatatypeConverter.printHexBinary(data)); if (towait > 0) { try { Thread.sleep(towait); } catch (InterruptedException ignore) { } } output.write(data); output.flush(); lastSend = System.currentTimeMillis(); } }
From source file:org.openhab.binding.rfxcom.internal.connector.RFXComJD2XXConnector.java
@Override public void sendMessage(byte[] data) throws IOException { logger.trace("Send data (len={}): {}", data.length, DatatypeConverter.printHexBinary(data)); out.write(data);/*from w w w. ja va 2s . c om*/ }
From source file:org.openhab.binding.rfxcom.internal.connector.RFXComTcpConnector.java
@Override public void sendMessage(byte[] data) throws IOException { logger.trace("Send data (len={}): {}", data.length, DatatypeConverter.printHexBinary(data)); out.write(data);/*from w w w . jav a 2 s.c o m*/ out.flush(); }
From source file:org.primefaces.virusscan.impl.VirusTotalVirusScanner.java
@Override public void performVirusScan(InputStream inputStream) throws VirusException { ExternalContext ctx = FacesContext.getCurrentInstance().getExternalContext(); String key = ctx.getInitParameter(CONTEXT_PARAM_KEY); try {// w w w. j a v a2s .c o m byte[] content = IOUtils.toByteArray(inputStream); MessageDigest md = MessageDigest.getInstance("MD5"); md.update(content); String hash = DatatypeConverter.printHexBinary(md.digest()); URL url = new URL(String.format(API_ENDPOINT, EscapeUtils.forUriComponent(key), EscapeUtils.forUriComponent(hash))); try (InputStream response = url.openStream()) { JSONObject json = new JSONObject(IOUtils.toString(response, "UTF-8")); int responseCode = json.getInt("response_code"); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(String.format("Retrieved response code %d.", responseCode)); } if (responseCode == 1) { // present int positives = json.getInt("positives"); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine(String.format("Retrieved %d positives.", positives)); } if (positives > 0) { throw new VirusException(); } } } } catch (IOException | NoSuchAlgorithmException ex) { if (LOGGER.isLoggable(Level.WARNING)) { LOGGER.log(Level.WARNING, "Cannot perform virus scan", ex); } throw new RuntimeException("Cannot perform virus scan"); } }
From source file:org.roda_project.commons_ip.model.impl.eark.EARKAIP.java
private void writeFileToPath(final ZipEntryInfo zipEntryInfo, final Path outputPath, final boolean onlyMets) throws IOException, NoSuchAlgorithmException { InputStream is = null;//from w w w . ja v a2s .c o m OutputStream os = null; try { is = Files.newInputStream(zipEntryInfo.getFilePath()); if (!onlyMets || zipEntryInfo instanceof METSZipEntryInfo) { Files.createDirectories(outputPath.getParent()); os = Files.newOutputStream(outputPath); } else { os = new NullOutputStream(); } final byte[] buffer = new byte[4096]; final MessageDigest complete = MessageDigest.getInstance(IPConstants.CHECKSUM_ALGORITHM); int numRead; do { numRead = is.read(buffer); if (numRead > 0) { complete.update(buffer, 0, numRead); if (!onlyMets || zipEntryInfo instanceof METSZipEntryInfo) { os.write(buffer, 0, numRead); } } } while (numRead != -1); setChecksum(zipEntryInfo, DatatypeConverter.printHexBinary(complete.digest()), IPConstants.CHECKSUM_ALGORITHM); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } }
From source file:org.roda_project.commons_ip.utils.Utils.java
/** * Calculates checksum, closing the inputstream in the end. *//* w w w. j a v a2s . co m*/ public static String calculateChecksum(InputStream is, String algorithm) throws NoSuchAlgorithmException, IOException { MessageDigest digester = MessageDigest.getInstance(algorithm); try { byte[] block = new byte[4096]; int length; while ((length = is.read(block)) > 0) { digester.update(block, 0, length); } } finally { is.close(); } return DatatypeConverter.printHexBinary(digester.digest()); }
From source file:org.roda_project.commons_ip.utils.ZIPUtils.java
public static Map<String, String> calculateChecksums(Optional<ZipOutputStream> zos, InputStream inputStream, Set<String> checksumAlgorithms) throws NoSuchAlgorithmException, IOException { byte[] buffer = new byte[4096]; Map<String, String> values = new HashMap<>(); // instantiate different checksum algorithms Map<String, MessageDigest> algorithms = new HashMap<>(); for (String alg : checksumAlgorithms) { algorithms.put(alg, MessageDigest.getInstance(alg)); }/*from w ww .j av a 2 s . com*/ // calculate value for each one of the algorithms int numRead; do { numRead = inputStream.read(buffer); if (numRead > 0) { for (Entry<String, MessageDigest> alg : algorithms.entrySet()) { alg.getValue().update(buffer, 0, numRead); } if (zos.isPresent()) { zos.get().write(buffer, 0, numRead); } } } while (numRead != -1); // generate hex versions of the digests algorithms.forEach((alg, dig) -> values.put(alg, DatatypeConverter.printHexBinary(dig.digest()))); return values; }
From source file:org.sakaiproject.lessonbuildertool.service.LessonBuilderAccessService.java
public void init() { lessonBuilderAccessAPI.setHttpAccess(getHttpAccess()); accessCache = memoryService.createCache( "org.sakaiproject.lessonbuildertool.service.LessonBuilderAccessService.cache", new SimpleConfiguration<Object, Object>(CACHE_MAX_ENTRIES, CACHE_TIME_TO_LIVE_SECONDS, CACHE_TIME_TO_IDLE_SECONDS)); SimplePageItem metaItem = null;// w ww . ja v a2 s. c om // Get crypto session key from metadata item // we have to keep it in the database so it's the same on all servers // There's no entirely sound way to create the item if it doesn't exist // other than by getting a table lock. Fortunately this will only be // needed when the entry is created. SimplePageProperty prop = simplePageToolDao.findProperty("accessCryptoKey"); if (prop == null) { try { sessionKey = KeyGenerator.getInstance("Blowfish").generateKey(); // need string version to save in item byte[] keyBytes = ((SecretKeySpec) sessionKey).getEncoded(); // set attribute to hex version of key prop = simplePageToolDao.makeProperty("accessCryptoKey", DatatypeConverter.printHexBinary(keyBytes)); simplePageToolDao.quickSaveItem(prop); } catch (Exception e) { System.out.println("unable to init cipher for session " + e); // in case of race condition, our save will fail, but we'll be able to get a value // saved by someone else simplePageToolDao.flush(); prop = simplePageToolDao.findProperty("accessCryptoKey"); } } if (prop != null) { String keyString = prop.getValue(); byte[] keyBytes = DatatypeConverter.parseHexBinary(keyString); sessionKey = new SecretKeySpec(keyBytes, "Blowfish"); } }
From source file:org.sakaiproject.lessonbuildertool.tool.producers.ShowPageProducer.java
public String getSessionParameter(String url) { UsageSession session = UsageSessionService.getSession(); if (!url.startsWith("/access/lessonbuilder")) return null; url = url.substring("/access/lessonbuilder".length()); try {/*ww w. j a v a 2s . c om*/ Cipher sessionCipher = Cipher.getInstance("Blowfish"); sessionCipher.init(Cipher.ENCRYPT_MODE, lessonBuilderAccessService.getSessionKey()); String sessionParam = session.getId() + ":" + url; byte[] sessionBytes = sessionParam.getBytes("UTF8"); sessionBytes = sessionCipher.doFinal(sessionBytes); sessionParam = DatatypeConverter.printHexBinary(sessionBytes); return sessionParam; } catch (Exception e) { System.out.println("unable to generate encrypted session id " + e); return null; } }