List of usage examples for org.apache.commons.codec.binary Hex encodeHex
public static char[] encodeHex(byte[] data)
From source file:codes.writeonce.maven.plugins.soy.CompileMojo.java
private void generateJs(List<Path> soyFiles, List<Path> xliffFiles, byte[] sourceDigestBytes) throws IOException, NoSuchAlgorithmException { final Path outputRootPath = jsOutputDirectory.toPath(); FileUtils.deleteDirectory(jsOutputDirectory); Files.createDirectories(outputRootPath); FileUtils.deleteDirectory(javaOutputDirectory); final Path javaSourceOutputPath = getJavaSourceOutputPath(); Files.createDirectories(javaSourceOutputPath); final SoyFileSet soyFileSet = getSoyFileSet(soyFiles); if (xliffFiles.isEmpty()) { getLog().info("No translations detected. Using default messages."); generateJs(soyFiles, soyFileSet, null, outputRootPath); } else {//w w w . ja v a 2 s . co m final SoyMsgBundleHandler smbh = new SoyMsgBundleHandler(new XliffMsgPlugin()); for (final Path xliffFilePath : xliffFiles) { final SoyMsgBundle smb = smbh.createFromFile(translations.toPath().resolve(xliffFilePath).toFile()); final Path outputPath = Utils.removeSuffix(outputRootPath.resolve(xliffFilePath), XLIFF_EXTENSION); generateJs(soyFiles, soyFileSet, smb, outputPath); } } final ImmutableMap<String, String> parseInfo = SoyFileSetAccessor.generateParseInfo(soyFileSet, javaPackage, javaClassNameSource.getValue()); final Charset classSourceCharset; if (StringUtils.isEmpty(javaOutputCharsetName)) { classSourceCharset = Charset.defaultCharset(); getLog().warn("Using platform encoding (" + classSourceCharset.displayName() + " actually) to generate SOY sources, i.e. build is platform dependent!"); } else { classSourceCharset = Charset.forName(javaOutputCharsetName); } for (final Map.Entry<String, String> entry : parseInfo.entrySet()) { final String classFileName = entry.getKey(); final String classSource = entry.getValue(); try (FileOutputStream out = new FileOutputStream(javaSourceOutputPath.resolve(classFileName).toFile()); OutputStreamWriter writer = new OutputStreamWriter(out, classSourceCharset)) { writer.write(classSource); } } final byte[] targetDigestBytes = getGeneratedFilesDigest(); final Path statusFilePath = getStatusFilePath(); Files.createDirectories(statusFilePath.getParent()); try (FileOutputStream out = new FileOutputStream(statusFilePath.toFile()); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(out, TEXT_DIGEST_CHARSET); BufferedWriter writer = new BufferedWriter(outputStreamWriter)) { writer.write(Hex.encodeHex(sourceDigestBytes)); writer.newLine(); writer.write(Hex.encodeHex(targetDigestBytes)); writer.newLine(); } }
From source file:com.ning.arecibo.util.timeline.times.TimelineCoderImpl.java
private byte[] combineTimelines(final List<byte[]> timesList) { final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final DataOutputStream dataStream = new DataOutputStream(outputStream); try {//w ww. jav a 2 s . c o m int lastTime = 0; int lastDelta = 0; int repeatCount = 0; int chunkCounter = 0; for (byte[] times : timesList) { final ByteArrayInputStream byteStream = new ByteArrayInputStream(times); final DataInputStream byteDataStream = new DataInputStream(byteStream); int byteCursor = 0; while (true) { // Part 1: Get the opcode, and come up with newTime, newCount and newDelta final int opcode = byteDataStream.read(); if (opcode == -1) { break; } byteCursor++; int newTime = 0; int newCount = 0; int newDelta = 0; boolean useNewDelta = false; boolean nonDeltaTime = false; if (opcode == TimelineOpcode.FULL_TIME.getOpcodeIndex()) { newTime = byteDataStream.readInt(); if (newTime < lastTime) { log.warn( "In TimelineCoder.combineTimeLines(), the fulltime read is %d, but the lastTime is %d; setting newTime to lastTime", newTime, lastTime); newTime = lastTime; } byteCursor += 4; if (lastTime == 0) { writeTime(0, newTime, dataStream); lastTime = newTime; lastDelta = 0; repeatCount = 0; continue; } else if (newTime - lastTime <= TimelineOpcode.MAX_DELTA_TIME) { newDelta = newTime - lastTime; useNewDelta = true; newCount = 1; } else { nonDeltaTime = true; } } else if (opcode <= TimelineOpcode.MAX_DELTA_TIME) { newTime = lastTime + opcode; newDelta = opcode; useNewDelta = true; newCount = 1; } else if (opcode == TimelineOpcode.REPEATED_DELTA_TIME_BYTE.getOpcodeIndex()) { newCount = byteDataStream.read(); newDelta = byteDataStream.read(); useNewDelta = true; byteCursor += 2; if (lastTime != 0) { newTime = lastTime + newDelta * newCount; } else { throw new IllegalStateException(String.format( "In TimelineCoder.combineTimelines, lastTime is 0 byte opcode = %d, byteCursor %d, chunkCounter %d, chunk %s", opcode, byteCursor, chunkCounter, new String(Hex.encodeHex(times)))); } } else if (opcode == TimelineOpcode.REPEATED_DELTA_TIME_SHORT.getOpcodeIndex()) { newCount = byteDataStream.readUnsignedShort(); newDelta = byteDataStream.read(); useNewDelta = true; byteCursor += 3; if (lastTime != 0) { newTime = lastTime + newDelta * newCount; } } else { throw new IllegalStateException(String.format( "In TimelineCoder.combineTimelines, Unrecognized byte opcode = %d, byteCursor %d, chunkCounter %d, chunk %s", opcode, byteCursor, chunkCounter, new String(Hex.encodeHex(times)))); } // Part 2: Combine existing state represented in lastTime, lastDelta and repeatCount with newTime, newCount and newDelta if (lastTime == 0) { log.error("In combineTimelines(), lastTime is 0; byteCursor %d, chunkCounter %d, times %s", byteCursor, chunkCounter, new String(Hex.encodeHex(times))); } else if (repeatCount > 0) { if (lastDelta == newDelta && newCount > 0) { repeatCount += newCount; lastTime = newTime; } else { writeRepeatedDelta(lastDelta, repeatCount, dataStream); if (useNewDelta) { lastDelta = newDelta; repeatCount = newCount; lastTime = newTime; } else { writeTime(lastTime, newTime, dataStream); lastTime = newTime; lastDelta = 0; repeatCount = 0; } } } else if (nonDeltaTime) { writeTime(lastTime, newTime, dataStream); lastTime = newTime; lastDelta = 0; repeatCount = 0; } else if (lastDelta == 0) { lastTime = newTime; repeatCount = newCount; lastDelta = newDelta; } } chunkCounter++; } if (repeatCount > 0) { writeRepeatedDelta(lastDelta, repeatCount, dataStream); } dataStream.flush(); return outputStream.toByteArray(); } catch (Exception e) { log.error(e, "In combineTimesLines(), exception combining timelines"); return new byte[0]; } }
From source file:com.konakart.actions.ipn.CyberpacAction.java
public String execute() { HttpServletRequest request = ServletActionContext.getRequest(); HttpServletResponse response = ServletActionContext.getResponse(); // Cyberpac Callback parameters if (log.isDebugEnabled()) { log.debug("*********** Cyberpac Callback"); }/*w w w . j a v a 2 s . com*/ // Create the outside of try / catch since they are needed in the case of a general // exception IpnHistoryIf ipnHistory = new IpnHistory(); ipnHistory.setOrderId(-1); ipnHistory.setModuleCode(code); String sessionId = null; KKAppEng kkAppEng = null; try { if (request == null) { return null; } // Process the parameters sent in the callback StringBuffer sb = new StringBuffer(); Enumeration<?> en = request.getParameterNames(); while (en.hasMoreElements()) { String paramName = (String) en.nextElement(); String paramValue = request.getParameter(paramName); if (sb.length() > 0) { sb.append("\n"); } sb.append(paramName); sb.append(" = "); sb.append(paramValue); } if (log.isDebugEnabled()) { log.debug("Cyberpac CallBack data:"); log.debug(sb.toString()); } // Some of the parameters returned by Cyberpac String ds_Signature = request.getParameter(Ds_Signature); String ds_Response = request.getParameter(Ds_Response); String ds_MerchantData = request.getParameter(Ds_MerchantData); String ds_AuthorisationCode = request.getParameter(Ds_AuthorisationCode); String ds_Amount = request.getParameter(Ds_Amount); String ds_Order = request.getParameter(Ds_Order); String ds_MerchantCode = request.getParameter(Ds_MerchantCode); String ds_Currency = request.getParameter(Ds_Currency); // Look up the SSO Token from the UUID String uuid = request.getParameter(ds_MerchantData); if (uuid == null) { throw new Exception("The callback from Cyberpac did not contain the 'Ds_MerchantCode' parameter."); } // Get an instance of the KonaKart engine kkAppEng = this.getKKAppEng(request, response); SSOTokenIf token = kkAppEng.getEng().getSSOToken(uuid, /* deleteToken */true); if (token == null) { throw new Exception("The SSOToken from the Cyberpac callback is null"); } try { // Get the order id from custom1 int orderId = Integer.parseInt(token.getCustom1()); ipnHistory.setOrderId(orderId); } catch (Exception e) { throw new Exception("The SSOToken does not contain an order id"); } // Use the session of the logged in user to initialise kkAppEng try { kkAppEng.getEng().checkSession(token.getSessionId()); } catch (KKException e) { throw new Exception("The SessionId from the SSOToken in the Cyberpac Callback is not valid: " + token.getSessionId()); } // Log in the user kkAppEng.getCustomerMgr().loginBySession(token.getSessionId()); sessionId = token.getSessionId(); // See if we need to send an email, by looking at the configuration String sendEmailsConfig = kkAppEng.getConfig(ConfigConstants.SEND_EMAILS); boolean sendEmail = false; if (sendEmailsConfig != null && sendEmailsConfig.equalsIgnoreCase("true")) { sendEmail = true; } // Fill more details of the IPN history class ipnHistory.setGatewayResult(ds_Response); ipnHistory.setGatewayFullResponse(sb.toString()); ipnHistory.setGatewayTransactionId(ds_AuthorisationCode); // Get integer value of ds_Response int ds_Response_int = -1; try { ds_Response_int = Integer.parseInt(ds_Response); } catch (Exception e) { throw new Exception("Ds_Response from Cyberpac does not contain a numeric value : " + ds_Response); } /* * Flag an error if the digital signature doesn't match */ String secretKey = kkAppEng.getConfig("MODULE_PAYMENT_CYBERPAC_SECRET_SIGNING_CODE"); String stringToSign = ds_Amount + ds_Order + ds_MerchantCode + ds_Currency + ds_Response + secretKey; MessageDigest md = MessageDigest.getInstance("SHA-1"); byte[] digest = md.digest(stringToSign.getBytes("UTF8")); String hexEncodedDigest = (Hex.encodeHex(digest)).toString(); if (log.isDebugEnabled()) { StringBuffer str = new StringBuffer(); str.append("Parameters to sign:").append("\n"); str.append("ds_Amount = ").append(ds_Amount).append("\n"); str.append("ds_Order = ").append(ds_Order).append("\n"); str.append("ds_MerchantCode = ").append(ds_MerchantCode).append("\n"); str.append("ds_Currency = ").append(ds_Currency).append("\n"); str.append("ds_Response = ").append(ds_Response).append("\n"); str.append("secretKey = ").append(secretKey).append("\n"); str.append("String to sign = ").append(stringToSign).append("\n"); str.append("SHA-1 result = ").append(hexEncodedDigest).append("\n"); str.append("ds_Signature = ").append(ds_Signature).append("\n"); log.debug(str); } if (ds_Signature == null || !ds_Signature.equals(hexEncodedDigest)) { ipnHistory.setKonakartResultDescription(RET5_DESC); ipnHistory.setKonakartResultId(RET5); kkAppEng.getEng().saveIpnHistory(sessionId, ipnHistory); return null; } OrderUpdateIf updateOrder = new OrderUpdate(); updateOrder.setUpdatedById(kkAppEng.getActiveCustId()); // If successful, we update the inventory as well as changing the state of the // order. String comment = null; if (ds_Response_int >= 0 && ds_Response_int <= 99) { comment = ORDER_HISTORY_COMMENT_OK + ds_AuthorisationCode; kkAppEng.getEng().updateOrder(sessionId, ipnHistory.getOrderId(), com.konakart.bl.OrderMgr.PAYMENT_RECEIVED_STATUS, sendEmail, comment, updateOrder); // If the order payment was approved we update the inventory kkAppEng.getEng().updateInventory(sessionId, ipnHistory.getOrderId()); if (sendEmail) { sendOrderConfirmationMail(kkAppEng, ipnHistory.getOrderId(), /* success */ true); } } else { comment = ORDER_HISTORY_COMMENT_KO + ds_Response; kkAppEng.getEng().updateOrder(sessionId, ipnHistory.getOrderId(), com.konakart.bl.OrderMgr.PAYMENT_DECLINED_STATUS, sendEmail, comment, updateOrder); if (sendEmail) { sendOrderConfirmationMail(kkAppEng, ipnHistory.getOrderId(), /* success */ false); } } ipnHistory.setKonakartResultDescription(RET0_DESC); ipnHistory.setKonakartResultId(RET0); kkAppEng.getEng().saveIpnHistory(sessionId, ipnHistory); return null; } catch (Exception e) { try { if (sessionId != null) { ipnHistory.setKonakartResultDescription(RET4_DESC); ipnHistory.setKonakartResultId(RET4); if (kkAppEng != null) { kkAppEng.getEng().saveIpnHistory(sessionId, ipnHistory); } } } catch (KKException e1) { e1.printStackTrace(); } e.printStackTrace(); return null; } finally { if (sessionId != null && kkAppEng != null) { try { kkAppEng.getEng().logout(sessionId); } catch (KKException e) { e.printStackTrace(); } } } }
From source file:com.ccstats.crypto.AESWorker.java
/** * Hashes the plain password to provide a more secure experience. * * @param password the bytes of the plaintext password. * * @return The hashed password's characters in an array. *//* www .j a va2s . com*/ private char[] hash(byte[] password) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("MD5"); md.reset(); md.update(password); return Hex.encodeHex(md.digest()); }
From source file:com.moz.fiji.schema.util.TestJsonEntityIdParser.java
@Test public void testShouldWorkWithRKF2SuppressedLayout() throws Exception { final TableLayoutDesc desc = FijiTableLayouts .getLayout(FijiTableLayouts.HASH_PREFIXED_FORMATTED_MULTI_COMPONENT); final FijiTableLayout layout = FijiTableLayout.newLayout(desc); // Construct complex entity id. final String eidString = String.format("[%s,%s,%s,%d,%d]", JSONObject.quote(UNUSUAL_STRING_EID), JSONObject.quote(UNUSUAL_STRING_EID), JSONObject.quote(UNUSUAL_STRING_EID), Integer.MIN_VALUE, Long.MAX_VALUE);/* w ww .j a v a2 s .c o m*/ final EntityId originalEid = ToolUtils.createEntityIdFromUserInputs(eidString, layout); final JsonEntityIdParser restEid1 = JsonEntityIdParser.create(originalEid, layout); final JsonEntityIdParser restEid2 = JsonEntityIdParser.create(eidString, layout); final JsonEntityIdParser restEid3 = JsonEntityIdParser.create( String.format("hbase_hex=%s", new String(Hex.encodeHex((originalEid.getHBaseRowKey())))), layout); final JsonEntityIdParser restEid4 = JsonEntityIdParser .create(String.format("hbase=%s", Bytes.toStringBinary(originalEid.getHBaseRowKey())), layout); // Resolved entity id should match origin entity id. assertEquals(originalEid, restEid1.getEntityId()); assertEquals(originalEid, restEid2.getEntityId()); assertEquals(originalEid, restEid3.getEntityId()); assertEquals(originalEid, restEid4.getEntityId()); }
From source file:com.ning.arecibo.util.timeline.samples.TestSampleCoder.java
@SuppressWarnings("unchecked") @Test(groups = "fast") public void testCombineMoreThan65KSamples() throws Exception { int count = 0; final TimelineChunkAccumulator accum = new TimelineChunkAccumulator(0, 0, sampleCoder); final List<ScalarSample> samples = new ArrayList<ScalarSample>(); final ScalarSample sample1 = new ScalarSample(SampleOpcode.BYTE, (byte) 1); final ScalarSample sample2 = new ScalarSample(SampleOpcode.BYTE, (byte) 2); for (int i = 0; i < 20; i++) { samples.add(sample1);/*from w w w. j a v a 2 s.co m*/ accum.addSample(sample1); } for (int i = 0; i < 0xFFFF + 100; i++) { samples.add(sample2); accum.addSample(sample2); } final byte[] sampleBytes = sampleCoder.compressSamples(samples); final String hex = new String(Hex.encodeHex(sampleBytes)); // Here are the compressed samples: ff140101feffff0102ff640102 // Translation: // [ff 14 01 01] means repeat 20 times BYTE value 1 // [fe ff ff 01 02] means repeat 65525 times BYTE value 2 // [ff 64 01 02] means repeat 100 times BYTE value 2 Assert.assertEquals(sampleBytes, Hex.decodeHex("ff140101feffff0102ff640102".toCharArray())); final List<ScalarSample> restoredSamples = sampleCoder.decompressSamples(sampleBytes); Assert.assertEquals(restoredSamples.size(), samples.size()); for (int i = 0; i < count; i++) { Assert.assertEquals(restoredSamples.get(i), samples.get(i)); } }
From source file:edu.hawaii.soest.kilonalu.adam.AdamDispatcher.java
/** * A method that executes the streaming of data from the source to the RBNB * server after all configuration of settings, connections to hosts, and * thread initiatizing occurs. This method contains the detailed code for * streaming the data and interpreting the stream. *//*from w w w .ja v a2 s . com*/ protected boolean execute() { logger.info("AdamDispatcher.execute() called."); // do not execute the stream if there is no connection if (!isConnected()) return false; boolean failed = false; // while data are being sent, read them into the buffer try { // Create a buffer that will store the sample bytes as they are read byte[] bufferArray = new byte[getBufferSize()]; // and a ByteBuffer used to transfer the bytes to the parser ByteBuffer sampleBuffer = ByteBuffer.allocate(getBufferSize()); this.datagramPacket = new DatagramPacket(bufferArray, bufferArray.length); // while there are bytes to read from the socket ... while (!failed) { // receive any incoming UDP packets and parse the data payload datagramSocket.receive(this.datagramPacket); logger.debug("Host: " + datagramPacket.getAddress() + " data: " + new String(Hex.encodeHex(datagramPacket.getData()))); // the address seems to be returned with a leading slash (/). Trim it. String datagramAddress = datagramPacket.getAddress().toString().replaceAll("/", ""); sampleBuffer.put(datagramPacket.getData()); // Given the IP address of the source UDP packet and the data ByteBuffer, // find the correct source in the sourceMap hash and process the data if (sourceMap.get(datagramAddress) != null) { AdamSource source = sourceMap.get(datagramAddress); // process the data using the AdamSource driver source.process(datagramAddress, this.xmlConfiguration, sampleBuffer); } else { logger.debug("There is no configuration information for " + "the ADAM module at " + datagramAddress + ". Please add the configuration to the " + "sensor.properties.xml configuration file."); } sampleBuffer.clear(); } // end while (more socket bytes to read) disconnect(); // } catch (IOException e) { // handle exceptions // In the event of an i/o exception, log the exception, and allow execute() // to return false, which will prompt a retry. failed = true; e.printStackTrace(); return !failed; } return !failed; }
From source file:com.spidertracks.datanucleus.query.runtime.EqualityOperand.java
@Override public void toString(final StringBuilder sb) { final List<IndexExpression> expList = this.clause.getExpressions(); int i;/*from w w w . j a v a 2 s . c o m*/ for (i = 0; i < expList.size(); i++) { if (i > 0) { sb.append(" AND "); } final IndexExpression exp = expList.get(i); sb.append(new String(exp.column_name.array())); switch (exp.op) { case EQ: sb.append(" = "); break; case GTE: sb.append(" >= "); break; case GT: sb.append(" > "); break; case LTE: sb.append(" <= "); break; case LT: sb.append(" < "); break; default: throw new RuntimeException("Unhandled operand [" + exp.op + "]"); } ; final String val = new String(exp.value.array()); if (!StringUtils.isAsciiPrintable(val)) { sb.append("hex('"); sb.append(new String(Hex.encodeHex(exp.value.array()))); sb.append("')"); } else { sb.append('\'').append(val.replace("\\", "\\\\").replace("'", "\\'")).append('\''); } } sb.append(" "); }
From source file:ie.peternagy.jcrypto.algo.EllipticCurveWrapper.java
/** * Write the keys to disk//from w w w . j a va2 s . c o m */ protected void writeKeys() { char[] publicBytes = Hex.encodeHex(publicKey.getEncoded()); char[] privateBytes = Hex.encodeHex(privateKey.getEncoded()); FileAccessUtil.writeToDisk(getKeyFilePath(false), new String(publicBytes).getBytes()); FileAccessUtil.writeToDisk(getKeyFilePath(true), new String(privateBytes).getBytes()); }
From source file:com.jpeterson.util.etag.FileETagTest.java
/** * Test the calculate method when using file last modified. *///from w w w . j ava 2 s.c o m public void test_calculateLastModified() { File file; String content = "Hello, world!"; String expected; FileETag etag; try { // create temporary file file = File.createTempFile("temp", "txt"); // make sure that it gets cleaned up file.deleteOnExit(); // put some date in the file FileOutputStream out = new FileOutputStream(file); out.write(content.getBytes()); out.flush(); out.close(); // manipulate the last modified value to a "known" value SimpleDateFormat date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); long lastModified = date.parse("06/21/2007 11:19:36").getTime(); file.setLastModified(lastModified); // determined expected StringBuffer buffer = new StringBuffer(); buffer.append(lastModified); MessageDigest messageDigest = MessageDigest.getInstance("MD5"); expected = new String(Hex.encodeHex(messageDigest.digest(buffer.toString().getBytes()))); etag = new FileETag(); etag.setFlags(FileETag.FLAG_MTIME); String value = etag.calculate(file); assertEquals("Unexpected value", expected, value); } catch (FileNotFoundException e) { e.printStackTrace(); fail("Unexpected exception"); } catch (IOException e) { e.printStackTrace(); fail("Unexpected exception"); } catch (ParseException e) { e.printStackTrace(); fail("Unexpected exception"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); fail("Unexpected exception"); } }