Java Code Examples for com.gianlu.commonutils.CommonUtils

The following examples show how to use com.gianlu.commonutils.CommonUtils. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: CommonUtils   Source File: LogsHelper.java    License: Apache License 2.0 6 votes vote down vote up
public static boolean exportLogFiles(@NonNull Context context, @NonNull Intent intent) {
    try {
        File parent = new File(context.getCacheDir(), "logs");
        if (!parent.exists() && !parent.mkdir())
            return false;

        Process process = Runtime.getRuntime().exec("logcat -d");
        File file = new File(parent, "logs-" + System.currentTimeMillis() + ".txt");
        try (FileOutputStream out = new FileOutputStream(file, false)) {
            CommonUtils.copy(process.getInputStream(), out);
        } finally {
            process.destroy();
        }

        Uri uri = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".logs", file);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.putExtra(Intent.EXTRA_STREAM, uri);
        return true;
    } catch (IllegalArgumentException | IOException ex) {
        Log.e(TAG, "Failed exporting logs.", ex);
    }

    return false;
}
 
Example 2
Source Project: Aria2App   Source File: CustomDownloadInfo.java    License: GNU General Public License v3.0 6 votes vote down vote up
public void update(DownloadWithUpdate.SmallUpdate download) {
    if (info.length == 0) return;

    for (int i = 0; i < this.info.length; i++) {
        switch (info[i]) {
            case DOWNLOAD_SPEED:
                setChildText(i, CommonUtils.speedFormatter(download.downloadSpeed, false));
                break;
            case UPLOAD_SPEED:
                setChildText(i, CommonUtils.speedFormatter(download.uploadSpeed, false));
                break;
            case REMAINING_TIME:
                setChildText(i, CommonUtils.timeFormatter(download.getMissingTime()));
                break;
            case COMPLETED_LENGTH:
                setChildText(i, CommonUtils.dimensionFormatter(download.completedLength, false));
                break;
            case CONNECTIONS:
                setChildText(i, String.valueOf(download.connections));
                break;
            case SEEDERS:
                setChildText(i, String.valueOf(download.numSeeders));
                break;
        }
    }
}
 
Example 3
Source Project: Aria2App   Source File: Download.java    License: GNU General Public License v3.0 6 votes vote down vote up
@WorkerThread
@NonNull
private static ChangeSelectionResult performSelectIndexesOperation(AbstractClient client, String gid, Integer[] currIndexes, Integer[] selIndexes, boolean select) throws Exception {
    Collection<Integer> newIndexes = new HashSet<>(Arrays.asList(currIndexes));
    if (select) {
        newIndexes.addAll(Arrays.asList(selIndexes)); // Does not allow duplicates
    } else {
        newIndexes.removeAll(Arrays.asList(selIndexes));
        if (newIndexes.isEmpty()) return ChangeSelectionResult.EMPTY;
    }

    OptionsMap map = new OptionsMap();
    map.put("select-file", CommonUtils.join(newIndexes, ","));
    client.sendSync(AriaRequests.changeDownloadOptions(gid, map));
    if (select) return ChangeSelectionResult.SELECTED;
    else return ChangeSelectionResult.DESELECTED;
}
 
Example 4
Source Project: Aria2App   Source File: DownloadWithUpdate.java    License: GNU General Public License v3.0 6 votes vote down vote up
BigUpdate(JSONObject obj) throws JSONException {
    super(obj);

    // Optional
    bitfield = CommonUtils.optString(obj, "bitfield");
    verifiedLength = obj.optLong("verifiedLength", 0);
    verifyIntegrityPending = obj.optBoolean("verifyIntegrityPending", false);

    if (isTorrent()) {
        infoHash = obj.getString("infoHash");
        seeder = obj.optBoolean("seeder", false);
    } else {
        seeder = false;
        infoHash = null;
    }
}
 
Example 5
Source Project: Aria2App   Source File: DirectorySheet.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
protected boolean onCustomizeAction(@NonNull FloatingActionButton action, @NonNull final SetupPayload payload) {
    try {
        final MultiProfile profile = ProfilesManager.get(requireContext()).getCurrent();
        if (payload.download.update().isMetadata() || profile.getProfile(getContext()).directDownload == null) {
            return false;
        } else {
            action.setImageResource(R.drawable.baseline_download_24);
            CommonUtils.setBackgroundColor(action, payload.download.update().getColorVariant());
            action.setSupportImageTintList(ColorStateList.valueOf(Color.WHITE));
            action.setOnClickListener(v -> payload.listener.onDownloadDirectory(profile, currentDir));
            return true;
        }
    } catch (ProfilesManager.NoCurrentProfileException ex) {
        Log.e(TAG, "No profile found.", ex);
        return false;
    }
}
 
Example 6
public PyxCardsGroupView(Context context, CardListener listener) {
    super(context);
    this.listener = listener;
    setOrientation(HORIZONTAL);
    setWillNotDraw(false);

    mPaddingSmall = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8, getResources().getDisplayMetrics());
    mCornerRadius = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, getResources().getDisplayMetrics());
    mLineWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1.6f, getResources().getDisplayMetrics());

    mLinePaint = new Paint();
    mLinePaint.setColor(CommonUtils.resolveAttrAsColor(context, android.R.attr.textColorSecondary));
    mLinePaint.setStrokeWidth(mLineWidth);
    mLinePaint.setStyle(Paint.Style.STROKE);
    mLinePaint.setPathEffect(new DashPathEffect(new float[]{20, 10}, 0));
}
 
Example 7
Source Project: Aria2App   Source File: NotificationService.java    License: GNU General Public License v3.0 6 votes vote down vote up
@NonNull
private String describeServiceStatus() {
    switch (startedFrom) {
        case GLOBAL:
            List<String> notNotify = getByMode(Mode.NOT_NOTIFY_EXCLUSIVE);
            if (notNotify.isEmpty())
                return CommonUtils.join(profiles, ", ", true);
            else
                return CommonUtils.join(profiles, ", ", true) + " except " + CommonUtils.join(notNotify, ", ", true);
        case DOWNLOAD:
            List<String> notify = getByMode(Mode.NOTIFY_EXCLUSIVE);
            if (notify.isEmpty())
                return "Should stop, not notifying anything."; // Should never appear on notification
            else
                return CommonUtils.join(profiles, ", ", true) + " for " + CommonUtils.join(notify, ", ", true);
        default:
        case NOT:
            return "Not started"; // Should never appear on notification
    }
}
 
Example 8
Source Project: CommonUtils   Source File: MenuItemsAdapter.java    License: Apache License 2.0 5 votes vote down vote up
MenuItemsAdapter(@NonNull Context context, List<BaseDrawerItem<E>> items, Listener<E> listener) {
    this.inflater = LayoutInflater.from(context);
    this.items = items;
    this.listener = listener;
    this.colorTextPrimary = CommonUtils.resolveAttrAsColor(context, android.R.attr.textColorPrimary);
    this.colorAccent = ContextCompat.getColor(context, R.color.colorSecondary);
}
 
Example 9
Source Project: PretendYoureXyzzyAndroid   Source File: Pyx.java    License: GNU General Public License v3.0 5 votes vote down vote up
static void parseAndSave(@NonNull JSONArray array) throws JSONException {
    List<Server> servers = new ArrayList<>(array.length());
    for (int i = 0; i < array.length(); i++) {
        JSONObject obj = array.getJSONObject(i);
        String name = CommonUtils.getStupidString(obj, "name");

        HttpUrl url = new HttpUrl.Builder()
                .host(obj.getString("host"))
                .scheme(obj.getBoolean("secure") ? "https" : "http")
                .port(obj.getInt("port"))
                .encodedPath(obj.getString("path"))
                .build();

        String metrics = CommonUtils.getStupidString(obj, "metrics");
        servers.add(new Server(url, metrics == null ? null : HttpUrl.parse(metrics),
                name == null ? (url.host() + " server") : name,
                obj.has("params") ? new Params(obj.getJSONObject("params")) : Params.defaultValues(),
                false));
    }

    JSONArray json = new JSONArray();
    for (Server server : servers)
        json.put(server.toJson());

    JsonStoring.intoPrefs().putJsonArray(PK.API_SERVERS, json);
    Prefs.putLong(PK.API_SERVERS_CACHE_AGE, System.currentTimeMillis());
}
 
Example 10
private PollMessage(JSONObject obj) throws JSONException {
    event = Event.parse(obj.getString("E"));
    sender = CommonUtils.optString(obj, "f");
    message = CommonUtils.optString(obj, "m");
    gid = obj.optInt("gid", -1);
    timestamp = obj.optLong("ts", -1);
    emote = obj.optBoolean("me", false);
    wall = obj.optBoolean("wall", false);

    this.obj = obj;
}
 
Example 11
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
    final SessionHistory.Game game = games.get(position);
    ((SuperTextView) holder.itemView).setHtml(R.string.gameStartedAt, CommonUtils.getFullVerbalDateFormatter().format(new Date(game.timestamp)));
    holder.itemView.setOnClickListener(v -> {
        if (listener != null) listener.onGameSelected(game);
    });
}
 
Example 12
private void loadGame(@NonNull final SessionHistory.Game game) {
    breadcrumbs.addItem(new BreadcrumbsView.Item(CommonUtils.getFullDateFormatter().format(new Date(game.timestamp)), TYPE_GAME, game));

    getSupportFragmentManager()
            .beginTransaction()
            .replace(R.id.metrics_container, GameHistoryFragment.get(game.id), TAG_GAME)
            .commit();
}
 
Example 13
@Override
public boolean canShow(@NonNull BaseTutorial tutorial) {
    if (getActivity() == null || !CommonUtils.isVisible(this)) return false;

    if (tutorial instanceof CreateGameTutorial) {
        return manager != null && manager.amHost();
    } else if (tutorial instanceof HowToPlayTutorial) {
        return manager != null && manager.isPlayerStatus(GameInfo.PlayerStatus.PLAYING);
    } else {
        return false;
    }
}
 
Example 14
private void done() {
    scoreLimit.setErrorEnabled(false);
    playerLimit.setErrorEnabled(false);
    spectatorLimit.setErrorEnabled(false);
    timerMultiplier.setErrorEnabled(false);
    blankCards.setErrorEnabled(false);
    password.setErrorEnabled(false);

    Game.Options newOptions;
    try {
        newOptions = Game.Options.validateAndCreate(pyx.config(), pyx.server.params(), CommonUtils.getText(timerMultiplier).trim(), CommonUtils.getText(spectatorLimit),
                CommonUtils.getText(playerLimit), CommonUtils.getText(scoreLimit), CommonUtils.getText(blankCards),
                decks, CommonUtils.getText(password));
    } catch (Game.Options.InvalidFieldException ex) {
        View view = layout.findViewById(ex.fieldId);
        if (view instanceof TextInputLayout) {
            if (ex.throwMessage == R.string.outOfRange)
                ((TextInputLayout) view).setError(getString(R.string.outOfRange, ex.min, ex.max));
            else
                ((TextInputLayout) view).setError(getString(ex.throwMessage));
        }

        return;
    }

    dismissAllowingStateLoss();
    if (listener != null) listener.changeGameOptions(gid, newOptions);
}
 
Example 15
Source Project: CommonUtils   Source File: Toaster.java    License: Apache License 2.0 5 votes vote down vote up
public void show(@NonNull Context context) {
    if (shown) {
        if (CommonUtils.isDebug()) System.out.println("Skipping toast, already shown!");
        return;
    }

    if (!DialogUtils.isContextValid(context)) {
        if (CommonUtils.isDebug())
            System.out.println("Skipping toast, context is invalid: " + context);
        return;
    }

    if (msg == null) {
        if (msgRes != 0) {
            msg = context.getString(msgRes, args);
            msgRes = 0;
            args = null;
        } else {
            throw new IllegalArgumentException("Missing toast message!");
        }
    }

    final int duration;
    if (msg.length() > 48) duration = Toast.LENGTH_LONG;
    else duration = Toast.LENGTH_SHORT;

    Runnable action = () -> {
        if (DialogUtils.isContextValid(context))
            Toast.makeText(context, msg, duration).show();
    };

    if (Looper.myLooper() == Looper.getMainLooper()) action.run();
    else handler.post(action);

    Log.v(TAG, buildLogMessage(context));
    shown = true;
}
 
Example 16
@NonNull
@SuppressLint("InflateParams")
public static MaterialAlertDialogBuilder gameOptions(@NonNull Context context, @NonNull Game.Options options, @NonNull FirstLoad firstLoad) {
    ScrollView layout = (ScrollView) LayoutInflater.from(context).inflate(R.layout.dialog_game_options, null, false);

    SuperTextView scoreLimit = layout.findViewById(R.id.gameOptions_scoreLimit);
    scoreLimit.setHtml(R.string.scoreLimit, options.scoreLimit);

    SuperTextView playerLimit = layout.findViewById(R.id.gameOptions_playerLimit);
    playerLimit.setHtml(R.string.playerLimit, options.playersLimit);

    SuperTextView spectatorLimit = layout.findViewById(R.id.gameOptions_spectatorLimit);
    spectatorLimit.setHtml(R.string.spectatorLimit, options.spectatorsLimit);

    SuperTextView timerMultiplier = layout.findViewById(R.id.gameOptions_timerMultiplier);
    timerMultiplier.setHtml(R.string.timerMultiplier, options.timerMultiplier);

    SuperTextView cardSets = layout.findViewById(R.id.gameOptions_cardSets);
    cardSets.setHtml(R.string.cardSets, options.cardSets.isEmpty() ? "<i>none</i>" : CommonUtils.join(firstLoad.createCardSetNamesList(options.cardSets), ", "));

    SuperTextView blankCards = layout.findViewById(R.id.gameOptions_blankCards);
    blankCards.setHtml(R.string.blankCards, options.blanksLimit);

    SuperTextView password = layout.findViewById(R.id.gameOptions_password);
    if (options.password == null || options.password.isEmpty())
        password.setVisibility(View.GONE);
    else
        password.setHtml(R.string.password, options.password);

    MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(context);
    builder.setTitle(R.string.gameOptions)
            .setView(layout)
            .setPositiveButton(android.R.string.ok, null);

    return builder;
}
 
Example 17
Source Project: DNSHero   Source File: Domain.java    License: GNU General Public License v3.0 5 votes vote down vote up
private NS(JSONObject obj) throws JSONException {
    source = obj.getString("source");
    nameservers = CommonUtils.toStringsList(obj.getJSONArray("name-servers"), true);
    glue = new Glue(obj.getJSONObject("glue"));
    rtt = Utils.parseMs(obj.getString("rtt"));
    a = new DNSRecord<>(obj.getJSONObject("a"), DNSRecord.AEntry.class);
    aaaa = new DNSRecord<>(obj.getJSONObject("aaaa"), DNSRecord.AEntry.class);
}
 
Example 18
Source Project: DNSHero   Source File: Domain.java    License: GNU General Public License v3.0 5 votes vote down vote up
Glue(JSONObject obj) throws JSONException {
    if (CommonUtils.isStupidNull(obj, "v4")) v4 = null;
    else v4 = Entry.list(obj.getJSONArray("v4"));

    if (CommonUtils.isStupidNull(obj, "v6")) v6 = null;
    else v6 = Entry.list(obj.getJSONArray("v6"));
}
 
Example 19
Source Project: DNSHero   Source File: Domain.java    License: GNU General Public License v3.0 5 votes vote down vote up
private Diagnostic(JSONObject obj) throws JSONException {
    JSONObject definition = obj.getJSONObject("definition");
    name = definition.getString("name");
    description = definition.getString("description");
    status = DiagnosticStatus.parse(obj.getString("status"));
    recommendation = CommonUtils.optString(obj, "recommendation");

    JSONObject sourcesObj = obj.getJSONObject("sources");
    sources = new HashMap<>();
    Iterator<String> keys = sourcesObj.keys();
    while (keys.hasNext()) {
        String key = keys.next();
        sources.put(key, sourcesObj.getBoolean(key));
    }
}
 
Example 20
Source Project: DNSHero   Source File: DiagnosticsAdapter.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {
    Domain.Diagnostic diagnostic = diagnostics.get(position);


    switch (diagnostic.status) {
        case PASSED:
            CommonUtils.setTextColor(holder.title, R.color.passed);
            break;
        case FAILED:
            CommonUtils.setTextColor(holder.title, R.color.failed);
            holder.recommendationImage.setImageResource(R.drawable.baseline_error_outline_24);
            break;
        default:
        case SKIPPED:
            CommonUtils.setTextColorFromAttr(holder.title, R.attr.colorOnSurface);
            holder.recommendationImage.setImageResource(R.drawable.outline_info_24);
            break;
        case INFO:
            CommonUtils.setTextColor(holder.title, R.color.info);
            holder.recommendationImage.setImageResource(R.drawable.outline_info_24);
            break;
    }

    holder.title.setText(diagnostic.name);
    holder.description.setText(diagnostic.description);
    holder.recommendationText.setText(diagnostic.recommendation);

    holder.toggle.setVisibility(diagnostic.recommendation != null ? View.VISIBLE : View.GONE);
    holder.toggle.setOnClickListener(v -> CommonUtils.handleCollapseClick(holder.toggle, holder.recommendation));

    CommonUtils.setRecyclerViewTopMargin(holder);
}
 
Example 21
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    ScrollView layout = (ScrollView) inflater.inflate(R.layout.fragment_root_nameserver, container, false);

    Bundle args = getArguments();
    Domain.RootNameserver root;
    if (getContext() == null || args == null || (root = (Domain.RootNameserver) args.getSerializable("root")) == null)
        return null;

    SuperTextView name = layout.findViewById(R.id.rootNsFragment_name);
    Utils.clickToCopy(name);
    name.setText(root.name);

    SuperTextView rtt = layout.findViewById(R.id.rootNsFragment_rtt);
    rtt.setHtml(R.string.rtt, Utils.formatRTT(root.rtt));

    final LinearLayout nameservers = layout.findViewById(R.id.rootNsFragment_nameservers);
    for (String nameserver : root.nameservers) {
        TextView text = (TextView) inflater.inflate(R.layout.item_secondary_text, nameservers, false);
        text.setText(nameserver);
        Utils.clickToCopy(text);

        nameservers.addView(text);
    }

    final ImageButton toggleNs = layout.findViewById(R.id.rootNsFragment_toggleNs);
    toggleNs.setOnClickListener(v -> CommonUtils.handleCollapseClick(toggleNs, nameservers));

    GlueView glue = layout.findViewById(R.id.rootNsFragment_glue);
    glue.setGlue(root.glue);

    return layout;
}
 
Example 22
Source Project: Aria2App   Source File: AboutAria2Dialog.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onResult(@NonNull VersionAndSession result) {
    loading.setVisibility(View.GONE);
    version.setHtml(R.string.versionLabel, result.version.version);
    features.setHtml(R.string.features, CommonUtils.join(result.version.enabledFeatures, ", "));
    sessionId.setHtml(R.string.sessionId, result.session.sessionId);
}
 
Example 23
Source Project: Aria2App   Source File: MainActivity.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void showFilteringDialog() {
    final Download.Status[] filters = new Download.Status[]{Download.Status.ACTIVE, Download.Status.PAUSED, Download.Status.WAITING, Download.Status.ERROR, Download.Status.REMOVED, Download.Status.COMPLETE};
    CharSequence[] stringFilters = new CharSequence[filters.length];

    for (int i = 0; i < filters.length; i++)
        stringFilters[i] = filters[i].getFormal(this, true);

    final boolean[] checkedFilters = new boolean[filters.length];
    Set<String> checkedFiltersSet = Prefs.getSet(PK.A2_MAIN_FILTERS);

    for (String checkedFilter : checkedFiltersSet) {
        Download.Status filter = Download.Status.valueOf(checkedFilter);
        int pos = CommonUtils.indexOf(filters, filter);
        if (pos != -1) checkedFilters[pos] = true;
    }

    AlertDialog.Builder builder = new MaterialAlertDialogBuilder(this);
    builder.setTitle(R.string.filters)
            .setMultiChoiceItems(stringFilters, checkedFilters, (dialog, which, isChecked) -> checkedFilters[which] = isChecked)
            .setPositiveButton(R.string.apply, (dialog, which) -> {
                List<Download.Status> toApplyFilters = new ArrayList<>();
                for (int i = 0; i < checkedFilters.length; i++)
                    if (!checkedFilters[i]) toApplyFilters.add(filters[i]);

                if (adapter != null) adapter.setFilters(toApplyFilters);
                Set<String> set = new HashSet<>();
                for (int i = 0; i < checkedFilters.length; i++)
                    if (checkedFilters[i]) set.add(filters[i].name());

                Prefs.putSet(PK.A2_MAIN_FILTERS, set);

                updateFiltersVerbose();
            })
            .setNegativeButton(android.R.string.cancel, null);

    showDialog(builder);
}
 
Example 24
Source Project: Aria2App   Source File: MainActivity.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void updateFiltersVerbose() {
    Set<String> filters = Prefs.getSet(PK.A2_MAIN_FILTERS);
    if (filters.size() == Download.Status.values().length) {
        filtersVerbose.setVisibility(View.GONE);
    } else {
        filtersVerbose.setVisibility(View.VISIBLE);
        filtersVerbose.setText(getString(R.string.filtersShowingOnly, CommonUtils.join(filters, ", ",
                obj -> Download.Status.valueOf(obj).getFormal(MainActivity.this, true)),
                adapter == null ? 0 : adapter.getItemCount()));
    }
}
 
Example 25
Source Project: Aria2App   Source File: TrackersListFetch.java    License: GNU General Public License v3.0 5 votes vote down vote up
public void getTrackers(@NonNull Type type, @Nullable Activity activity, @NonNull Listener listener) {
    if (Prefs.has(PK.TRACKERS_LIST_CACHE) && !CommonUtils.isDebug()) {
        long age = Prefs.getLong(PK.TRACKERS_LIST_CACHE_AGE, 0);
        if (System.currentTimeMillis() - age < TimeUnit.DAYS.toMillis(1)) {
            Set<String> set = Prefs.getSet(PK.TRACKERS_LIST_CACHE, null);
            if (set != null && set.size() > 0)
                listener.onDone(new ArrayList<>(set));
        }
    }

    executorService.execute(new LifecycleAwareRunnable(handler, activity == null ? listener : activity) {
        @Override
        public void run() {
            try {
                Response resp = client.newCall(new Request.Builder().get().url(String.format(BASE_URL, type.getId())).build()).execute();
                if (resp.code() != 200)
                    throw new IOException(resp.code() + ": " + resp.message());

                ResponseBody body = resp.body();
                if (body == null)
                    throw new IOException("Body is empty!");

                List<String> trackers = new ArrayList<>();
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(body.byteStream()))) {
                    String line;
                    while ((line = reader.readLine()) != null && !line.isEmpty())
                        trackers.add(line);
                }

                Prefs.putLong(PK.TRACKERS_LIST_CACHE_AGE, System.currentTimeMillis());
                Prefs.putSet(PK.TRACKERS_LIST_CACHE, new HashSet<>(trackers));

                post(() -> listener.onDone(trackers));
            } catch (IOException ex) {
                post(() -> listener.onFailed(ex));
            }
        }
    });
}
 
Example 26
Source Project: Aria2App   Source File: AriaRequests.java    License: GNU General Public License v3.0 5 votes vote down vote up
@NonNull
public static AbstractClient.AriaRequestWithResult<String> addUri(@NonNull Collection<String> uris, @Nullable Integer pos, @Nullable OptionsMap options) throws JSONException {
    Object[] params = new Object[3];
    params[0] = CommonUtils.toJSONArray(uris, true);
    if (options != null) params[1] = options.toJson();
    else params[1] = new JSONObject();
    if (pos != null) params[2] = pos;
    else params[2] = Integer.MAX_VALUE;
    return new AbstractClient.AriaRequestWithResult<>(AbstractClient.Method.ADD_URI, STRING_PROCESSOR, params);
}
 
Example 27
Source Project: Aria2App   Source File: AriaRequests.java    License: GNU General Public License v3.0 5 votes vote down vote up
@NonNull
public static AbstractClient.AriaRequestWithResult<String> addTorrent(@NonNull String base64, @Nullable Collection<String> uris, @Nullable Integer pos, @Nullable OptionsMap options) throws JSONException {
    Object[] params = new Object[4];
    params[0] = base64;
    if (uris != null) params[1] = CommonUtils.toJSONArray(uris, true);
    else params[1] = new JSONArray();
    if (options != null) params[2] = options.toJson();
    else params[2] = new JSONObject();
    if (pos != null) params[3] = pos;
    else params[3] = Integer.MAX_VALUE;
    return new AbstractClient.AriaRequestWithResult<>(AbstractClient.Method.ADD_TORRENT, STRING_PROCESSOR, params);
}
 
Example 28
Source Project: Aria2App   Source File: AriaRequests.java    License: GNU General Public License v3.0 5 votes vote down vote up
@NonNull
public static AbstractClient.AriaRequestWithResult<List<String>> listMethods() {
    return new AbstractClient.AriaRequestWithResult<>(AbstractClient.Method.LIST_METHODS, new AbstractClient.Processor<List<String>>() {
        @NonNull
        @Override
        public List<String> process(@NonNull ClientInterface client, @NonNull JSONObject obj) throws JSONException {
            return CommonUtils.toStringsList(obj.getJSONArray("result"), false);
        }
    });
}
 
Example 29
Source Project: Aria2App   Source File: PreferenceActivity.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void doExport() {
    try {
        JSONArray json = ProfilesManager.get(requireContext()).exportAllProfiles();

        File file = new File(requireContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "aria2app-profiles-" + CommonUtils.randomString(5) + ".json");
        try (FileOutputStream out = new FileOutputStream(file)) {
            out.write(json.toString().getBytes());
        }

        showToast(Toaster.build().message(R.string.profilesExportedSuccessfully, file.getAbsolutePath()));
    } catch (JSONException | IOException ex) {
        Log.e(TAG, "Failed exporting profiles.", ex);
        showToast(Toaster.build().message(R.string.failedExportingProfiles));
    }
}
 
Example 30
Source Project: Aria2App   Source File: Torrent.java    License: GNU General Public License v3.0 5 votes vote down vote up
public Torrent(JSONObject obj) throws JSONException {
    engineId = obj.getString("engine");
    title = obj.getString("title");
    magnet = obj.getString("magnet");
    torrentFileUrl = CommonUtils.optString(obj, "torrent");
    size = obj.getLong("size");
    seeders = obj.getInt("seeders");
    leeches = obj.getInt("leeches");
}