/** * Loads the entire stream into memory as a String and returns it. * * <p><b>Notice:</b> This implementation appends a <tt>\n</tt> as line terminator at the of the * text. * * <p>Warning, don't use for crazy big streams :) */ public static String loadText(InputStream in, boolean skipCommentOrEmptyLines) throws IOException { StringBuilder builder = new StringBuilder(); InputStreamReader isr = new InputStreamReader(in); try { BufferedReader reader = new BufferedReader(isr); while (true) { String line = reader.readLine(); if (line != null) { boolean empty = Strings.isNullOrEmpty(line); boolean comment = line.trim().startsWith("#"); if (skipCommentOrEmptyLines && (empty || comment)) { continue; } builder.append(line); builder.append("\n"); } else { break; } } return builder.toString(); } finally { close(isr, in); } }
public void loadGridNet(String mapGrid) throws IOException { Preconditions.checkArgument(!Strings.isNullOrEmpty(mapGrid)); logger.debug("loading {}...", mapGrid); CSVReader reader = new CSVReader(new FileReader(mapGrid), ',', '"', 1); String[] row; while ((row = reader.readNext()) != null) { String gridId = row[1].trim(); String dmRoads = row[2].trim(); String gjRoads = row[3].trim(); Set<String> x = Sets.newHashSet(Splitter.on('|').trimResults().omitEmptyStrings().split(dmRoads)); Set<String> y = Sets.newHashSet(Splitter.on('|').trimResults().omitEmptyStrings().split(gjRoads)); if (x.size() > 0 || y.size() > 0) { MapGrid grid = new MapGrid(); grid.dmRoads = x; grid.gjRoads = y; gridNet.put(gridId, grid); // logger.debug("{},{},{}", gridId, x, y); } } reader.close(); }
protected static void getServerUrlAsyn( String url, Boolean isCluster, String applicationKey, final OnRestWebserviceResponse onCompleted) throws MalformedURLException { if (!Strings.isNullOrEmpty(url) && isCluster) { getServerFromBalancerAsync(url, applicationKey, onCompleted); } else { onCompleted.run(null, url); } }
/** * Retrieves an Ortc Server url from the Ortc Balancer * * @param balancerUrl The Ortc Balancer url * @throws java.net.MalformedURLException */ public static void getServerFromBalancerAsync( String balancerUrl, String applicationKey, final OnRestWebserviceResponse onCompleted) throws MalformedURLException { Matcher protocolMatcher = urlProtocolPattern.matcher(balancerUrl); String protocol = protocolMatcher.matches() ? "" : protocolMatcher.group(1); String parsedUrl = String.format("%s%s", protocol, balancerUrl); if (!Strings.isNullOrEmpty(applicationKey)) { // CAUSE: Prefer String.format to + parsedUrl += String.format("?appkey=%s", applicationKey); } URL url = new URL(parsedUrl); RestWebservice.getAsync( url, new OnRestWebserviceResponse() { @Override public void run(Exception error, String response) { if (error != null) { onCompleted.run(error, null); } else { String clusterServer = null; Matcher matcher = balancerServerPattern.matcher(response); if (matcher.matches()) { clusterServer = matcher.group(1); } if (Strings.isNullOrEmpty(clusterServer)) { onCompleted.run(new InvalidBalancerServerException(response), null); } else { onCompleted.run(null, clusterServer); } } } }); }
protected static String getServerUrl(String url, Boolean isCluster, String applicationKey) { // CAUSE: Unused assignment String result; if (!Strings.isNullOrEmpty(url) && isCluster) { try { result = getServerFromBalancer(url, applicationKey); // CAUSE: Prefer throwing/catching meaningful exceptions instead of Exception } catch (MalformedURLException ex) { result = null; } catch (IOException ex) { result = null; } catch (InvalidBalancerServerException ex) { result = null; } } else { result = url; } return result; }
/** * Retrieves an Ortc Server url from the Ortc Balancer * * @param balancerUrl The Ortc Balancer url * @return An Ortc Server url * @throws java.io.IOException * @throws InvalidBalancerServerException */ public static String getServerFromBalancer(String balancerUrl, String applicationKey) throws IOException, InvalidBalancerServerException { Matcher protocolMatcher = urlProtocolPattern.matcher(balancerUrl); String protocol = protocolMatcher.matches() ? "" : protocolMatcher.group(1); String parsedUrl = String.format("%s%s", protocol, balancerUrl); if (!Strings.isNullOrEmpty(applicationKey)) { // CAUSE: Prefer String.format to + parsedUrl += String.format("?appkey=%s", applicationKey); } URL url = new URL(parsedUrl); // CAUSE: Unused assignment String clusterServer; clusterServer = unsecureRequest(url); return clusterServer; }
public List<RoadLink> loadRoadNet(String mif, String mid) throws IOException { Preconditions.checkArgument(!Strings.isNullOrEmpty(mif)); Preconditions.checkArgument(!Strings.isNullOrEmpty(mid)); logger.debug("loading {}...", mid); CSVReader reader = new CSVReader(new FileReader(mid), ',', '"', 0); String[] row; List<RoadLink> links = new ArrayList(); while ((row = reader.readNext()) != null) { RoadLink link = new RoadLink(); link.no = Integer.valueOf(row[0]); link.fromNode = Integer.valueOf(row[1]); link.toNode = Integer.valueOf(row[2]); link.name = row[3]; link.length = Double.valueOf(row[4]); link.ft = row[5]; link.tf = row[6]; link.combine = row[7]; link.overhead = row[8]; link.xmin = Double.valueOf(row[9]); link.ymin = Double.valueOf(row[10]); link.xmax = Double.valueOf(row[11]); link.ymax = Double.valueOf(row[12]); links.add(link); roadNet.put(link.no, link); } Charset charset = Charset.forName("UTF-8"); BufferedReader mifReader = Files.newBufferedReader(Paths.get(mif), charset); String line; int index = -1; int pos = -1; int segs = -1; Point2D prePoint = null; while ((line = mifReader.readLine()) != null) { List<String> cols = Lists.newArrayList( Splitter.on(CharMatcher.BREAKING_WHITESPACE) .trimResults() .omitEmptyStrings() .split(line)); // logger.debug("{}", line); if (cols.get(0).compareTo("PLINE") == 0) { index++; segs = Integer.valueOf(cols.get(1)); pos = 0; prePoint = null; } else if (cols.get(0).compareTo("LINE") == 0) { index++; RoadLink link = links.get(index); // link.segments.add(new Point2D.Double(Double.valueOf(cols.get(1)), // Double.valueOf(cols.get(2)))); // link.segments.add(new Point2D.Double(Double.valueOf(cols.get(3)), // Double.valueOf(cols.get(4)))); Segment seg = new Segment(); seg.start = new Point2D.Double(Double.valueOf(cols.get(1)), Double.valueOf(cols.get(2))); seg.end = new Point2D.Double(Double.valueOf(cols.get(3)), Double.valueOf(cols.get(4))); seg.length = seg.start.distance(seg.end); link.segments.add(seg); } else if (index >= 0) { if (prePoint == null) { prePoint = new Point2D.Double(Double.valueOf(cols.get(0)), Double.valueOf(cols.get(1))); } else { Segment seg = new Segment(); seg.start = prePoint; prePoint = new Point2D.Double(Double.valueOf(cols.get(0)), Double.valueOf(cols.get(1))); seg.end = prePoint; seg.length = seg.start.distance(seg.end); RoadLink link = links.get(index); link.segments.add(seg); } // RoadLink link = links.get(index); // link.segments.add(new Point2D.Double(Double.valueOf(cols.get(0)), // Double.valueOf(cols.get(1)))); } } return links; }
/** * Create a wallet from a seed phrase, timestamp and credentials * * @param seedPhrase the seed phrase to use in the restore * @param walletTypeToRestore the type of wallet to restore (one of the WalletType enum values) * @param timestamp the string format of the timestamp to use in the restore. May be blank in * which case the earliest HD birth date is used * @param password the password to use to secure the newly created wallet */ private boolean createWalletFromSeedPhraseAndTimestamp( List<String> seedPhrase, WalletType walletTypeToRestore, String timestamp, String password) { if (!verifySeedPhrase(seedPhrase)) { return false; } try { byte[] entropy = MnemonicCode.INSTANCE.toEntropy(seedPhrase); SeedPhraseGenerator seedGenerator = new Bip39SeedPhraseGenerator(); byte[] seed = seedGenerator.convertToSeed(seedPhrase); // Locate the user data directory File applicationDataDirectory = InstallationManager.getOrCreateApplicationDataDirectory(); if (Strings.isNullOrEmpty(timestamp)) { // Use the earliest possible HD wallet birthday timestamp = EARLIEST_HD_TIMESTAMP; } DateTime replayDate = Dates.parseSeedTimestamp(timestamp); // Provide some default text String name = Languages.safeText(MessageKey.WALLET); // Display in the system timezone String notes = Languages.safeText( MessageKey.WALLET_DEFAULT_NOTES, Dates.formatDeliveryDateLocal( Dates.nowUtc(), Configurations.currentConfiguration.getLocale())); switch (walletTypeToRestore) { case TREZOR_SOFT_WALLET: { // Create Trezor soft wallet WalletManager.INSTANCE.getOrCreateTrezorSoftWalletSummaryFromSeedPhrase( applicationDataDirectory, Joiner.on(" ").join(seedPhrase), Dates.thenInSeconds(replayDate), password, name, notes, true); return true; } case MBHD_SOFT_WALLET_BIP32: { // BIP32 compliant soft wallet WalletManager.INSTANCE.getOrCreateMBHDSoftWalletSummaryFromEntropy( applicationDataDirectory, entropy, seed, Dates.thenInSeconds(replayDate), password, name, notes, true); return true; } case MBHD_SOFT_WALLET: { // Beta 7 MBHD wallet - not BIP32 compliant WalletManager.INSTANCE.badlyGetOrCreateMBHDSoftWalletSummaryFromSeed( applicationDataDirectory, seed, Dates.thenInSeconds(replayDate), password, name, notes, true); return true; } default: { throw new IllegalArgumentException( "Cannot restore the wallet with unknown type " + walletTypeToRestore); } } } catch (Exception e) { log.error("Failed to restore wallet.", e); return false; } }