Search in sources :

Example 36 with Splitter

use of com.google.common.base.Splitter in project bitcoin-wallet by bitcoin-wallet.

the class AlertDialogsFragment method process.

private void process() {
    final PackageInfo packageInfo = application.packageInfo();
    final HttpUrl.Builder url = Constants.VERSION_URL.newBuilder();
    url.addEncodedQueryParameter("package", packageInfo.packageName);
    final String installerPackageName = Installer.installerPackageName(application);
    if (installerPackageName != null)
        url.addEncodedQueryParameter("installer", installerPackageName);
    url.addQueryParameter("sdk", Integer.toString(Build.VERSION.SDK_INT));
    url.addQueryParameter("current", Integer.toString(packageInfo.versionCode));
    final HttpUrl versionUrl = url.build();
    AsyncTask.execute(() -> {
        try {
            log.debug("querying \"{}\"...", versionUrl);
            final Request.Builder request = new Request.Builder();
            request.url(versionUrl);
            final Headers.Builder headers = new Headers.Builder();
            headers.add("Accept-Charset", "utf-8");
            final String userAgent = application.httpUserAgent();
            if (userAgent != null)
                headers.add("User-Agent", userAgent);
            request.headers(headers.build());
            final Builder httpClientBuilder = Constants.HTTP_CLIENT.newBuilder();
            httpClientBuilder.connectionSpecs(Collections.singletonList(ConnectionSpec.RESTRICTED_TLS));
            final Call call = httpClientBuilder.build().newCall(request.build());
            final Response response = call.execute();
            if (response.isSuccessful()) {
                // Maybe show timeskew alert.
                final Date serverDate = response.headers().getDate("Date");
                if (serverDate != null) {
                    final long diffMinutes = Math.abs((System.currentTimeMillis() - serverDate.getTime()) / DateUtils.MINUTE_IN_MILLIS);
                    if (diffMinutes >= 60) {
                        log.info("according to \"" + versionUrl + "\", system clock is off by " + diffMinutes + " minutes");
                        viewModel.showTimeskewAlertDialog.postValue(new Event<>(diffMinutes));
                        return;
                    }
                }
                // Read properties from server.
                final Map<String, String> properties = new HashMap<>();
                try (final BufferedReader reader = new BufferedReader(response.body().charStream())) {
                    while (true) {
                        final String line = reader.readLine();
                        if (line == null)
                            break;
                        if (line.charAt(0) == '#')
                            continue;
                        final Splitter splitter = Splitter.on('=').trimResults();
                        final Iterator<String> split = splitter.split(line).iterator();
                        if (!split.hasNext())
                            continue;
                        final String key = split.next();
                        if (!split.hasNext()) {
                            properties.put(null, key);
                            continue;
                        }
                        final String value = split.next();
                        if (!split.hasNext()) {
                            properties.put(key.toLowerCase(Locale.US), value);
                            continue;
                        }
                        log.info("Ignoring line: {}", line);
                    }
                }
                // Maybe show version alert.
                String versionKey = null;
                String version = null;
                if (installer != null) {
                    versionKey = "version." + installer.name().toLowerCase(Locale.US);
                    version = properties.get(versionKey);
                }
                if (version == null) {
                    versionKey = "version";
                    version = properties.get(versionKey);
                }
                if (version != null) {
                    log.info("according to \"{}\", strongly recommended minimum app {} is \"{}\"", versionUrl, versionKey, version);
                    final Integer recommendedVersionCode = Ints.tryParse(version);
                    if (recommendedVersionCode != null) {
                        if (recommendedVersionCode > application.packageInfo().versionCode) {
                            viewModel.showVersionAlertDialog.postValue(Event.simple());
                            return;
                        }
                    }
                }
                // Maybe show insecure device alert.
                if (Build.VERSION.SECURITY_PATCH.compareToIgnoreCase(Constants.SECURITY_PATCH_INSECURE_BELOW) < 0) {
                    viewModel.showInsecureDeviceAlertDialog.postValue(new Event<>(Constants.SECURITY_PATCH_INSECURE_BELOW));
                    return;
                }
                // Maybe show insecure bluetooth alert.
                final String minSecurityPatchLevel = properties.get("min.security_patch.bluetooth");
                if (minSecurityPatchLevel != null) {
                    log.info("according to \"{}\", minimum security patch level for bluetooth is {}", versionUrl, minSecurityPatchLevel);
                    if (Build.VERSION.SECURITY_PATCH.compareTo(minSecurityPatchLevel) < 0) {
                        final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
                        if (bluetoothAdapter != null && BluetoothAdapter.getDefaultAdapter().isEnabled()) {
                            viewModel.showInsecureBluetoothAlertDialog.postValue(new Event<>(minSecurityPatchLevel));
                            return;
                        }
                    }
                }
                // Maybe show low storage alert.
                final Intent stickyIntent = activity.registerReceiver(null, new IntentFilter(Intent.ACTION_DEVICE_STORAGE_LOW));
                if (stickyIntent != null) {
                    viewModel.showLowStorageAlertDialog.postValue(Event.simple());
                    return;
                }
                // Maybe show too much balance alert.
                if (Constants.NETWORK_PARAMETERS.getId().equals(MainNetParams.ID_MAINNET)) {
                    final Coin balance = application.getWallet().getBalance();
                    if (balance.isGreaterThan(Constants.TOO_MUCH_BALANCE_THRESHOLD)) {
                        viewModel.showTooMuchBalanceAlertDialog.postValue(Event.simple());
                        return;
                    }
                }
                log.info("all good, no alert dialog shown");
            }
        } catch (final Exception x) {
            if (x instanceof UnknownHostException || x instanceof SocketException || x instanceof SocketTimeoutException) {
                // swallow
                log.debug("problem reading", x);
            } else {
                CrashReporter.saveBackgroundTrace(new RuntimeException(versionUrl.toString(), x), application.packageInfo());
                log.warn("problem parsing", x);
            }
        }
    });
}
Also used : SocketException(java.net.SocketException) HashMap(java.util.HashMap) Headers(okhttp3.Headers) Builder(okhttp3.OkHttpClient.Builder) Coin(org.bitcoinj.core.Coin) Call(okhttp3.Call) IntentFilter(android.content.IntentFilter) Splitter(com.google.common.base.Splitter) UnknownHostException(java.net.UnknownHostException) PackageInfo(android.content.pm.PackageInfo) Request(okhttp3.Request) Intent(android.content.Intent) HttpUrl(okhttp3.HttpUrl) Date(java.util.Date) SocketException(java.net.SocketException) SocketTimeoutException(java.net.SocketTimeoutException) UnknownHostException(java.net.UnknownHostException) Response(okhttp3.Response) SocketTimeoutException(java.net.SocketTimeoutException) BufferedReader(java.io.BufferedReader) BluetoothAdapter(android.bluetooth.BluetoothAdapter)

Example 37 with Splitter

use of com.google.common.base.Splitter in project snow-owl by b2ihealthcare.

the class BranchPath method lastSegment.

/* (non-Javadoc)
	 * @see com.b2international.snowowl.core.api.IBranchPath#lastSegment()
	 */
@Override
public String lastSegment() {
    if (BranchPathUtils.isMain(this)) {
        return IBranchPath.MAIN_BRANCH;
    }
    if (StringUtils.isEmpty(path)) {
        return IBranchPath.EMPTY_PATH;
    }
    final Splitter splitter = Splitter.on(IBranchPath.SEPARATOR_CHAR).omitEmptyStrings().trimResults();
    final Iterable<String> segments = splitter.split(path);
    return Iterables.getLast(segments, IBranchPath.EMPTY_PATH);
}
Also used : Splitter(com.google.common.base.Splitter)

Example 38 with Splitter

use of com.google.common.base.Splitter in project bazel by bazelbuild.

the class WorkspaceStatusAction method parseValues.

/**
   * Parses the output of the workspace status action.
   *
   * <p>The output is a text file with each line representing a workspace status info key.
   * The key is the part of the line before the first space and should consist of the characters
   * [A-Z_] (although this is not checked). Everything after the first space is the value.
   */
public static Map<String, String> parseValues(Path file) throws IOException {
    HashMap<String, String> result = new HashMap<>();
    Splitter lineSplitter = Splitter.on(' ').limit(2);
    for (String line : Splitter.on('\n').split(new String(FileSystemUtils.readContentAsLatin1(file)))) {
        List<String> items = lineSplitter.splitToList(line);
        if (items.size() != 2) {
            continue;
        }
        result.put(items.get(0), items.get(1));
    }
    return ImmutableMap.copyOf(result);
}
Also used : Splitter(com.google.common.base.Splitter) HashMap(java.util.HashMap)

Example 39 with Splitter

use of com.google.common.base.Splitter in project buck by facebook.

the class ProjectWorkspace method buildMultipleAndReturnOutputs.

public Map<String, Path> buildMultipleAndReturnOutputs(String... args) throws IOException {
    // Add in `--show-output` to the build, so we can parse the output paths after the fact.
    ImmutableList<String> buildArgs = ImmutableList.<String>builder().add("--show-output").add(args).build();
    ProjectWorkspace.ProcessResult buildResult = runBuckBuild(buildArgs.toArray(new String[buildArgs.size()]));
    buildResult.assertSuccess();
    // Grab the stdout lines, which have the build outputs.
    List<String> lines = Splitter.on(CharMatcher.anyOf(System.lineSeparator())).trimResults().omitEmptyStrings().splitToList(buildResult.getStdout());
    // Skip the first line, which is just "The outputs are:".
    assertThat(lines.get(0), Matchers.equalTo("The outputs are:"));
    lines = lines.subList(1, lines.size());
    Splitter lineSplitter = Splitter.on(' ').trimResults();
    ImmutableMap.Builder<String, Path> builder = ImmutableMap.builder();
    for (String line : lines) {
        List<String> fields = lineSplitter.splitToList(line);
        assertThat(fields, Matchers.hasSize(2));
        builder.put(fields.get(0), getPath(fields.get(1)));
    }
    return builder.build();
}
Also used : Path(java.nio.file.Path) Splitter(com.google.common.base.Splitter) ImmutableMap(com.google.common.collect.ImmutableMap)

Example 40 with Splitter

use of com.google.common.base.Splitter in project buck by facebook.

the class XmlAttribute method handleBothToolsAttributePresent.

/**
     * Handles tools: namespace attributes presence in both documents.
     * @param higherPriority the higherPriority attribute
     */
private void handleBothToolsAttributePresent(@NonNull XmlAttribute higherPriority) {
    // do not merge tools:node attributes, the higher priority one wins.
    if (getName().getLocalName().equals(NodeOperationType.NODE_LOCAL_NAME)) {
        return;
    }
    // everything else should be merged, duplicates should be eliminated.
    @NonNull Splitter splitter = Splitter.on(',');
    @NonNull ImmutableSet.Builder<String> targetValues = ImmutableSet.builder();
    targetValues.addAll(splitter.split(higherPriority.getValue()));
    targetValues.addAll(splitter.split(getValue()));
    higherPriority.getXml().setValue(Joiner.on(',').join(targetValues.build()));
}
Also used : Splitter(com.google.common.base.Splitter) ImmutableSet(com.google.common.collect.ImmutableSet) NonNull(com.android.annotations.NonNull)

Aggregations

Splitter (com.google.common.base.Splitter)86 ArrayList (java.util.ArrayList)19 IOException (java.io.IOException)11 HashSet (java.util.HashSet)10 File (java.io.File)7 HashMap (java.util.HashMap)7 Test (org.junit.Test)5 BufferedReader (java.io.BufferedReader)4 NonNull (com.android.annotations.NonNull)3 URI (java.net.URI)3 URL (java.net.URL)3 ItemStack (net.minecraft.item.ItemStack)3 StringColumn (tech.tablesaw.api.StringColumn)3 CharMatcher (com.google.common.base.CharMatcher)2 ImmutableList (com.google.common.collect.ImmutableList)2 ImmutableMap (com.google.common.collect.ImmutableMap)2 CharSource (com.google.common.io.CharSource)2 BufferedOutputStream (java.io.BufferedOutputStream)2 FileInputStream (java.io.FileInputStream)2 InputStreamReader (java.io.InputStreamReader)2