List of usage examples for javax.xml.bind.annotation.adapters HexBinaryAdapter HexBinaryAdapter
HexBinaryAdapter
From source file:com.hybridbpm.core.util.HybridbpmCoreUtil.java
public static String hashPassword(String password) { try {//from w ww . j a v a 2s . com MessageDigest md = MessageDigest.getInstance("SHA-512"); md.update(password.getBytes("UTF-8")); byte[] bytes = md.digest(); return (new HexBinaryAdapter()).marshal(bytes); } catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) { logger.severe(ex.getMessage()); } return null; }
From source file:com.xumpy.thuisadmin.services.implementations.PersonenSrvImpl.java
@Override public String getMD5Password(String password) { try {/*from w w w.j av a2s .c om*/ MessageDigest md = MessageDigest.getInstance("MD5"); return (new HexBinaryAdapter()).marshal(md.digest(password.getBytes())).toLowerCase(); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(PersonenDaoPojo.class.getName()).log(Level.SEVERE, null, ex); return null; } }
From source file:com.hybridbpm.core.util.HybridbpmCoreUtil.java
public static String generateToken(String username) throws NoSuchAlgorithmException, UnsupportedEncodingException { try {//from w w w .j a v a2 s . c om SecureRandom random = new SecureRandom(); String token_data = UUID.randomUUID().toString() + username + System.nanoTime() + new BigInteger(32, random).toString(32); MessageDigest md = MessageDigest.getInstance("MD5"); md.update(token_data.getBytes("UTF-8")); byte[] bytes = md.digest(); return new HexBinaryAdapter().marshal(bytes); } catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) { logger.severe(ex.getMessage()); } return null; }
From source file:com.shuffle.bitcoin.blockchain.BlockchainDotInfo.java
/** * * This function takes in a transaction hash and passes it to Blockchain.info's API. * After some formatting, it returns a bitcoinj Transaction object using this transaction hash. * *//*from www . ja v a2 s . co m*/ public synchronized org.bitcoinj.core.Transaction getTransaction(String transactionHash) throws IOException { String url = "https://blockchain.info/tr/rawtx/" + transactionHash + "?format=hex"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("User-Agent", userAgent); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } HexBinaryAdapter adapter = new HexBinaryAdapter(); byte[] bytearray = adapter.unmarshal(response.toString()); // bitcoinj needs this Context variable Context context = Context.getOrCreate(netParams); return new org.bitcoinj.core.Transaction(netParams, bytearray); }
From source file:com.shuffle.bitcoin.blockchain.Btcd.java
/** * This method takes in a transaction hash and returns a bitcoinj transaction object. *//* ww w.j a va2 s . co m*/ synchronized org.bitcoinj.core.Transaction getTransaction(String transactionHash) throws IOException { org.bitcoinj.core.Transaction tx = null; String requestBody = "{\"jsonrpc\":\"2.0\",\"id\":\"null\",\"method\":\"getrawtransaction\", \"params\":[\"" + transactionHash + "\"]}"; HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Accept", "application/json"); Base64 b = new Base64(); String authString = rpcuser + ":" + rpcpass; String encoding = b.encodeAsString(authString.getBytes()); connection.setRequestProperty("Authorization", "Basic " + encoding); connection.setRequestProperty("Content-Length", Integer.toString(requestBody.getBytes().length)); connection.setDoInput(true); OutputStream out = connection.getOutputStream(); out.write(requestBody.getBytes()); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); JSONObject json = new JSONObject(response.toString()); String hexTx = (String) json.get("result"); HexBinaryAdapter adapter = new HexBinaryAdapter(); byte[] bytearray = adapter.unmarshal(hexTx); Context context = Context.getOrCreate(netParams); tx = new org.bitcoinj.core.Transaction(netParams, bytearray); } out.flush(); out.close(); return tx; }
From source file:de.tiqsolutions.hdfs.HadoopFileSystemProvider.java
private String getURIKey(URI uri) { String s = String.format("%s://%s@%s:%d", getScheme(), uri.getUserInfo() == null ? "" : uri.getUserInfo(), uri.getHost(), uri.getPort()); try {/*w ww . j a v a 2 s. c o m*/ MessageDigest cript = MessageDigest.getInstance("SHA-1"); cript.reset(); cript.update(s.getBytes("utf8")); return new HexBinaryAdapter().marshal(cript.digest()); } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) { } return null; }
From source file:com.shuffle.bitcoin.blockchain.BlockCypherDotCom.java
/** * * This function takes in a transaction hash and passes it to Blockchain.info's API. * After some formatting, it returns a bitcoinj Transaction object using this transaction hash. * *///from w w w . j ava 2 s . c om public synchronized org.bitcoinj.core.Transaction getTransaction(String transactionHash) throws IOException { rateLimiter.acquire(); String url; if (netParams == NetworkParameters.fromID(NetworkParameters.ID_TESTNET)) { url = "https://api.blockcypher.com/v1/btc/test3/txs/" + transactionHash + "?includeHex=true"; } else { url = "https://api.blockcypher.com/v1/btc/main/txs/" + transactionHash + "?includeHex=true"; } URL obj = new URL(url); rateLimiter.acquire(); JSONTokener tokener = new JSONTokener(obj.openStream()); JSONObject root = new JSONObject(tokener); HexBinaryAdapter adapter = new HexBinaryAdapter(); byte[] bytearray = adapter.unmarshal(root.get("hex").toString()); org.bitcoinj.core.Transaction transaction = new org.bitcoinj.core.Transaction(netParams, bytearray); return transaction; }
From source file:com.shuffle.bitcoin.blockchain.Btcd.java
/** * This method will take in an address hash and return a List of all transactions associated with * this address. These transactions are in bitcoinj's Transaction format. *//*from w w w .j av a 2 s . co m*/ public synchronized List<Transaction> getAddressTransactionsInner(String address) throws IOException { List<Transaction> txList = null; String requestBody = "{\"jsonrpc\":\"2.0\",\"id\":\"null\",\"method\":\"searchrawtransactions\", \"params\":[\"" + address + "\"]}"; HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Accept", "application/json"); Base64 b = new Base64(); String authString = rpcuser + ":" + rpcpass; String encoding = b.encodeAsString(authString.getBytes()); connection.setRequestProperty("Authorization", "Basic " + encoding); connection.setRequestProperty("Content-Length", Integer.toString(requestBody.getBytes().length)); connection.setDoInput(true); OutputStream out = connection.getOutputStream(); out.write(requestBody.getBytes()); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); JSONObject json = new JSONObject(response.toString()); JSONArray jsonarray = null; txList = new LinkedList<>(); if (json.isNull("result")) { return txList; } else { jsonarray = json.getJSONArray("result"); } for (int i = 0; i < jsonarray.length(); i++) { JSONObject currentJson = jsonarray.getJSONObject(i); String txid = currentJson.get("txid").toString(); HexBinaryAdapter adapter = new HexBinaryAdapter(); byte[] bytearray = adapter.unmarshal(currentJson.get("hex").toString()); Context context = Context.getOrCreate(netParams); int confirmations = Integer.parseInt(currentJson.get("confirmations").toString()); boolean confirmed; if (confirmations == 0) { confirmed = false; } else { confirmed = true; } org.bitcoinj.core.Transaction bitTx = new org.bitcoinj.core.Transaction(netParams, bytearray); Transaction tx = new Transaction(txid, bitTx, false, confirmed); txList.add(tx); } } out.flush(); out.close(); return txList; }
From source file:com.smartmarmot.dbforbix.config.Config.java
/** * calculates hash for config file//ww w. j ava 2s. co m * @throws NullPointerException - if hash is null */ private void calculateFileConfigHash() throws NullPointerException { MessageDigest md = null; byte[] b = new byte[2048]; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { LOG.error("Wrong algorithm provided while getting instance of MessageDigest: " + e.getMessage()); } /** * try with resources. Autoclosing after exitting try block */ try (InputStream is = Files.newInputStream(Paths.get(getConfigFile())); DigestInputStream dis = new DigestInputStream(is, md)) { while (dis.read(b) >= 0) ; } catch (IOException e) { LOG.error("Something has happenned reading file: " + e.getLocalizedMessage()); } try { setFileConfigHash((new HexBinaryAdapter()).marshal(md.digest())); } catch (Exception e) { LOG.error("Something has happenned converting md5 sum to string: " + e.getLocalizedMessage()); } if (null == getFileConfigHash()) throw new NullPointerException("Hash for config file is null!"); }
From source file:dk.dma.ais.store.FileExportRest.java
/** {@inheritDoc} */ @Override/*from ww w. ja va 2s . c o m*/ protected void run(Injector injector) throws Exception { printAisStoreNL("AIS STORE COMMAND LINE TOOL INITIATED"); printAisStoreLine(); // Hardcoded values // interval = "2015-1-5T14:00:00Z/2015-1-5T14:10:00Z"; // java -jar ais-store-cli-0.3-SNAPSHOT.jar export -area 15,-18,-10,14 -filter // "m.country=DNK & t.pos within bbox(15,-18,-10,14) & (t.lat<-0.3|t.lat>0.3) & (t.lon<-0.3|t.lon>0.3)" -fetchSize 30000 // -interval // java -jar ais-store-cli-0.3-SNAPSHOT.jar export -area 15,-18,-10,14 -filter // "m.country=DNK & t.pos within bbox(15,-18,-10,14) & (t.lat<-0.3|t.lat>0.3) & (t.lon<-0.3|t.lon>0.3)" -fetchSize 30000 // -interval 2015-1-5T14:00:00Z/2015-1-5T14:10:00Z // Create request String request = ""; if (interval == null || interval.equals("")) { printAisStoreNL("No Interval provided, please check your request."); // return; terminateAndPrintHelp(); } try { intervalVar = Interval.parse(interval); } catch (Exception e) { printAisStoreNL("Invalid Interval provided, please check your request."); terminateAndPrintHelp(); } // intervalVar = DateTimeUtil.toInterval(intervalStr); intervalStartTime = intervalVar.getStartMillis(); String intervalStr = interval.toString(); request = request + "?interval=" + interval; // System.out.println("Interval parsed correct " + intervalStr); // Check if interval is valid, throw exception etc // Create task for exception throwing if args are required // If error, throw exception of error description then -help if (mmsis.size() > 0) { request = request + "&mmsi="; for (int i = 0; i < mmsis.size() - 1; i++) { request = request + Integer.toString(mmsis.get(i)) + ","; } request = request + mmsis.get(mmsis.size() - 1); } // filter // Google URL Encoder // "t.name like H* & t.name like HAMLET" // CHeck if url filter is valid, then url encode it and add to request // filter = "t.name like H* & t.name like HAMLET"; // filter = "s.country in (DNK)"; if (filter != null && !filter.equals("")) { String encodedFilter = URLEncoder.encode(filter, "UTF-8"); try { AisPacketFilters.parseExpressionFilter(filter); } catch (Exception e) { printAisStoreNL("Invalid filter expression"); terminateAndPrintHelp(); } request = request + "&filter=" + encodedFilter; } // area // "&box=lat1,lon1,lat2,lon2" // blabla check if valid if (area != null && !area.equals("")) { request = request + "&box=" + area; } // If table, make sure column is added if ((columns == null || columns.equals("")) && (outputFormat.equals("table") || outputFormat.equals("jsonObject"))) { printAisStoreNL("When using outputFormat " + outputFormat + ", columns are required"); terminateAndPrintHelp(); } try { sink = AisPacketOutputSinks.getOutputSink(outputFormat, columns, separator); request = request + "&outputFormat=" + outputFormat; } catch (Exception e) { printAisStoreNL("Invalid output format provided, " + outputFormat + ", please check your request."); terminateAndPrintHelp(); } // if table do shit // columns \/ REQUIRED // "columns=mmsi;time;timestamp" // Check if valid // Split on ";" // "columns=<listElement0>:list1" if (columns != null) { request = request + "&columns=" + columns; } // seperator // "seperator=\t" // Url encode and add if (separator != null || !separator.equals("")) { String encodedSeparator = URLEncoder.encode(separator, "UTF-8"); request = request + "&seperator=" + encodedSeparator; } // fetchSize if (fetchSize != -1) { request = request + "&fetchsize=" + fetchSize; } // Get path from request, if none it will store in root of ais store client // filePath = "C:\\AisStoreData\\"; if (filePath == null) { filePath = ""; } else { filePath = filePath + "/"; } // No filename provided, generate unique based on request parameters if (fileName == null || fileName.equals("")) { MessageDigest md5 = MessageDigest.getInstance("MD5"); String hex = (new HexBinaryAdapter()).marshal(md5.digest(request.getBytes())); fileName = hex; } // Generate unique hashsum based on request metaFileName = fileName + ".aisstore"; // boolean isTryResume = true; // If we are trying to resume, don't override previous file try { fileOutputStream = new FileOutputStream(filePath + fileName, !forceDownload); } catch (Exception e) { printAisStoreNL("Error occuring writing to disk, make sure the folder path exists "); terminateAndPrintHelp(); } outputStream = new BufferedOutputStream(fileOutputStream); // Should we resume anything // We have read the file // If the file exists that means a previous transaction has been done // Do we resume, if we do, we need to find the resume point ie move the start interval /** * System.out.println("Test Compare"); System.out.println(intervalStr); * * DateTime time = new DateTime(interval.getStartMillis(), DateTimeZone.UTC); DateTime time2 = new * DateTime(interval.getEndMillis(), DateTimeZone.UTC); * * String newIntervalStr = dateTimeFormatter.withZoneUTC().print(time) + "/" + dateTimeFormatter.withZoneUTC().print(time2); * System.out.println(newIntervalStr); // DateTime dateTime = * dateTimeFormatter.parseDateTime("15-Oct-2013 11:34:26 AM").withZone(DateTimeZone.UTC); * * // System.out.println(dateTime); * * // Interval var = Interval.parse(intervalStr); // String dateStr = formatter.withZone(DateTimeZone.UTC).print(dateTime1); * // * * System.exit(0); **/ printAisStoreNL("Request generation complete."); printAisStoreNL("AIS Data will be saved to " + filePath + fileName); // System.out.println("--------------------------------------------------------------------------------"); // We are resuming, insert a Carriage Return Line Feed if (!forceDownload) { // Load the meta data in readMeta(); // We have processed some packages already if (packageCount != 0) { String str = "\r\n"; outputStream.write(str.getBytes()); printAisStoreLine(); printAisStoreNL("Resume detected - Updating Request"); // System.out.println("From " + intervalStr); // Update intervalStr DateTime time = new DateTime(lastLoadedTimestamp, DateTimeZone.UTC); DateTime time2 = new DateTime(intervalVar.getEndMillis(), DateTimeZone.UTC); intervalStr = dateTimeFormatter.withZoneUTC().print(time) + "/" + dateTimeFormatter.withZoneUTC().print(time2); // System.out.println("To " + intervalStr); printAisStoreLine(); // System.out.println("The last stored timestamp was \n" + lastLoadedTimestamp); // Interval interval2 = DateTimeUtil.toInterval(intervalStr); // System.out.println(interval2.getStartMillis()); } else { writeMetaInit(intervalVar.getStartMillis()); lastLoadedTimestamp = intervalVar.getStartMillis(); } } else { // We are starting a new request, create a new meta init writeMetaInit(intervalVar.getStartMillis()); lastLoadedTimestamp = intervalVar.getStartMillis(); } // System.out.println("Interval Str is " + intervalStr); // System.exit(0); // Initialize counter = new AtomicLong(packageCount); // Do we need to set a new interval start based on the meta data read? DefaultHttpClient httpClient = new DefaultHttpClient(); HttpHost target = new HttpHost("ais2.e-navigation.net", 443, "https"); request = "/aisview/rest/store/query" + request; HttpGet getRequest = new HttpGet(request); // HttpGet getRequest = new // HttpGet("/aisview/rest/store/query?interval=2015-1-1T10:00:00Z/2015-2-1T10:10:00Z&box=65.145,-5.373,34.450,76.893"); // + "&mmsi=219230000" // + "&mmsi=219230000" printAisStoreNL("Executing request to " + target); printAisStoreNL("Request is: " + request); HttpResponse httpResponse = httpClient.execute(target, getRequest); HttpEntity entity = httpResponse.getEntity(); // Check we have an OK from server etc. printAisStoreLine(); boolean terminateFailure = false; StatusLine reply = httpResponse.getStatusLine(); switch (reply.getStatusCode()) { case HttpStatus.SC_OK: printAisStoreNL("Server Accepted Connection, download will begin shortly"); printAisStoreLine(); break; default: printAisStoreNL("An error occured establishing connection to the server. "); printAisStoreNL( "Server returned Status Code " + reply.getStatusCode() + " with " + reply.getReasonPhrase()); terminateFailure = true; break; } if (terminateFailure) { return; } // System.out.println("Got reply " + reply.getReasonPhrase() + " status code " + reply.getStatusCode()); // String httpServerReply = httpResponse.getStatusLine(); // System.out.println(httpResponse.getStatusLine()); // // Header[] headers = httpResponse.getAllHeaders(); // for (int i = 0; i < headers.length; i++) { // System.out.println(headers[i]); // } // Do we use the footer? AisReader aisReader; if (entity != null) { InputStream inputStream = entity.getContent(); aisReader = aisReadWriter(inputStream); aisReader.start(); aisReader.join(); // Write the remainder still stored in buffer, update the final meta data with the finished data writeMetaUpdate(currentTimeStamp, counter.get()); // Write the footer sink.footer(outputStream, counter.get()); // Closer and flush the buffer outputStream.flush(); outputStream.close(); // Close and flush the file stream fileOutputStream.flush(); fileOutputStream.close(); } // print a new line to move on from previous /r printAisStoreNL( "Downloading AIS Data 100% Estimated Time Left: 00:00:00 "); printAisStoreLine(); printAisStoreNL("DOWNLOAD SUCCESS"); printAisStoreLine(); // We know current time long currentTime = System.currentTimeMillis(); // How long have we been running long millis = currentTime - timeStart; String timeLeftStr = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis), TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)), TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))); printAisStoreNL("Total Time " + timeLeftStr); printAisStoreNL("Finished at: " + new Date()); printAisStoreNL("Messages recieved " + counter); // printAisStore("Query took " + timeLeftStr); }