repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/testCommon/src/testFixtures/java/com/virtuslab/gitmachete/testcommon/TestFileUtils.java
testCommon/src/testFixtures/java/com/virtuslab/gitmachete/testcommon/TestFileUtils.java
package com.virtuslab.gitmachete.testcommon; import static com.virtuslab.gitmachete.testcommon.TestProcessUtils.runProcessAndReturnStdout; import java.io.File; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.util.Comparator; import lombok.SneakyThrows; import lombok.val; import org.apache.commons.io.IOUtils; public final class TestFileUtils { private TestFileUtils() {} @SneakyThrows public static void copyScriptFromResources(String scriptName, Path targetDir) { String scriptContents = IOUtils.resourceToString("/" + scriptName, StandardCharsets.UTF_8); Files.copy(IOUtils.toInputStream(scriptContents, StandardCharsets.UTF_8), targetDir.resolve(scriptName), StandardCopyOption.REPLACE_EXISTING); } public static void prepareRepoFromScript(String scriptName, Path workingDir) { runProcessAndReturnStdout(/* workingDirectory */ workingDir, /* timeoutSeconds */ 60, /* command */ "bash", workingDir.resolve(scriptName).toString()); } @SneakyThrows public static void cleanUpDir(Path dir) { try (val walkDirs = Files.walk(dir)) { walkDirs.sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete); } } @SneakyThrows public static void saveFile(Path directory, String fileName, String contents) { Files.write(directory.resolve(fileName), contents.getBytes(StandardCharsets.UTF_8)); } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/testCommon/src/testFixtures/java/com/virtuslab/gitmachete/testcommon/SetupScripts.java
testCommon/src/testFixtures/java/com/virtuslab/gitmachete/testcommon/SetupScripts.java
package com.virtuslab.gitmachete.testcommon; public final class SetupScripts { private SetupScripts() {} public static final String SETUP_FOR_NO_REMOTES = "setup-with-no-remotes.sh"; public static final String SETUP_WITH_SINGLE_REMOTE = "setup-with-single-remote.sh"; public static final String SETUP_README_SCENARIOS = "setup-readme-scenarios.sh"; public static final String SETUP_WITH_MULTIPLE_REMOTES = "setup-with-multiple-remotes.sh"; public static final String SETUP_FOR_DIVERGED_AND_OLDER_THAN = "setup-for-diverged-and-older-than.sh"; public static final String SETUP_FOR_YELLOW_EDGES = "setup-for-yellow-edges.sh"; public static final String SETUP_FOR_OVERRIDDEN_FORK_POINT = "setup-for-overridden-fork-point.sh"; public static final String SETUP_FOR_SQUASH_MERGE = "setup-for-squash-merge.sh"; public static final String[] ALL_SETUP_SCRIPTS = { SETUP_FOR_NO_REMOTES, SETUP_WITH_SINGLE_REMOTE, SETUP_WITH_MULTIPLE_REMOTES, SETUP_FOR_DIVERGED_AND_OLDER_THAN, SETUP_FOR_YELLOW_EDGES, SETUP_FOR_OVERRIDDEN_FORK_POINT, SETUP_FOR_SQUASH_MERGE }; }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/testCommon/src/testFixtures/java/com/virtuslab/gitmachete/testcommon/TestProcessUtils.java
testCommon/src/testFixtures/java/com/virtuslab/gitmachete/testcommon/TestProcessUtils.java
package com.virtuslab.gitmachete.testcommon; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.concurrent.TimeUnit; import lombok.SneakyThrows; import org.apache.commons.io.IOUtils; public final class TestProcessUtils { private TestProcessUtils() {} @SneakyThrows public static String runProcessAndReturnStdout(Path workingDirectory, int timeoutSeconds, String... command) { Process process = new ProcessBuilder() .command(command) .directory(workingDirectory.toFile()) .start(); boolean completed = process.waitFor(timeoutSeconds, TimeUnit.SECONDS); String stdout = IOUtils.toString(process.getInputStream(), StandardCharsets.UTF_8); String stderr = IOUtils.toString(process.getErrorStream(), StandardCharsets.UTF_8); String commandRepr = Arrays.toString(command); String NL = System.lineSeparator(); String stdoutMessage = "Stdout of " + commandRepr + ": " + NL + stdout; String stderrMessage = "Stderr of " + commandRepr + ": " + NL + stderr; String joinedMessage = NL + NL + stdoutMessage + NL + stderrMessage + NL; assertTrue( completed, "command " + commandRepr + " has not completed within " + timeoutSeconds + " seconds" + joinedMessage); int exitValue = process.exitValue(); assertEquals(0, exitValue, "command " + commandRepr + " has completed with exit code " + exitValue + joinedMessage); return stdout; } public static String runProcessAndReturnStdout(int timeoutSeconds, String... command) { Path currentDir = Paths.get(".").toAbsolutePath().normalize(); return runProcessAndReturnStdout(currentDir, timeoutSeconds, command); } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
VirtusLab/git-machete-intellij-plugin
https://github.com/VirtusLab/git-machete-intellij-plugin/blob/2b736d89bd073f82456de77481c7f6714716efca/testCommon/src/testFixtures/java/com/virtuslab/gitmachete/testcommon/TestGitRepository.java
testCommon/src/testFixtures/java/com/virtuslab/gitmachete/testcommon/TestGitRepository.java
package com.virtuslab.gitmachete.testcommon; import static com.virtuslab.gitmachete.testcommon.TestFileUtils.copyScriptFromResources; import static com.virtuslab.gitmachete.testcommon.TestFileUtils.prepareRepoFromScript; import java.nio.file.Files; import java.nio.file.Path; import lombok.SneakyThrows; public class TestGitRepository { public final Path parentDirectoryPath; public final Path rootDirectoryPath; public final Path mainGitDirectoryPath; public final Path worktreeGitDirectoryPath; @SneakyThrows public TestGitRepository(String scriptName) { parentDirectoryPath = Files.createTempDirectory("machete-tests-"); if (scriptName.equals("setup-with-single-remote.sh")) { rootDirectoryPath = parentDirectoryPath.resolve("machete-sandbox-worktree"); mainGitDirectoryPath = parentDirectoryPath.resolve("machete-sandbox").resolve(".git"); worktreeGitDirectoryPath = mainGitDirectoryPath.resolve("worktrees").resolve("machete-sandbox-worktree"); } else { rootDirectoryPath = parentDirectoryPath.resolve("machete-sandbox"); mainGitDirectoryPath = rootDirectoryPath.resolve(".git"); worktreeGitDirectoryPath = rootDirectoryPath.resolve(".git"); } copyScriptFromResources("common.sh", parentDirectoryPath); copyScriptFromResources(scriptName, parentDirectoryPath); prepareRepoFromScript(scriptName, parentDirectoryPath); System.out.println("Set up a test repo in " + rootDirectoryPath); } }
java
MIT
2b736d89bd073f82456de77481c7f6714716efca
2026-01-05T02:37:01.395349Z
false
TJHello/GoogleBilling
https://github.com/TJHello/GoogleBilling/blob/6aa1ac5c4fec48a95a722d8c90a1fc27cc4b8402/billing/src/test/java/com/tjbaobao/gitee/billing/ExampleUnitTest.java
billing/src/test/java/com/tjbaobao/gitee/billing/ExampleUnitTest.java
package com.tjbaobao.gitee.billing; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() { assertEquals(4, 2 + 2); } }
java
Apache-2.0
6aa1ac5c4fec48a95a722d8c90a1fc27cc4b8402
2026-01-05T02:37:59.273232Z
false
TJHello/GoogleBilling
https://github.com/TJHello/GoogleBilling/blob/6aa1ac5c4fec48a95a722d8c90a1fc27cc4b8402/billing/src/main/java/com/tjbaobao/gitee/billing/GoogleBillingUtil.java
billing/src/main/java/com/tjbaobao/gitee/billing/GoogleBillingUtil.java
package com.tjbaobao.gitee.billing; import android.app.Activity; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import com.android.billingclient.api.*; import java.util.*; /** * 作者:天镜baobao * 时间:2019/1/5 15:16 * 说明:允许对该封装进行改动,但请注明出处。 * 使用: * * Copyright 2019 天镜baobao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @SuppressWarnings({"WeakerAccess", "unused", "UnusedReturnValue"}) public class GoogleBillingUtil { private static final String TAG = "GoogleBillingUtil"; private static boolean IS_DEBUG = false; private static String[] inAppSKUS = new String[]{};//内购ID,必填,注意!如果用不着的请去掉多余的"" private static String[] subsSKUS = new String[]{};//订阅ID,必填,注意!如果用不着的请去掉多余的"" public static final String BILLING_TYPE_INAPP = BillingClient.SkuType.INAPP;//内购 public static final String BILLING_TYPE_SUBS = BillingClient.SkuType.SUBS;//订阅 private static BillingClient mBillingClient; private static BillingClient.Builder builder ; private static List<OnGoogleBillingListener> onGoogleBillingListenerList = new ArrayList<>(); private static Map<String,OnGoogleBillingListener> onGoogleBillingListenerMap = new HashMap<>(); private MyPurchasesUpdatedListener purchasesUpdatedListener = new MyPurchasesUpdatedListener(); private static boolean isAutoConsumeAsync = true;//是否在购买成功后自动消耗商品 private static final GoogleBillingUtil mGoogleBillingUtil = new GoogleBillingUtil() ; private GoogleBillingUtil() { } //region===================================初始化google应用内购买服务================================= /** * 设置skus * @param inAppSKUS 内购id * @param subsSKUS 订阅id */ public static void setSkus(@Nullable String[] inAppSKUS,@Nullable String[] subsSKUS){ if(inAppSKUS!=null){ GoogleBillingUtil.inAppSKUS = Arrays.copyOf(inAppSKUS,inAppSKUS.length); } if(subsSKUS!=null){ GoogleBillingUtil.subsSKUS = Arrays.copyOf(subsSKUS,subsSKUS.length); } } private static <T> void copyToArray(T[] base,T[] target){ System.arraycopy(base, 0, target, 0, base.length); } public static GoogleBillingUtil getInstance() { return mGoogleBillingUtil; } /** * 开始建立内购连接 * @param activity activity */ public GoogleBillingUtil build(Activity activity) { purchasesUpdatedListener.tag = getTag(activity); if(mBillingClient==null) { synchronized (mGoogleBillingUtil) { if(mBillingClient==null) { builder = BillingClient.newBuilder(activity); mBillingClient = builder.setListener(purchasesUpdatedListener).build(); } else { builder.setListener(purchasesUpdatedListener); } } } else { builder.setListener(purchasesUpdatedListener); } synchronized (mGoogleBillingUtil) { if(mGoogleBillingUtil.startConnection(activity)) { mGoogleBillingUtil.queryInventoryInApp(getTag(activity)); mGoogleBillingUtil.queryInventorySubs(getTag(activity)); mGoogleBillingUtil.queryPurchasesInApp(getTag(activity)); } } return mGoogleBillingUtil; } public boolean startConnection(Activity activity){ return startConnection(getTag(activity)); } private boolean startConnection(String tag) { if(mBillingClient==null) { log("初始化失败:mBillingClient==null"); return false; } if(!mBillingClient.isReady()) { mBillingClient.startConnection(new BillingClientStateListener() { @Override public void onBillingSetupFinished(@BillingClient.BillingResponse int billingResponseCode) { if (billingResponseCode == BillingClient.BillingResponse.OK) { queryInventoryInApp(tag); queryInventorySubs(tag); queryPurchasesInApp(tag); for(OnGoogleBillingListener listener:onGoogleBillingListenerList){ listener.onSetupSuccess(listener.tag.equals(tag)); } } else { log("初始化失败:onSetupFail:code="+billingResponseCode); for(OnGoogleBillingListener listener:onGoogleBillingListenerList){ listener.onFail(GoogleBillingListenerTag.SETUP,billingResponseCode, listener.tag.equals(tag)); } } } @Override public void onBillingServiceDisconnected() { for(OnGoogleBillingListener listener:onGoogleBillingListenerList){ listener.onBillingServiceDisconnected(); } log("初始化失败:onBillingServiceDisconnected"); } }); return false; } else { return true; } } //endregion //region===================================查询商品================================= /** * 查询内购商品信息 */ public void queryInventoryInApp(Activity activity) { queryInventoryInApp(getTag(activity)); } private void queryInventoryInApp(String tag) { queryInventory(tag,BillingClient.SkuType.INAPP); } /** * 查询订阅商品信息 */ public void queryInventorySubs(Activity activity) { queryInventory(getTag(activity),BillingClient.SkuType.SUBS); } private void queryInventorySubs(String tag) { queryInventory(tag,BillingClient.SkuType.SUBS); } private void queryInventory(String tag,final String skuType) { Runnable runnable = () -> { if (mBillingClient == null) { for(OnGoogleBillingListener listener:onGoogleBillingListenerList){ listener.onError(GoogleBillingListenerTag.QUERY, listener.tag.equals(tag)); } return ; } ArrayList<String> skuList = new ArrayList<>(); if(skuType.equals(BillingClient.SkuType.INAPP)) { Collections.addAll(skuList, inAppSKUS); } else if(skuType.equals(BillingClient.SkuType.SUBS)) { Collections.addAll(skuList, subsSKUS); } if(!skuList.isEmpty()){ SkuDetailsParams.Builder params = SkuDetailsParams.newBuilder(); params.setSkusList(skuList).setType(skuType); mBillingClient.querySkuDetailsAsync(params.build(),new MySkuDetailsResponseListener(skuType,tag)); } }; executeServiceRequest(tag,runnable); } //endregion //region===================================购买商品================================= /** * 发起内购 * @param skuId 内购商品id */ public void purchaseInApp(Activity activity, String skuId) { purchase(activity,skuId, BillingClient.SkuType.INAPP); } /** * 发起订阅 * @param skuId 订阅商品id */ public void purchaseSubs(Activity activity,String skuId) { purchase(activity,skuId, BillingClient.SkuType.SUBS); } private void purchase(Activity activity,final String skuId,final String skuType) { String tag = getTag(activity); if(mBillingClient==null) { for(OnGoogleBillingListener listener:onGoogleBillingListenerList){ listener.onError(GoogleBillingListenerTag.PURCHASE, listener.tag.equals(tag)); } return ; } if(startConnection(tag)) { purchasesUpdatedListener.tag = tag; builder.setListener(purchasesUpdatedListener); List<String> skuList = new ArrayList<>(); skuList.add(skuId); SkuDetailsParams skuDetailsParams = SkuDetailsParams.newBuilder() .setSkusList(skuList) .setType(skuType) .build(); mBillingClient.querySkuDetailsAsync(skuDetailsParams, (responseCode, skuDetailsList) -> { if(skuDetailsList!=null&&!skuDetailsList.isEmpty()){ BillingFlowParams flowParams = BillingFlowParams.newBuilder() .setSkuDetails(skuDetailsList.get(0)) .build(); mBillingClient.launchBillingFlow(activity,flowParams); } }); } else { for(OnGoogleBillingListener listener:onGoogleBillingListenerList){ listener.onError(GoogleBillingListenerTag.PURCHASE,listener.tag.equals(tag)); } } } //endregion //region===================================消耗商品================================= /** * 消耗商品 * @param purchaseToken {@link Purchase#getPurchaseToken()} */ public void consumeAsync(Activity activity,String purchaseToken) { consumeAsync(getTag(activity),purchaseToken); } /** * 消耗商品 * @param purchaseToken {@link Purchase#getPurchaseToken()} */ private void consumeAsync(String tag,String purchaseToken) { if(mBillingClient==null) { return ; } mBillingClient.consumeAsync(purchaseToken, new MyConsumeResponseListener(tag)); } /** * 消耗内购商品-通过sku数组 * @param sku sku */ public void consumeAsyncInApp(Activity activity,@NonNull String... sku) { if(mBillingClient==null) { return ; } List<String> skuList = Arrays.asList(sku); consumeAsyncInApp(activity,skuList); } /** * 消耗内购商品-通过sku数组 * @param skuList sku数组 */ public void consumeAsyncInApp(Activity activity,@NonNull List<String> skuList) { if(mBillingClient==null) { return ; } List<Purchase> purchaseList = queryPurchasesInApp(activity); if(purchaseList!=null){ for(Purchase purchase : purchaseList){ if(skuList.contains(purchase.getSku())){ mBillingClient.consumeAsync(purchase.getPurchaseToken(), new MyConsumeResponseListener(getTag(activity))); } } } } //endregion //region===================================本地订单查询================================= /** * 获取已经内购的商品 * @return 商品列表 */ public List<Purchase> queryPurchasesInApp(Activity activity) { return queryPurchases(getTag(activity),BillingClient.SkuType.INAPP); } private List<Purchase> queryPurchasesInApp(String tag) { return queryPurchases(tag,BillingClient.SkuType.INAPP); } /** * 获取已经订阅的商品 * @return 商品列表 */ public List<Purchase> queryPurchasesSubs(Activity activity) { return queryPurchases(getTag(activity),BillingClient.SkuType.SUBS); } private List<Purchase> queryPurchases(String tag,String skuType) { if(mBillingClient==null) { return null; } if(!mBillingClient.isReady()) { startConnection(tag); } else { Purchase.PurchasesResult purchasesResult = mBillingClient.queryPurchases(skuType); if(purchasesResult!=null) { if(purchasesResult.getResponseCode()== BillingClient.BillingResponse.OK) { List<Purchase> purchaseList = purchasesResult.getPurchasesList(); if(isAutoConsumeAsync) { if(purchaseList!=null) { for(Purchase purchase:purchaseList) { if(skuType.equals(BillingClient.SkuType.INAPP)) { consumeAsync(tag,purchase.getPurchaseToken()); } } } } return purchaseList; } } } return null; } //endregion //region===================================在线订单查询================================= /** * 异步联网查询所有的内购历史-无论是过期的、取消、等等的订单 * @param activity activity */ public void queryPurchaseHistoryAsyncInApp(Activity activity){ queryPurchaseHistoryAsync(getTag(activity),BILLING_TYPE_INAPP); } /** * 异步联网查询所有的订阅历史-无论是过期的、取消、等等的订单 * @param activity activity */ public void queryPurchaseHistoryAsyncSubs(Activity activity){ queryPurchaseHistoryAsync(getTag(activity),BILLING_TYPE_SUBS); } private void queryPurchaseHistoryAsync(String tag,String type){ if(isReady()) { mBillingClient.queryPurchaseHistoryAsync(type,new MyPurchaseHistoryResponseListener(tag)); } } //endregion //region===================================工具集合================================= /** * 获取有效订阅的数量 * @return -1查询失败,0没有有效订阅,>0具有有效的订阅 */ public int getPurchasesSizeSubs(Activity activity) { List<Purchase> list = queryPurchasesSubs(activity); if(list!=null) { return list.size(); } return -1; } /** * 通过sku获取订阅商品序号 * @param sku sku * @return 序号 */ public int getSubsPositionBySku(String sku) { return getPositionBySku(sku, BillingClient.SkuType.SUBS); } /** * 通过sku获取内购商品序号 * @param sku sku * @return 成功返回需要 失败返回-1 */ public int getInAppPositionBySku(String sku) { return getPositionBySku(sku, BillingClient.SkuType.INAPP); } private int getPositionBySku(String sku,String skuType) { if(skuType.equals(BillingClient.SkuType.INAPP)) { int i = 0; for(String s:inAppSKUS) { if(s.equals(sku)) { return i; } i++; } } else if(skuType.equals(BillingClient.SkuType.SUBS)) { int i = 0; for(String s:subsSKUS) { if(s.equals(sku)) { return i; } i++; } } return -1; } /** * 通过序号获取订阅sku * @param position 序号 * @return sku */ public String getSubsSkuByPosition(int position) { if(position>=0&&position<subsSKUS.length) { return subsSKUS[position]; } else { return null; } } /** * 通过序号获取内购sku * @param position 序号 * @return sku */ public String getInAppSkuByPosition(int position) { if(position>=0&&position<inAppSKUS.length) { return inAppSKUS[position]; } else { return null; } } /** * 通过sku获取商品类型(订阅获取内购) * @param sku sku * @return inapp内购,subs订阅 */ public String getSkuType(String sku) { if(Arrays.asList(inAppSKUS).contains(sku)) { return BillingClient.SkuType.INAPP; } else if(Arrays.asList(subsSKUS).contains(sku)) { return BillingClient.SkuType.SUBS; } return null; } private String getTag(Activity activity){ return activity.getLocalClassName(); } //endregion //region===================================其他方法================================= private void executeServiceRequest(String tag,final Runnable runnable) { if(startConnection(tag)) { runnable.run(); } } /** * google内购服务是否已经准备好 * @return boolean */ public static boolean isReady() { return mBillingClient!=null&&mBillingClient.isReady(); } /** * 设置是否自动消耗内购商品 * @param isAutoConsumeAsync 自动消耗内购商品 */ public static void setIsAutoConsumeAsync(boolean isAutoConsumeAsync) { GoogleBillingUtil.isAutoConsumeAsync= isAutoConsumeAsync; } /** * 断开连接google服务 * 注意!!!一般情况不建议调用该方法,让google保留连接是最好的选择。 */ public static void endConnection() { //注意!!!一般情况不建议调用该方法,让google保留连接是最好的选择。 if(mBillingClient!=null) { if(mBillingClient.isReady()) { mBillingClient.endConnection(); mBillingClient = null; } } } //endregion public GoogleBillingUtil addOnGoogleBillingListener(Activity activity,OnGoogleBillingListener onGoogleBillingListener){ String tag = getTag(activity); onGoogleBillingListener.tag = tag; onGoogleBillingListenerMap.put(getTag(activity),onGoogleBillingListener); for(int i=onGoogleBillingListenerList.size()-1;i>=0;i--){ OnGoogleBillingListener listener = onGoogleBillingListenerList.get(i); if(listener.tag.equals(tag)){ onGoogleBillingListenerList.remove(listener); } } onGoogleBillingListenerList.add(onGoogleBillingListener); return this; } public void removeOnGoogleBillingListener(OnGoogleBillingListener onGoogleBillingListener){ onGoogleBillingListenerList.remove(onGoogleBillingListener); } public void removeOnGoogleBillingListener(Activity activity){ String tag = getTag(activity); for(int i=onGoogleBillingListenerList.size()-1;i>=0;i--){ OnGoogleBillingListener listener = onGoogleBillingListenerList.get(i); if(listener.tag.equals(tag)){ removeOnGoogleBillingListener(listener); onGoogleBillingListenerMap.remove(tag); } } } /** * 清除内购监听器,防止内存泄漏-在Activity-onDestroy里面调用。 * 需要确保onDestroy和build方法在同一个线程。 */ public void onDestroy(Activity activity){ if(builder!=null) { builder.setListener(null); } removeOnGoogleBillingListener(activity); } /** * Google购买商品回调接口(订阅和内购都走这个接口) */ private class MyPurchasesUpdatedListener implements PurchasesUpdatedListener { public String tag ; @Override public void onPurchasesUpdated(int responseCode, @Nullable List<Purchase> list) { if(responseCode== BillingClient.BillingResponse.OK&&list!=null) { if(isAutoConsumeAsync) { //消耗商品 for(Purchase purchase:list) { String sku = purchase.getSku(); if(sku!=null) { String skuType = getSkuType(sku); if(skuType!=null) { if(skuType.equals(BillingClient.SkuType.INAPP)) { consumeAsync(tag,purchase.getPurchaseToken()); } } } } } for(OnGoogleBillingListener listener:onGoogleBillingListenerList){ int i = 0; for(Purchase purchase:list) { listener.onPurchaseSuccess(purchase,listener.tag.equals(tag),i,list.size()); i++; } } } else { if(IS_DEBUG){ log("购买失败,responseCode:"+responseCode); } for(OnGoogleBillingListener listener:onGoogleBillingListenerList){ listener.onFail(GoogleBillingListenerTag.PURCHASE,responseCode,listener.tag.equals(tag)); } } } } /** * Google查询商品信息回调接口 */ private class MySkuDetailsResponseListener implements SkuDetailsResponseListener { private String skuType ; private String tag; public MySkuDetailsResponseListener(String skuType,String tag) { this.skuType = skuType; this.tag = tag; } @Override public void onSkuDetailsResponse(int responseCode , List<SkuDetails> list) { if(responseCode== BillingClient.BillingResponse.OK&&list!=null) { for(OnGoogleBillingListener listener:onGoogleBillingListenerList){ listener.onQuerySuccess(skuType,list,listener.tag.equals(tag)); } } else { for(OnGoogleBillingListener listener:onGoogleBillingListenerList){ listener.onFail(GoogleBillingListenerTag.QUERY,responseCode,listener.tag.equals(tag)); } } } } /** * Googlg消耗商品回调 */ private class MyConsumeResponseListener implements ConsumeResponseListener { private String tag ; public MyConsumeResponseListener(String tag) { this.tag = tag; } @Override public void onConsumeResponse(int responseCode, String purchaseToken) { if (responseCode == BillingClient.BillingResponse.OK) { for(OnGoogleBillingListener listener:onGoogleBillingListenerList){ listener.onConsumeSuccess(purchaseToken,listener.tag.equals(tag)); } }else{ for(OnGoogleBillingListener listener:onGoogleBillingListenerList){ listener.onFail(GoogleBillingListenerTag.COMSUME,responseCode,listener.tag.equals(tag)); } } } } private class MyPurchaseHistoryResponseListener implements PurchaseHistoryResponseListener{ private String tag ; public MyPurchaseHistoryResponseListener(String tag) { this.tag = tag; } @Override public void onPurchaseHistoryResponse(int responseCode, List<Purchase> list) { if(responseCode== BillingClient.BillingResponse.OK&&list!=null){ for(OnGoogleBillingListener listener:onGoogleBillingListenerList){ for (Purchase purchase : list) { listener.onQueryHistory(purchase); } } }else{ for(OnGoogleBillingListener listener:onGoogleBillingListenerList){ listener.onFail(GoogleBillingListenerTag.HISTORY,responseCode,listener.tag.equals(tag)); } } } } public enum GoogleBillingListenerTag{ QUERY("query"), PURCHASE("purchase"), SETUP("setup"), COMSUME("comsume"), HISTORY("history") ; public String tag ; GoogleBillingListenerTag(String tag){ this.tag = tag; } } private static void log(String msg) { if(IS_DEBUG) { Log.e(TAG,msg); } } public static void isDebug(boolean isDebug){ GoogleBillingUtil.IS_DEBUG = isDebug; } }
java
Apache-2.0
6aa1ac5c4fec48a95a722d8c90a1fc27cc4b8402
2026-01-05T02:37:59.273232Z
false
TJHello/GoogleBilling
https://github.com/TJHello/GoogleBilling/blob/6aa1ac5c4fec48a95a722d8c90a1fc27cc4b8402/billing/src/main/java/com/tjbaobao/gitee/billing/PackInfo.java
billing/src/main/java/com/tjbaobao/gitee/billing/PackInfo.java
package com.tjbaobao.gitee.billing; /** * 作者:TJbaobao * 时间:2019/1/5 14:41 * 说明: * 使用: */ public class PackInfo { }
java
Apache-2.0
6aa1ac5c4fec48a95a722d8c90a1fc27cc4b8402
2026-01-05T02:37:59.273232Z
false
TJHello/GoogleBilling
https://github.com/TJHello/GoogleBilling/blob/6aa1ac5c4fec48a95a722d8c90a1fc27cc4b8402/billing/src/main/java/com/tjbaobao/gitee/billing/GoogleBillingUtilOld.java
billing/src/main/java/com/tjbaobao/gitee/billing/GoogleBillingUtilOld.java
package com.tjbaobao.gitee.billing; import android.app.Activity; import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import com.android.billingclient.api.*; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * Created by 天镜baobao on 2017/11/2. * CSDN:http://blog.csdn.net/u013640004/article/details/78257536 * 允许对该封装进行改动,但请注明出处。 * * 当前版本:V1.1.7 * 更新日志: * * v1.1.7 2019/01/05 * 开放消耗结果监听器设置-{@link #setOnConsumeResponseListener} * * v1.1.6 2018/09/05 * 去掉我项目了的BaseApplication.getContext()的方法,初始现在需要传入一个Context,可以使用Application的Context * 对isGooglePlayServicesAvailable方法进行了说明,因为这个方法是要导入一个包才能使用的。 * --> api "com.google.android.gms:play-services-location:11.8.0" * * v1.1.5 2018/07/13 * 优化-尽可能处理了一些可能造成的内存泄漏的问题。 * 修改-查询成功接口增加一个String skuType,参数,各位在查询的时候需要判断skuType * 增加-增加两处接口为Null的Log提示,tag为GoogleBillingUtil。 * * V1.1.4 2018/01/03 * 修改-实现单例模式,避免多实例导致的谷歌接口回调错乱问题。 * * V1.1.3 2017/12/19 * 修复-服务启动失败时导致的空指针错误。 * * V1.1.2 2017/12/18 * 修复-修复内购未被消耗的BUG。 * 增加-每次启动都获取一次历史内购订单,并且全部消耗。 * 增加-可以通过设置isAutoConsumeAsync来确定内购是否每次自动消耗。 * 增加-将consumeAsync改为public,你可以手动调用消耗。 * * V1.1.1 2017/11/2 * 升级-内购API版本为google最新版本。compile 'com.android.billingclient:billing:1.0' * 特性-不需要key了,不需要IInAppBillingService.aidl了,不需要那一大堆Utils了,创建新实例的时候必须要传入购买回调接口。 * * V1.0.3 2017/10/27 * 增加-支持内购 * * V1.0.2 2017/09/11 * 修复-修复BUG * * v1.0.1 2017/07/29 * 初始版本 * * * Copyright 2019 天镜baobao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @SuppressWarnings("ALL") public class GoogleBillingUtilOld { private static final String TAG = "GoogleBillingUtilOld"; private static final boolean IS_DEBUG = false; private static String[] inAppSKUS = new String[]{};//内购ID private static String[] subsSKUS = new String[]{};//订阅ID public static final String BILLING_TYPE_INAPP = BillingClient.SkuType.INAPP;//内购 public static final String BILLING_TYPE_SUBS = BillingClient.SkuType.SUBS;//订阅 private static BillingClient mBillingClient; private static BillingClient.Builder builder ; private static OnPurchaseFinishedListener mOnPurchaseFinishedListener; private static OnStartSetupFinishedListener mOnStartSetupFinishedListener ; private static OnQueryFinishedListener mOnQueryFinishedListener; private static OnConsumeResponseListener mOnConsumeResponseListener; private boolean isAutoConsumeAsync = true;//是否在购买成功后自动消耗商品 private static final GoogleBillingUtilOld mGoogleBillingUtil = new GoogleBillingUtilOld() ; private GoogleBillingUtilOld() { } /** * 设置skus * @param inAppSKUS 内购id * @param subsSKUS 订阅id */ public static void setSkus(@Nullable String[] inAppSKUS,@Nullable String[] subsSKUS){ if(inAppSKUS!=null){ GoogleBillingUtilOld.inAppSKUS = Arrays.copyOf(inAppSKUS,inAppSKUS.length); } if(subsSKUS!=null){ GoogleBillingUtilOld.subsSKUS = Arrays.copyOf(subsSKUS,subsSKUS.length); } } public static GoogleBillingUtilOld getInstance() { cleanListener(); return mGoogleBillingUtil; } public GoogleBillingUtilOld build(Context context) { if(mBillingClient==null) { synchronized (mGoogleBillingUtil) { if(mBillingClient==null) { builder = BillingClient.newBuilder(context); mBillingClient = builder.setListener(mGoogleBillingUtil.new MyPurchasesUpdatedListener()).build(); } else { builder.setListener(mGoogleBillingUtil.new MyPurchasesUpdatedListener()); } } } else { builder.setListener(mGoogleBillingUtil.new MyPurchasesUpdatedListener()); } synchronized (mGoogleBillingUtil) { if(mGoogleBillingUtil.startConnection()) { mGoogleBillingUtil.queryInventoryInApp(); mGoogleBillingUtil.queryInventorySubs(); mGoogleBillingUtil.queryPurchasesInApp(); } } return mGoogleBillingUtil; } public boolean startConnection() { if(mBillingClient==null) { log("初始化失败:mBillingClient==null"); return false; } if(!mBillingClient.isReady()) { mBillingClient.startConnection(new BillingClientStateListener() { @Override public void onBillingSetupFinished(@BillingClient.BillingResponse int billingResponseCode) { if (billingResponseCode == BillingClient.BillingResponse.OK) { queryInventoryInApp(); queryInventorySubs(); queryPurchasesInApp(); if(mOnStartSetupFinishedListener!=null) { mOnStartSetupFinishedListener.onSetupSuccess(); } } else { log("初始化失败:onSetupFail:code="+billingResponseCode); if(mOnStartSetupFinishedListener!=null) { mOnStartSetupFinishedListener.onSetupFail(billingResponseCode); } } } @Override public void onBillingServiceDisconnected() { if(mOnStartSetupFinishedListener!=null) { mOnStartSetupFinishedListener.onSetupError(); } log("初始化错误:onBillingServiceDisconnected"); } }); return false; } else { return true; } } /** * Google购买商品回调接口(订阅和内购都走这个接口) */ private class MyPurchasesUpdatedListener implements PurchasesUpdatedListener { @Override public void onPurchasesUpdated(int responseCode, @Nullable List<Purchase> list) { if(mOnPurchaseFinishedListener==null) { if(IS_DEBUG) { log("警告:接收到购买回调,但购买商品接口为Null,请设置购买接口。eg:setOnPurchaseFinishedListener()"); } return ; } if(responseCode== BillingClient.BillingResponse.OK&&list!=null) { if(isAutoConsumeAsync) { //消耗商品 for(Purchase purchase:list) { String sku = purchase.getSku(); if(sku!=null) { String skuType = getSkuType(sku); if(skuType!=null) { if(skuType.equals(BillingClient.SkuType.INAPP)) { consumeAsync(purchase.getPurchaseToken()); } } } } } mOnPurchaseFinishedListener.onPurchaseSuccess(list); } else { mOnPurchaseFinishedListener.onPurchaseFail(responseCode); } } } /** * 查询内购商品信息 */ public void queryInventoryInApp() { queryInventory(BillingClient.SkuType.INAPP); } /** * 查询订阅商品信息 */ public void queryInventorySubs() { queryInventory(BillingClient.SkuType.SUBS); } private void queryInventory(final String skuType) { Runnable runnable = new Runnable() { @Override public void run() { if (mBillingClient == null) { if(mOnQueryFinishedListener!=null) { mOnQueryFinishedListener.onQueryError(); } return ; } ArrayList<String> skuList = new ArrayList<>(); if(skuType.equals(BillingClient.SkuType.INAPP)) { Collections.addAll(skuList, inAppSKUS); } else if(skuType.equals(BillingClient.SkuType.SUBS)) { Collections.addAll(skuList, subsSKUS); } SkuDetailsParams.Builder params = SkuDetailsParams.newBuilder(); params.setSkusList(skuList).setType(skuType); mBillingClient.querySkuDetailsAsync(params.build(),new MySkuDetailsResponseListener(skuType)); } }; executeServiceRequest(runnable); } /** * Google查询商品信息回调接口 */ private class MySkuDetailsResponseListener implements SkuDetailsResponseListener { private String skuType ; public MySkuDetailsResponseListener(String skuType) { this.skuType = skuType; } @Override public void onSkuDetailsResponse(int responseCode , List<SkuDetails> list) { if(mOnQueryFinishedListener==null) { if(IS_DEBUG) { log("警告:接收到查询商品回调,但查询商品接口为Null,请设置购买接口。eg:setOnQueryFinishedListener()"); } return ; } if(responseCode== BillingClient.BillingResponse.OK&&list!=null) { mOnQueryFinishedListener.onQuerySuccess(skuType,list); } else { mOnQueryFinishedListener.onQueryFail(responseCode); } } } /** * 发起内购 * @param skuId */ public void purchaseInApp(Activity activity,String skuId) { purchase(activity,skuId, BillingClient.SkuType.INAPP); } /** * 发起订阅 * @param skuId */ public void purchaseSubs(Activity activity,String skuId) { purchase(activity,skuId, BillingClient.SkuType.SUBS); } private void purchase(Activity activity,final String skuId,final String skuType) { if(mBillingClient==null) { if(mOnPurchaseFinishedListener!=null) { mOnPurchaseFinishedListener.onPurchaseError(); } return ; } if(startConnection()) { BillingFlowParams flowParams = BillingFlowParams.newBuilder() .setSku(skuId) .setType(skuType) .build(); mBillingClient.launchBillingFlow(activity,flowParams); } else { if(mOnPurchaseFinishedListener!=null) { mOnPurchaseFinishedListener.onPurchaseError(); } } } /** * 消耗商品 * @param purchaseToken */ public void consumeAsync(String purchaseToken) { if(mBillingClient==null) { return ; } mBillingClient.consumeAsync(purchaseToken, new MyConsumeResponseListener(mOnConsumeResponseListener)); } /** * 消耗内购商品-通过sku数组 * @param sku */ public void consumeAsyncInApp(@NonNull String... sku) { if(mBillingClient==null) { return ; } List<String> skuList = Arrays.asList(sku); consumeAsyncInApp(skuList); } /** * 消耗内购商品-通过sku数组 * @param skuList */ public void consumeAsyncInApp(@NonNull List<String> skuList) { if(mBillingClient==null) { return ; } List<Purchase> purchaseList = queryPurchasesInApp(); if(purchaseList!=null){ for(Purchase purchase : purchaseList){ if(skuList.contains(purchase.getSku())){ mBillingClient.consumeAsync(purchase.getPurchaseToken(), new MyConsumeResponseListener(mOnConsumeResponseListener)); } } } } /** * Googlg消耗商品回调 */ private class MyConsumeResponseListener implements ConsumeResponseListener { private OnConsumeResponseListener onConsumeResponseListener; public MyConsumeResponseListener(OnConsumeResponseListener mOnConsumeResponseListener) { this.onConsumeResponseListener = mOnConsumeResponseListener; } @Override public void onConsumeResponse(int responseCode, String purchaseToken) { if (responseCode == BillingClient.BillingResponse.OK) { if(onConsumeResponseListener!=null){ onConsumeResponseListener.onConsumeSuccess(purchaseToken); } }else{ if(onConsumeResponseListener!=null){ onConsumeResponseListener.onConsumeFail(responseCode); } } } } /** * 获取已经内购的商品 */ public List<Purchase> queryPurchasesInApp() { return queryPurchases(BillingClient.SkuType.INAPP); } /** * 获取已经订阅的商品 * @return 商品列表 */ public List<Purchase> queryPurchasesSubs() { return queryPurchases(BillingClient.SkuType.SUBS); } private List<Purchase> queryPurchases(String skuType) { if(mBillingClient==null) { return null; } if(!mBillingClient.isReady()) { startConnection(); } else { Purchase.PurchasesResult purchasesResult = mBillingClient.queryPurchases(skuType); if(purchasesResult!=null) { if(purchasesResult.getResponseCode()== BillingClient.BillingResponse.OK) { List<Purchase> purchaseList = purchasesResult.getPurchasesList(); if(isAutoConsumeAsync) { if(purchaseList!=null) { for(Purchase purchase:purchaseList) { if(skuType.equals(BillingClient.SkuType.INAPP)) { consumeAsync(purchase.getPurchaseToken()); } } } } return purchaseList; } } } return null; } /** * 异步联网查询所有的内购历史-无论是过期的、取消、等等的订单 * @param listener */ public void queryPurchaseHistoryAsyncInApp(PurchaseHistoryResponseListener listener){ if(mBillingClient!=null) { if(mBillingClient.isReady()){ mBillingClient.queryPurchaseHistoryAsync(BillingClient.SkuType.INAPP,listener); }else{ listener.onPurchaseHistoryResponse(-1,null); } } else{ listener.onPurchaseHistoryResponse(-1,null); } } /** * 异步联网查询所有的订阅历史-无论是过期的、取消、等等的订单 * @param listener */ public void queryPurchaseHistoryAsyncSubs(PurchaseHistoryResponseListener listener){ if(mBillingClient!=null) { if(mBillingClient.isReady()){ mBillingClient.queryPurchaseHistoryAsync(BillingClient.SkuType.SUBS,listener); }else{ listener.onPurchaseHistoryResponse(-1,null); } }else{ listener.onPurchaseHistoryResponse(-1,null); } } /** * 获取有效订阅的数量 * @return -1查询失败,0没有有效订阅,>0具有有效的订阅 */ public int getPurchasesSizeSubs() { List<Purchase> list = queryPurchasesSubs(); if(list!=null) { return list.size(); } return -1; } /** * 通过sku获取订阅商品序号 * @param sku * @return 序号 */ public int getSubsPositionBySku(String sku) { return getPositionBySku(sku, BillingClient.SkuType.SUBS); } /** * 通过sku获取内购商品序号 * @param sku * @return 成功返回需要 失败返回-1 */ public int getInAppPositionBySku(String sku) { return getPositionBySku(sku, BillingClient.SkuType.INAPP); } private int getPositionBySku(String sku,String skuType) { if(skuType.equals(BillingClient.SkuType.INAPP)) { int i = 0; for(String s:inAppSKUS) { if(s.equals(sku)) { return i; } i++; } } else if(skuType.equals(BillingClient.SkuType.SUBS)) { int i = 0; for(String s:subsSKUS) { if(s.equals(sku)) { return i; } i++; } } return -1; } private void executeServiceRequest(final Runnable runnable) { if(startConnection()) { runnable.run(); } } /** * 通过序号获取订阅sku * @param position * @return sku */ public String getSubsSkuByPosition(int position) { if(position>=0&&position<subsSKUS.length) { return subsSKUS[position]; } else { return null; } } /** * 通过序号获取内购sku * @param position * @return sku */ public String getInAppSkuByPosition(int position) { if(position>=0&&position<inAppSKUS.length) { return inAppSKUS[position]; } else { return null; } } /** * 通过sku获取商品类型(订阅获取内购) * @param sku * @return inapp内购,subs订阅 */ public String getSkuType(String sku) { if(Arrays.asList(inAppSKUS).contains(sku)) { return BillingClient.SkuType.INAPP; } else if(Arrays.asList(subsSKUS).contains(sku)) { return BillingClient.SkuType.SUBS; } return null; } public GoogleBillingUtilOld setOnQueryFinishedListener(OnQueryFinishedListener onQueryFinishedListener) { mOnQueryFinishedListener = onQueryFinishedListener; return mGoogleBillingUtil; } public GoogleBillingUtilOld setOnPurchaseFinishedListener(OnPurchaseFinishedListener onPurchaseFinishedListener) { mOnPurchaseFinishedListener = onPurchaseFinishedListener; return mGoogleBillingUtil; } public OnStartSetupFinishedListener getOnStartSetupFinishedListener() { return mOnStartSetupFinishedListener; } public GoogleBillingUtilOld setOnStartSetupFinishedListener(OnStartSetupFinishedListener onStartSetupFinishedListener) { mOnStartSetupFinishedListener = onStartSetupFinishedListener; return mGoogleBillingUtil; } public static OnConsumeResponseListener getmOnConsumeResponseListener() { return mOnConsumeResponseListener; } public GoogleBillingUtilOld setOnConsumeResponseListener(OnConsumeResponseListener onConsumeResponseListener) { mOnConsumeResponseListener = onConsumeResponseListener; return mGoogleBillingUtil; } /** * 本工具查询回调接口 */ public interface OnQueryFinishedListener{ //Inapp和sub都走这个接口,查询的时候一定要判断skuType public void onQuerySuccess(String skuType, List<SkuDetails> list); public void onQueryFail(int responseCode); public void onQueryError(); } /** * 本工具购买回调接口(内购与订阅都走这接口) */ public interface OnPurchaseFinishedListener{ public void onPurchaseSuccess(List<Purchase> list); public void onPurchaseFail(int responseCode); public void onPurchaseError(); } /** * google服务启动接口 */ public interface OnStartSetupFinishedListener{ public void onSetupSuccess(); public void onSetupFail(int responseCode); public void onSetupError(); } /** * 消耗回调监听器 */ public interface OnConsumeResponseListener{ public void onConsumeSuccess(String purchaseToken); public void onConsumeFail(int responseCode); } public boolean isReady() { return mBillingClient!=null&&mBillingClient.isReady(); } public boolean isAutoConsumeAsync() { return isAutoConsumeAsync; } public void setIsAutoConsumeAsync(boolean isAutoConsumeAsync) { this.isAutoConsumeAsync= isAutoConsumeAsync; } /** * 清除所有监听器,防止内存泄漏 * 如果有多个页面使用了支付,需要确保上个页面的cleanListener在下一个页面的GoogleBillingUtil.getInstance()前使用。 * 所以不建议放在onDestory里调用 */ public static void cleanListener() { mOnPurchaseFinishedListener = null; mOnQueryFinishedListener = null; mOnStartSetupFinishedListener = null; mOnConsumeResponseListener = null; if(builder!=null) { builder.setListener(null); } } /** * 断开连接google服务 * 注意!!!一般情况不建议调用该方法,让google保留连接是最好的选择。 */ public static void endConnection() { //注意!!!一般情况不建议调用该方法,让google保留连接是最好的选择。 if(mBillingClient!=null) { if(mBillingClient.isReady()) { mBillingClient.endConnection(); mBillingClient = null; } } } private static void log(String msg) { if(IS_DEBUG) { Log.e(TAG,msg); } } }
java
Apache-2.0
6aa1ac5c4fec48a95a722d8c90a1fc27cc4b8402
2026-01-05T02:37:59.273232Z
false
TJHello/GoogleBilling
https://github.com/TJHello/GoogleBilling/blob/6aa1ac5c4fec48a95a722d8c90a1fc27cc4b8402/billing/src/main/java/com/tjbaobao/gitee/billing/OnGoogleBillingListener.java
billing/src/main/java/com/tjbaobao/gitee/billing/OnGoogleBillingListener.java
package com.tjbaobao.gitee.billing; import android.support.annotation.NonNull; import com.android.billingclient.api.Purchase; import com.android.billingclient.api.SkuDetails; import java.util.ArrayList; import java.util.List; /** * 作者:天镜baobao * 时间:2019/6/2 13:51 * 说明:允许对该封装进行改动,但请注明出处。 * 使用: * * Copyright 2019 天镜baobao * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class OnGoogleBillingListener { @SuppressWarnings("WeakerAccess") public String tag = null; /** * 查询成功 * @param skuType 内购或者订阅 * @param list 商品列表 * @param isSelf 是否是当前页面的结果 */ public void onQuerySuccess(@NonNull String skuType, @NonNull List<SkuDetails> list, boolean isSelf){} /** * 购买成功 * @param purchase 商品 * @param isSelf 是否是当前页面的结果 * @param index 在当前列表的序号 * @param size 商品列表的长度 */ public void onPurchaseSuccess(@NonNull Purchase purchase, boolean isSelf,int index,int size){ onPurchaseSuccess(purchase,isSelf); } /** * 购买成功 * @param purchase 商品 * @param isSelf 是否是当前页面的结果 */ public void onPurchaseSuccess(@NonNull Purchase purchase, boolean isSelf){} /** * 初始化成功 * @param isSelf 是否是当前页面的结果 */ public void onSetupSuccess(boolean isSelf){} /** * 链接断开 */ @SuppressWarnings("WeakerAccess") public void onBillingServiceDisconnected(){ } /** * 消耗成功 * @param purchaseToken token * @param isSelf 是否是当前页面的结果 */ public void onConsumeSuccess(@NonNull String purchaseToken,boolean isSelf){} /** * 失败回调 * @param tag {@link GoogleBillingUtil.GoogleBillingListenerTag} * @param responseCode 返回码{https://developer.android.com/google/play/billing/billing_reference} * @param isSelf 是否是当前页面的结果 */ public void onFail(@NonNull GoogleBillingUtil.GoogleBillingListenerTag tag, int responseCode, boolean isSelf){} /** * google组件初始化失败等等。 * @param tag {@link GoogleBillingUtil.GoogleBillingListenerTag} * @param isSelf 是否是当前页面的结果 */ public void onError(@NonNull GoogleBillingUtil.GoogleBillingListenerTag tag, boolean isSelf){} /** * 获取历史订单-无论是否还有效 * @param purchase 商品实体 */ public void onQueryHistory(@NonNull Purchase purchase){ } }
java
Apache-2.0
6aa1ac5c4fec48a95a722d8c90a1fc27cc4b8402
2026-01-05T02:37:59.273232Z
false
TJHello/GoogleBilling
https://github.com/TJHello/GoogleBilling/blob/6aa1ac5c4fec48a95a722d8c90a1fc27cc4b8402/billing/src/androidTest/java/com/tjbaobao/gitee/billing/ExampleInstrumentedTest.java
billing/src/androidTest/java/com/tjbaobao/gitee/billing/ExampleInstrumentedTest.java
package com.tjbaobao.gitee.billing; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.tjbaobao.gitee.billing.test", appContext.getPackageName()); } }
java
Apache-2.0
6aa1ac5c4fec48a95a722d8c90a1fc27cc4b8402
2026-01-05T02:37:59.273232Z
false
nisrulz/validatetor
https://github.com/nisrulz/validatetor/blob/cfe7115d792a988dd8efee96468ad95223b65a5f/validatetor/src/test/java/com/raywenderlich/android/validatetor/ValidateTorTest.java
validatetor/src/test/java/com/raywenderlich/android/validatetor/ValidateTorTest.java
/* * Modifications Copyright (c) 2018 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.raywenderlich.android.validatetor; import org.json.JSONException; import org.junit.After; import org.junit.Before; import org.junit.Test; import static junit.framework.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class ValidateTorTest { private ValidateTor validateTor; @Before public void setUp() throws Exception { validateTor = new ValidateTor(); } @After public void tearDown() throws Exception { validateTor = null; } @Test public void containsSubstring_shouldReturnsTrue_whenSeedIsPresentInsideString_ignoreCase() throws Exception { assertEquals(true, validateTor.containsSubstring("abcdEfgHiJK", "def")); assertEquals(true, validateTor.containsSubstring("abcdEfgHiJK", "DEFG")); assertEquals(true, validateTor.containsSubstring("abcdEfgHiJK", "f")); assertEquals(true, validateTor.containsSubstring("abcdEfgHiJK", "F")); assertEquals(true, validateTor.containsSubstring("abcdEfgHiJK", "E")); } @Test public void containsSubstring_shouldReturnsFalse_whenSeedIsNotPresentInsideString_ignoreCase() throws Exception { assertEquals(false, validateTor.containsSubstring("abcdEfgHiJK", "acd")); } @Test public void isAlpha_shouldReturnTrue_whenStringContainsOnlyAlphaCharacters() throws Exception { assertEquals(true, validateTor.isAlpha("abcdEfgHiJK")); assertEquals(true, validateTor.isAlpha("abcd")); assertEquals(true, validateTor.isAlpha("A")); assertEquals(true, validateTor.isAlpha("Ab")); assertEquals(true, validateTor.isAlpha("bC")); } @Test public void isAlpha_shouldReturnFalse_whenStringContainsAnyOtherCharacterOtherThanAlphaCharacters() throws Exception { assertEquals(false, validateTor.isAlpha("1")); assertEquals(false, validateTor.isAlpha("&")); assertEquals(false, validateTor.isAlpha("abc123")); assertEquals(false, validateTor.isAlpha("123abc")); assertEquals(false, validateTor.isAlpha(" ")); // space character assertEquals(false, validateTor.isAlpha(" ")); //tab character } @Test public void isAlphanumeric_shouldReturnTrue_whenStringContainsOnlyAlphaAndNumericCharacters() throws Exception { assertEquals(true, validateTor.isAlphanumeric("abcd123")); assertEquals(true, validateTor.isAlphanumeric("12452abcd")); assertEquals(true, validateTor.isAlphanumeric("abcdEfgHiJK")); } @Test public void isAlphanumeric_shouldReturnFalse_whenStringContainsSpecialCharacterOtherThanAlphaNumericCharacters() throws Exception { assertEquals(false, validateTor.isAlphanumeric("#")); assertEquals(false, validateTor.isAlphanumeric("%")); assertEquals(false, validateTor.isAlphanumeric("\r")); assertEquals(false, validateTor.isAlphanumeric("123(")); assertEquals(false, validateTor.isAlphanumeric("123(abc")); assertEquals(false, validateTor.isAlphanumeric(" ")); // space character assertEquals(false, validateTor.isAlphanumeric(" ")); //tab character } @Test public void isBoolean_shouldReturnTrue_whenStringIsTrue() throws Exception { assertEquals(true, validateTor.isBoolean("true")); assertEquals(true, validateTor.isBoolean("True")); assertEquals(true, validateTor.isBoolean("TRUE")); assertEquals(true, validateTor.isBoolean("TrUe")); assertEquals(true, validateTor.isBoolean("false")); assertEquals(true, validateTor.isBoolean("False")); assertEquals(true, validateTor.isBoolean("FALSE")); assertEquals(true, validateTor.isBoolean("fAlSe")); } @Test public void isBoolean_shouldReturnFalse_whenStringIsFalse() throws Exception { assertEquals(false, validateTor.isBoolean("fals1")); assertEquals(false, validateTor.isBoolean("1False")); assertEquals(false, validateTor.isBoolean("Trye1")); assertEquals(false, validateTor.isBoolean("True1")); } @Test public void isIPAddress_shouldReturnTrue_whenStringIsValidIP() throws Exception { assertEquals(true, validateTor.isIPAddress("10.255.255.254")); assertEquals(true, validateTor.isIPAddress("192.168.0.0")); assertEquals(true, validateTor.isIPAddress("0:0:0:0:0:0:0:1")); assertEquals(true, validateTor.isIPAddress("0.0.0.1")); } @Test public void isEmail_shouldReturnTrue_whenStringIsValidEmailAddress() throws Exception { assertEquals(true, validateTor.isEmail("a&d@somedomain.com")); assertEquals(true, validateTor.isEmail("a*d@somedomain.com")); assertEquals(true, validateTor.isEmail("a/d@somedomain.com")); } @Test public void isEmail_shouldReturnTrue_whenStringIsInvalidEmailAddress() throws Exception { assertEquals(false, validateTor.isEmail(".abc@somedomain.com")); assertEquals(false, validateTor.isEmail("bc.@somedomain.com")); assertEquals(false, validateTor.isEmail("a>b@somedomain.com")); } @Test public void isPhoneNumber_shouldReturnTrue_whenStringIsValidPhoneNumber() throws Exception { assertEquals(true, validateTor.isPhoneNumber("800-555-5555")); assertEquals(true, validateTor.isPhoneNumber("333-444-5555")); assertEquals(true, validateTor.isPhoneNumber("212-666-1234")); } @Test public void isPhoneNumber_shouldReturnFalse_whenStringIsInvalidPhoneNumber() throws Exception { assertEquals(false, validateTor.isPhoneNumber("000-000-0000")); assertEquals(false, validateTor.isPhoneNumber("123-456-7890")); assertEquals(false, validateTor.isPhoneNumber("2126661234")); } @Test public void isDecimal_shouldReturnTrue_whenStringIsDecimal() throws Exception { assertEquals(true, validateTor.isDecimal("1.000")); assertEquals(true, validateTor.isDecimal("0012.0")); assertEquals(true, validateTor.isDecimal("123.000")); assertEquals(true, validateTor.isDecimal(".003")); } @Test public void isAtleastLength_shouldReturnTrue_whenStringIsOfAtleastSpecifiedLength() throws Exception { assertEquals(true, validateTor.isAtleastLength("abc", 2)); assertEquals(true, validateTor.isAtleastLength("abc", 3)); assertEquals(true, validateTor.isAtleastLength("abcdef", 5)); } @Test public void isAtleastLength_shouldReturnFalse_whenStringIsNotOfAtleastSpecifiedLength() throws Exception { assertEquals(false, validateTor.isAtleastLength("abc", 4)); assertEquals(false, validateTor.isAtleastLength("abc", 5)); } @Test public void isAtMostLength_shouldReturnTrue_whenStringIsOfAtleastSpecifiedLength() throws Exception { assertEquals(true, validateTor.isAtMostLength("abc", 5)); assertEquals(true, validateTor.isAtMostLength("abc", 3)); assertEquals(true, validateTor.isAtMostLength("abcdef", 10)); } @Test public void isAtMostLength_shouldReturnFalse_whenStringIsNotOfAtleastSpecifiedLength() throws Exception { assertEquals(false, validateTor.isAtMostLength("abc", 2)); assertEquals(false, validateTor.isAtMostLength("abc", 1)); } @Test public void isLowercase_shouldReturnTrue_whenStringIsLowercase() throws Exception { assertEquals(true, validateTor.isLowercase("abc")); } @Test public void isLowercase_shouldReturnFalse_whenStringIsNotLowercase() throws Exception { assertEquals(false, validateTor.isLowercase("aBC")); assertEquals(false, validateTor.isLowercase("ABC")); assertEquals(false, validateTor.isLowercase("AbC")); } @Test public void isUppercase_shouldReturnTrue_whenStringIsUppercase() throws Exception { assertEquals(true, validateTor.isUppercase("ABC")); } @Test public void isUppercase_shouldReturnFalse_whenStringIsNotUppercase() throws Exception { assertEquals(false, validateTor.isUppercase("aBC")); assertEquals(false, validateTor.isUppercase("abc")); assertEquals(false, validateTor.isUppercase("AbC")); } @Test public void isValidMD5_shouldReturnTrue_whenStringIsValidMD5() throws Exception { assertEquals(true, validateTor.isValidMD5("5d41402abc4b2a76b9719d911017c592")); } @Test public void isValidMD5_shouldReturnFalse_whenStringIsInvalidMD5() throws Exception { assertEquals(false, validateTor.isValidMD5("5d41402abc4b2a76b9719d911017")); } // Not work, maybe only in Android JUnit test. @Test public void isJson_shouldReturnTrue_whenStringIsJsonArray() throws JSONException { assertTrue(validateTor.isJSON("[]")); assertTrue(validateTor.isJSON("[{\"id\":1}]")); } @Test public void isNumeric_shouldReturnTrue_whenStringIsNumeric() throws Exception { assertEquals(true, validateTor.isNumeric("1234")); } @Test public void isNumeric_shouldReturnFalse_whenStringIsNotNumeric() throws Exception { assertEquals(false, validateTor.isUppercase("123a")); assertEquals(false, validateTor.isUppercase("abc123")); } @Test public void isInt_shouldReturnTrue_whenStringIsInteger() throws Exception { assertEquals(true, validateTor.isInteger("123")); } @Test public void isInt_shouldReturnFalse_whenStringIsNotInteger() throws Exception { assertEquals(false, validateTor.isInteger("a12")); assertEquals(false, validateTor.isInteger("abc")); } @Test public void isIn_shouldReturnTrue_whenStringIsInTheArray() throws Exception { assertEquals(true, validateTor.isIn("a1", new String[]{"a1", "a2", "a3", "a4"})); } @Test public void isIn_shouldReturnFalse_whenStringIsNotInTheArray() throws Exception { assertEquals(false, validateTor.isIn("a1", new String[]{"a2", "a3", "a4"})); } @Test public void isHexadecimal_shouldReturnTrue_whenStringIsHexadecimal() throws Exception { assertEquals(true, validateTor.isHexadecimal("3FA7")); } @Test public void isHexadecimal_shouldReturnFalse_whenStringIsNotHexadecimal() throws Exception { assertEquals(false, validateTor.isHexadecimal("GFA7")); } @Test public void isPinCode_shouldReturnTrue_whenStringIsValidPinCode() throws Exception { assertEquals(true, validateTor.isPinCode("282001")); } @Test public void isPinCode_shouldReturnFalse_whenStringIsInvalidPinCode() throws Exception { assertEquals(false, validateTor.isPinCode("28200")); assertEquals(false, validateTor.isPinCode("a28200")); assertEquals(false, validateTor.isPinCode("123")); } @Test public void hasAtleastOneDigit_shouldReturnTrue_whenStringHasAtleastOneDigit() throws Exception { assertEquals(true, validateTor.hasAtleastOneDigit("abcde1")); assertEquals(true, validateTor.hasAtleastOneDigit("a1b2c3")); assertEquals(true, validateTor.hasAtleastOneDigit("123")); } @Test public void hasAtleastOneDigit_shouldReturnFalse_whenStringDoesnotHaveAtleastOneDigit() throws Exception { assertEquals(false, validateTor.hasAtleastOneDigit("abcde")); assertEquals(false, validateTor.hasAtleastOneDigit("aaaa")); assertEquals(false, validateTor.hasAtleastOneDigit("#$%^&")); } @Test public void hasAtleastOneLetter_shouldReturnTrue_whenStringHasAtleastOneLetter() throws Exception { assertEquals(true, validateTor.hasAtleastOneLetter("abcde1")); assertEquals(true, validateTor.hasAtleastOneLetter("a1b2c3")); assertEquals(true, validateTor.hasAtleastOneLetter("123abc")); assertEquals(true, validateTor.hasAtleastOneLetter("abcdef")); assertEquals(true, validateTor.hasAtleastOneLetter("ABC")); assertEquals(true, validateTor.hasAtleastOneLetter("AB123")); assertEquals(true, validateTor.hasAtleastOneLetter("aBcD123#")); } @Test public void hasAtleastOneLetter_shouldReturnFalse_whenStringDoesnotHasAtleastOneLetter() throws Exception { assertEquals(false, validateTor.hasAtleastOneLetter("123456")); assertEquals(false, validateTor.hasAtleastOneLetter("11#$")); assertEquals(false, validateTor.hasAtleastOneLetter("#$%^&")); } @Test public void hasAtleastOneLowercaseLetter_shouldReturnTrue_whenStringHasAtleastOneLowercaseLetter() throws Exception { assertEquals(true, validateTor.hasAtleastOneLowercaseCharacter("abcde1")); assertEquals(true, validateTor.hasAtleastOneLowercaseCharacter("a1b2c3")); assertEquals(true, validateTor.hasAtleastOneLowercaseCharacter("123abc")); assertEquals(true, validateTor.hasAtleastOneLowercaseCharacter("abcdef")); assertEquals(true, validateTor.hasAtleastOneLowercaseCharacter("aBcD123#")); } @Test public void hasAtleastOneLowercaseLetter_shouldReturnFalse_whenStringDoesnotHasAtleastOneLowercaseLetter() throws Exception { assertEquals(false, validateTor.hasAtleastOneLowercaseCharacter("123456")); assertEquals(false, validateTor.hasAtleastOneLowercaseCharacter("11#$")); assertEquals(false, validateTor.hasAtleastOneLowercaseCharacter("#$%^&")); assertEquals(false, validateTor.hasAtleastOneLowercaseCharacter("ABC")); assertEquals(false, validateTor.hasAtleastOneLowercaseCharacter("ABC123")); } @Test public void hasAtleastOneUppercaseLetter_shouldReturnTrue_whenStringHasAtleastOneUppercaseLetter() throws Exception { assertEquals(true, validateTor.hasAtleastOneUppercaseCharacter("ABC123")); assertEquals(true, validateTor.hasAtleastOneUppercaseCharacter("A1B2C3")); assertEquals(true, validateTor.hasAtleastOneUppercaseCharacter("123ABC")); assertEquals(true, validateTor.hasAtleastOneUppercaseCharacter("ABC")); assertEquals(true, validateTor.hasAtleastOneUppercaseCharacter("aBcD123#")); } @Test public void hasAtleastOneUpperLetter_shouldReturnFalse_whenStringDoesnotHasAtleastOneUppercaseLetter() throws Exception { assertEquals(false, validateTor.hasAtleastOneUppercaseCharacter("123456")); assertEquals(false, validateTor.hasAtleastOneUppercaseCharacter("11#$")); assertEquals(false, validateTor.hasAtleastOneUppercaseCharacter("#$%^&")); assertEquals(false, validateTor.hasAtleastOneUppercaseCharacter("abc")); assertEquals(false, validateTor.hasAtleastOneUppercaseCharacter("abcde1")); } @Test public void hasAtleastOneSpecialCharacter_shouldReturnTrue_whenStringHasAtleastOneSpecialCharacter() throws Exception { assertEquals(true, validateTor.hasAtleastOneSpecialCharacter("ABC123#")); assertEquals(true, validateTor.hasAtleastOneSpecialCharacter("$A1B2C3")); assertEquals(true, validateTor.hasAtleastOneSpecialCharacter("123@ABC")); assertEquals(true, validateTor.hasAtleastOneSpecialCharacter("!ABC")); assertEquals(true, validateTor.hasAtleastOneSpecialCharacter(".aBcD123#")); assertEquals(true, validateTor.hasAtleastOneSpecialCharacter("11#$")); assertEquals(true, validateTor.hasAtleastOneSpecialCharacter("#$%^&")); } @Test public void hasAtleastOneSpecialCharacter_shouldReturnFalse_whenStringDoesnotHasAtleastOneSpecialCharacter() throws Exception { assertEquals(false, validateTor.hasAtleastOneSpecialCharacter("123456")); assertEquals(false, validateTor.hasAtleastOneSpecialCharacter("abc")); assertEquals(false, validateTor.hasAtleastOneSpecialCharacter("ABC")); assertEquals(false, validateTor.hasAtleastOneSpecialCharacter("ABCdef123")); assertEquals(false, validateTor.hasAtleastOneSpecialCharacter("abcde1")); } }
java
Apache-2.0
cfe7115d792a988dd8efee96468ad95223b65a5f
2026-01-05T02:38:00.782804Z
false
nisrulz/validatetor
https://github.com/nisrulz/validatetor/blob/cfe7115d792a988dd8efee96468ad95223b65a5f/validatetor/src/test/java/com/raywenderlich/android/validatetor/RegexMatcherTest.java
validatetor/src/test/java/com/raywenderlich/android/validatetor/RegexMatcherTest.java
/* * Modifications Copyright (c) 2018 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.raywenderlich.android.validatetor; import org.junit.After; import org.junit.Before; import org.junit.Test; import static junit.framework.Assert.assertEquals; public class RegexMatcherTest { private RegexMatcher regexMatcher; private String str; @Before public void setup() throws Exception { regexMatcher = new RegexMatcher(); } @After public void tearDown() throws Exception { regexMatcher = null; } @Test public void validate_shouldThrowExeception_whenRegexStringIsNull() throws Exception { str = "abc"; boolean threwException = false; try { regexMatcher.validate(str, (String) null); } catch (IllegalArgumentException expectedException) { threwException = true; } assertEquals(true, threwException); } @Test public void validate_shouldThrowExeception_whenRegexStringIsEmpty() throws Exception { str = "abc"; boolean threwException = false; try { regexMatcher.validate(str, ""); } catch (IllegalArgumentException expectedException) { threwException = true; } assertEquals(true, threwException); } @Test public void validate_shouldReturnFalse_whenStringIsEmpty() throws Exception { str = ""; assertEquals(false, regexMatcher.validate(str, RegexPresetPattern.ALPHA)); } @Test public void validate_shouldReturnFalse_whenStringIsNull() throws Exception { assertEquals(false, regexMatcher.validate(null, RegexPresetPattern.ALPHA)); } @Test public void validate_shouldReturnTrue_whenStringIsValidAlpha() throws Exception { str = "abc"; assertEquals(true, regexMatcher.validate(str, RegexPresetPattern.ALPHA)); } @Test public void validate_shouldReturnTrue_whenRegexStringIsValidString() throws Exception { str = "abc"; assertEquals(true, regexMatcher.validate(str, "[a-zA-Z]+")); } }
java
Apache-2.0
cfe7115d792a988dd8efee96468ad95223b65a5f
2026-01-05T02:38:00.782804Z
false
nisrulz/validatetor
https://github.com/nisrulz/validatetor/blob/cfe7115d792a988dd8efee96468ad95223b65a5f/validatetor/src/test/java/com/raywenderlich/android/validatetor/CardValidatorTest.java
validatetor/src/test/java/com/raywenderlich/android/validatetor/CardValidatorTest.java
/* * Modifications Copyright (c) 2018 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.raywenderlich.android.validatetor; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.Arrays; import java.util.Collection; import static junit.framework.Assert.assertEquals; import static org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class CardValidatorTest { private final String cardNumber; private final boolean expectedIsValid; private final String expectedCardIssuer; private final String expectedErrorInfo; private CardInformation cardInformation; private CardValidator cardValidator; public CardValidatorTest(final String cardNumber, final boolean expectedIsValid, final String expectedCardIssuer, String expectedErrorInfo) { this.cardNumber = cardNumber; this.expectedIsValid = expectedIsValid; this.expectedCardIssuer = expectedCardIssuer; this.expectedErrorInfo = expectedErrorInfo; } @Parameters(name = "{index}: testCreditCard({0}) = {1}") public static Collection<Object[]> data() { return Arrays.asList(new Object[][]{ {"4929804463622139", true, "Visa", "NA"}, {"4929804463622138", false, "Visa", "Number did not pass the Luhn Algo Test!"}, {"6762765696545485", true, "Maestro", "NA"}, {"5212132012291762", false, "Mastercard", "Number did not pass the Luhn Algo Test!"}, {"6210948000000029", true, "China Union Pay", "NA"}, {"61294wuriyq98797", false, "Unknown", "Number should be composed of only digits!"}, {"00007129847197591315", false, "Unknown", "Card number should be of length > 12 and < 19 digits!"}, {"8971247", false, "Unknown", "Card number should be of length > 12 and < 19 digits!"}, {"1241241294184701240124", false, "Unknown", "Card number should be of length > 12 and < 19 digits!"}, }); } @Before public void setup() throws Exception { cardValidator = new CardValidator(); cardInformation = cardValidator.getCardInformation(cardNumber); } @Test public void checkIfCardIsValid() { assertEquals(cardInformation.isValid(), expectedIsValid); } @Test public void checkIfCardIssuerIsCorrect() { assertEquals(cardInformation.getCardIssuer(), expectedCardIssuer); } @Test public void checkIfErrorInfoIsCorrect() { assertEquals(cardInformation.getError(), expectedErrorInfo); } @Test public void checkIfNumberIsSetInCardInformationObject() { assertEquals(cardInformation.getCardNumber(), cardNumber); } }
java
Apache-2.0
cfe7115d792a988dd8efee96468ad95223b65a5f
2026-01-05T02:38:00.782804Z
false
nisrulz/validatetor
https://github.com/nisrulz/validatetor/blob/cfe7115d792a988dd8efee96468ad95223b65a5f/validatetor/src/main/java/com/raywenderlich/android/validatetor/RegexPresetPattern.java
validatetor/src/main/java/com/raywenderlich/android/validatetor/RegexPresetPattern.java
/* * Modifications Copyright (c) 2018 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.raywenderlich.android.validatetor; import java.util.regex.Pattern; /** * The type Regex preset pattern. */ class RegexPresetPattern { /** * The constant ATLEAST_ONE_DIGIT. */ final static Pattern ATLEAST_ONE_DIGIT = Pattern.compile("[0-9]"); /** * The constant ATLEAST_ONE_UPPERCASE_CHARACTER. */ final static Pattern ATLEAST_ONE_UPPERCASE_CHARACTER = Pattern.compile("[A-Z]"); /** * The constant ATLEAST_ONE_LOWERCASE_CHARACTER. */ final static Pattern ATLEAST_ONE_LOWERCASE_CHARACTER = Pattern.compile("[a-z]"); /** * The constant ATLEAST_ONE_LETTER. */ final static Pattern ATLEAST_ONE_LETTER = Pattern.compile("[a-zA-Z]"); /** * The constant ATLEAST_ONE_SPECIAL_CHARACTER. */ final static Pattern ATLEAST_ONE_SPECIAL_CHARACTER = Pattern.compile("[^a-zA-Z0-9\\s]"); /** * The constant PINCODE. */ final static Pattern PINCODE = Pattern.compile("^[0-9]{6}$"); /** * The constant ALPHANUMERIC. */ final static Pattern ALPHANUMERIC = Pattern.compile("^[a-zA-Z0-9_]+$"); /** * The constant NUMERIC. */ final static Pattern NUMERIC = Pattern.compile("^[0-9]+"); /** * The constant ALPHA. */ final static Pattern ALPHA = Pattern.compile("[a-zA-Z]+"); /** * The constant DECIMAL_NUMBER. */ final static Pattern DECIMAL_NUMBER = Pattern.compile("^[0-9]*\\.?[0-9]*$"); /** * The constant MAC_ADDRESS. */ final static Pattern MAC_ADDRESS = Pattern.compile("^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$"); /** * The constant HEXADECIMAL. */ final static Pattern HEXADECIMAL = Pattern.compile("\\p{XDigit}+"); final static Pattern MD5 = Pattern.compile("[a-fA-F0-9]{32}"); /** * Matches all IPV6 and IPV4 addresses. Doesn't limit IPV4 to just values of 255. Doesn't * allow IPV6 compression. */ final static Pattern IP_ADDRESS = Pattern.compile("([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4}|(\\d{1,3}\\.){3}\\d{1,3}"); /** * According to RFC 2821 (see http://tools.ietf.org/html/2821) and * RFC 2822 (see http://tools.ietf.org/html/2822), the local-part of an email addresses * may use any of these ASCII characters: * 1. Uppercase and lowercare letters * 2. The digits 0 through 9 * 3. The characters, !#$%&'*+-/=?^_`{|}~ * 4. The character "." provided that it is not the first or last character in the local-part. */ final static Pattern EMAIL = Pattern.compile("^((([!#$%&'*+\\-/=?^_`{|}~\\w])|" + "([!#$%&'*+\\-/=?^_`{|}~\\w][!#$%&'*+\\-/=?^_`{|}~\\w]*[!#$%&'*+\\-/=?^_`{|}~\\w]))[@]\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*)$"); /** * Matches a hyphen separated US phone number, of the form ANN-NNN-NNNN, where A is between 2 * and 9 and N is between 0 and 9. */ final static Pattern PHONE = Pattern.compile("^[2-9]\\d{2}-\\d{3}-\\d{4}$"); }
java
Apache-2.0
cfe7115d792a988dd8efee96468ad95223b65a5f
2026-01-05T02:38:00.782804Z
false
nisrulz/validatetor
https://github.com/nisrulz/validatetor/blob/cfe7115d792a988dd8efee96468ad95223b65a5f/validatetor/src/main/java/com/raywenderlich/android/validatetor/RegexMatcher.java
validatetor/src/main/java/com/raywenderlich/android/validatetor/RegexMatcher.java
/* * Modifications Copyright (c) 2018 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.raywenderlich.android.validatetor; import java.util.regex.Pattern; /** * The type Regex matcher. */ public class RegexMatcher { /** * Validate string against a regex. * * @param dataStr the data str * @param regex the regex * @return the boolean */ public boolean validate(String dataStr, String regex) { if (regex == null || regex.equals("")) { throw new IllegalArgumentException("regex field cannot is be null or empty!"); } else { Pattern p = Pattern.compile(regex); return validate(dataStr, p); } } /** * Find in string against a regex. * * @param dataStr the data str * @param regex the regex * @return the boolean */ public boolean find(String dataStr, String regex) { if (regex == null || regex.equals("")) { throw new IllegalArgumentException("regex field cannot is be null or empty!"); } else { Pattern p = Pattern.compile(regex); return find(dataStr, p); } } /** * Validate string against a pattern. * * @param dataStr the data str * @param pattern the pattern * @return the boolean */ public boolean validate(String dataStr, Pattern pattern) { return !(dataStr == null || dataStr.equals("")) && pattern.matcher(dataStr).matches(); } /** * Find in string against a pattern. * * @param dataStr the data str * @param pattern the pattern * @return the boolean */ public boolean find(String dataStr, Pattern pattern) { return !(dataStr == null || dataStr.equals("")) && pattern.matcher(dataStr).find(); } }
java
Apache-2.0
cfe7115d792a988dd8efee96468ad95223b65a5f
2026-01-05T02:38:00.782804Z
false
nisrulz/validatetor
https://github.com/nisrulz/validatetor/blob/cfe7115d792a988dd8efee96468ad95223b65a5f/validatetor/src/main/java/com/raywenderlich/android/validatetor/ValidateTor.java
validatetor/src/main/java/com/raywenderlich/android/validatetor/ValidateTor.java
/* * Modifications Copyright (c) 2018 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.raywenderlich.android.validatetor; import android.graphics.Color; import android.text.TextUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.regex.Pattern; /** * The type Validate tor. */ public class ValidateTor { /** * The Regex matcher. */ private final RegexMatcher regexMatcher; /** * The Card validator. */ private final CardValidator cardValidator; /** * Instantiates a new Validate tor. */ public ValidateTor() { this.regexMatcher = new RegexMatcher(); this.cardValidator = new CardValidator(); } /** * check if the string contains the seed. * * @param str the str * @param seed the seed * @return the boolean */ public boolean containsSubstring(String str, String seed) { return Pattern.compile(Pattern.quote(seed), Pattern.CASE_INSENSITIVE).matcher(str).find(); } /** * check if the string contains only letters. * * @param str the str * @return the boolean */ public boolean isAlpha(String str) { return regexMatcher.validate(str, RegexPresetPattern.ALPHA); } /** * check if the string contains only letters and numbers. * * @param str the str * @return the boolean */ public boolean isAlphanumeric(String str) { return regexMatcher.validate(str, RegexPresetPattern.ALPHANUMERIC); } /** * check if a string is a boolean. * * @param str the str * @return the boolean */ public boolean isBoolean(String str) { return str.toLowerCase().equals("true") || str.toLowerCase().equals("false"); } /** * check if the string is a ip address. * * @param str the str * @return the boolean */ public boolean isIPAddress(String str) { return regexMatcher.validate(str, RegexPresetPattern.IP_ADDRESS); } /** * check if the string is a email address * * @param str the str * @return the boolean */ public boolean isEmail(String str) { return regexMatcher.validate(str, RegexPresetPattern.EMAIL); } /** * check if the string is a US phone number * * @param str the str * @return the boolean */ public boolean isPhoneNumber(String str) { return regexMatcher.validate(str, RegexPresetPattern.PHONE); } /** * check if the string has a length of zero. * * @param str the str * @return the boolean */ public boolean isEmpty(String str) { return str == null || TextUtils.isEmpty(str); } /** * check if a string is base64 encoded. * * @param str the str * @return the boolean */ public boolean isBase64(String str) { try { android.util.Base64.decode(str, android.util.Base64.DEFAULT); return true; } catch (IllegalArgumentException e) { return false; } } /** * check if the string represents a decimal number, such as 0.1, .3, 1.1, 1.00003, 4.0, etc. * * @param str the str * @return the boolean */ public boolean isDecimal(String str) { return regexMatcher.validate(str, RegexPresetPattern.DECIMAL_NUMBER); } /** * check if the string is of atleast the specified length. * * @param str the str * @param len the len * @return the boolean */ public boolean isAtleastLength(String str, int len) { return str.length() >= len; } /** * check if the string is of atmost the specified length. * * @param str the str * @param len the len * @return the boolean */ public boolean isAtMostLength(String str, int len) { return str.length() <= len; } /** * check if the string is all lowercase. * * @param str the str * @return the boolean */ public boolean isLowercase(String str) { return str.equals(str.toLowerCase()); } /** * check if the string is all uppercase. * * @param str the str * @return the boolean */ public boolean isUppercase(String str) { return str.equals(str.toUpperCase()); } /** * check if the string is a valid MD5 hash. * * @param str the str * @return the boolean */ public boolean isValidMD5(String str) { return regexMatcher.validate(str, RegexPresetPattern.MD5); } /** * check if the string contains only numbers. * * @param str the str * @return the boolean */ public boolean isNumeric(String str) { return regexMatcher.validate(str, RegexPresetPattern.NUMERIC); } /** * check if the string is a MAC address * * @param str the str * @return the boolean */ public boolean isMACAddress(String str) { return regexMatcher.validate(str, RegexPresetPattern.MAC_ADDRESS); } /** * check if the string is valid JSON. * * @param str the str * @return the boolean */ public boolean isJSON(String str) { try { // check against JSONObject new JSONObject(str); } catch (JSONException ex) { // check against JSONArray try { new JSONArray(str); } catch (JSONException ex1) { return false; } return true; } return true; } /** * check if the string is an integer. * * @param str the str * @return the boolean */ public boolean isInteger(String str) { if (str == null) { return false; } int length = str.length(); if (length == 0) { return false; } int i = 0; if (str.charAt(0) == '-') { if (length == 1) { return false; } i = 1; } for (; i < length; i++) { char c = str.charAt(i); if (c < '0' || c > '9') { return false; } } return true; } /** * check if the string is present in an array of allowed values. * * @param str the str * @param values the values * @return the boolean */ public boolean isIn(String str, String[] values) { for (String val : values) { if (val.equals(str)) { return true; } } return false; } /** * check if the string is a hexadecimal number. * * @param str the str * @return the boolean */ public boolean isHexadecimal(String str) { return regexMatcher.validate(str, RegexPresetPattern.HEXADECIMAL); } /** * check if the string is a pincode. * * @param str the str * @return the boolean */ public boolean isPinCode(String str) { return regexMatcher.validate(str, RegexPresetPattern.PINCODE); } /** * check if the string is a hexadecimal color. * * @param str the str * @return the boolean */ public boolean isHexColor(String str) { try { Color.parseColor(str); return true; } catch (IllegalArgumentException iae) { return false; } } /** * check if the string has atleast one digit * * @param str the str * @return the boolean */ public boolean hasAtleastOneDigit(String str) { return regexMatcher.find(str, RegexPresetPattern.ATLEAST_ONE_DIGIT); } /** * check if the string has atleast one letter * * @param str the str * @return the boolean */ public boolean hasAtleastOneLetter(String str) { return regexMatcher.find(str, RegexPresetPattern.ATLEAST_ONE_LETTER); } /** * check if the string has atleast one lowercase character * * @param str the str * @return the boolean */ public boolean hasAtleastOneLowercaseCharacter(String str) { return regexMatcher.find(str, RegexPresetPattern.ATLEAST_ONE_LOWERCASE_CHARACTER); } /** * check if the string has atleast one uppercase character * * @param str the str * @return the boolean */ public boolean hasAtleastOneUppercaseCharacter(String str) { return regexMatcher.find(str, RegexPresetPattern.ATLEAST_ONE_UPPERCASE_CHARACTER); } /** * check if the string has atleast one special character * * @param str the str * @return the boolean */ public boolean hasAtleastOneSpecialCharacter(String str) { return regexMatcher.find(str, RegexPresetPattern.ATLEAST_ONE_SPECIAL_CHARACTER); } /** * check if the string is a valid credit card number * * @param str the str * @return the boolean */ public boolean validateCreditCard(String str) { return cardValidator.validateCreditCardNumber(str); } /** * Get CreditCard information from string * * @param str the str * @return the credit card info */ public CardInformation getCreditCardInfo(String str) { return cardValidator.getCardInformation(str); } }
java
Apache-2.0
cfe7115d792a988dd8efee96468ad95223b65a5f
2026-01-05T02:38:00.782804Z
false
nisrulz/validatetor
https://github.com/nisrulz/validatetor/blob/cfe7115d792a988dd8efee96468ad95223b65a5f/validatetor/src/main/java/com/raywenderlich/android/validatetor/CardValidator.java
validatetor/src/main/java/com/raywenderlich/android/validatetor/CardValidator.java
/* * Modifications Copyright (c) 2018 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.raywenderlich.android.validatetor; /** * The type Card validator. */ class CardValidator { /** * Validate credit card number. * * @param number the number * @return the boolean */ public boolean validateCreditCardNumber(String number) { return checkIfNumberContainsOnlyDigits(number) && validateLengthOfCardNumber(number) && (validateAndGetStartingSixDigits(number) > 0) && validateCardNumberWithLuhnAlgo(number); } private String getErrorInfo(String number) { if (!checkIfNumberContainsOnlyDigits(number)) { return "Number should be composed of only digits!"; } if (!validateLengthOfCardNumber(number)) { return "Card number should be of length > 12 and < 19 digits!"; } if (validateAndGetStartingSixDigits(number) == 0) { return "Number contains leading zeros!"; } if (!validateCardNumberWithLuhnAlgo(number)) { return "Number did not pass the Luhn Algo Test!"; } return "NA"; } private String getCreditCardIssuer(String number) { return getTypeOfCard(validateAndGetStartingSixDigits(number)); } private int countDigitsInNumber(long num) { int count = 0; while (num > 0) { num = num / 10; count++; } return count; } private boolean validateCardNumberWithLuhnAlgo(String num) { int sumOfDoubleOfDigits = 0; if (checkIfNumberContainsOnlyDigits(num)) { boolean alternateValue = false; for (int i = num.length() - 1; i >= 0; i--) { int digit = Integer.parseInt(String.valueOf(num.charAt(i))); if (alternateValue) { digit *= 2; if (digit > 9) { digit -= 9; } } sumOfDoubleOfDigits += digit; alternateValue = !alternateValue; } } return (sumOfDoubleOfDigits % 10 == 0); } private boolean checkIfNumberContainsOnlyDigits(String number) { // check if number string contains only digits return number.matches("[0-9]+"); } private boolean validateLengthOfCardNumber(String number) { // check for number of digits return !(number.length() < 12 || number.length() > 19); } private long validateAndGetStartingSixDigits(String number) { String startSixDigitSubstring = number.substring(0, 6); if (checkIfNumberContainsOnlyDigits(startSixDigitSubstring)) { long startNumber = Long.parseLong(startSixDigitSubstring); // Check for leading zeros if (startNumber == 0 || countDigitsInNumber(startNumber) < 6) { return 0; } return startNumber; } else { return 0; } } private String getTypeOfCard(long startingSixDigits) { if (startingSixDigits > 400000 && startingSixDigits < 499999) { return "Visa"; } else if ((startingSixDigits > 222100 && startingSixDigits < 272099) || (startingSixDigits > 510000 && startingSixDigits < 559999)) { return "Mastercard"; } else if (startingSixDigits > 620000 && startingSixDigits < 629999) { return "China Union Pay"; } else if ((startingSixDigits > 500000 && startingSixDigits < 509999) || (startingSixDigits > 560000 && startingSixDigits < 699999)) { return "Maestro"; } else { return "Unknown"; } } /** * Gets card information. * * @param num the num * @return the card information */ public CardInformation getCardInformation(String num) { CardInformation cardInformation = new CardInformation(num); cardInformation.setCardIssuer(getCreditCardIssuer(num)); cardInformation.setValid(validateCreditCardNumber(num)); cardInformation.setError(getErrorInfo(num)); return cardInformation; } }
java
Apache-2.0
cfe7115d792a988dd8efee96468ad95223b65a5f
2026-01-05T02:38:00.782804Z
false
nisrulz/validatetor
https://github.com/nisrulz/validatetor/blob/cfe7115d792a988dd8efee96468ad95223b65a5f/validatetor/src/main/java/com/raywenderlich/android/validatetor/CardInformation.java
validatetor/src/main/java/com/raywenderlich/android/validatetor/CardInformation.java
/* * Modifications Copyright (c) 2018 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.raywenderlich.android.validatetor; /** * The type Card information. */ public class CardInformation { private String cardIssuer; private boolean isValid; private String error; private String cardNumber; /** * Instantiates a new Card information. * * @param cardNumber the card number */ public CardInformation(final String cardNumber) { this.cardNumber = cardNumber; } /** * Gets card issuer. * * @return the card issuer */ public String getCardIssuer() { return cardIssuer; } /** * Sets card issuer. * * @param cardIssuer the card issuer */ public void setCardIssuer(final String cardIssuer) { this.cardIssuer = cardIssuer; } /** * Is valid boolean. * * @return the boolean */ public boolean isValid() { return isValid; } /** * Sets valid. * * @param valid the valid */ public void setValid(final boolean valid) { isValid = valid; } /** * Gets error. * * @return the error */ public String getError() { return error; } /** * Sets error. * * @param error the error */ public void setError(final String error) { this.error = error; } /** * Gets card number. * * @return the card number */ public String getCardNumber() { return cardNumber; } /** * Sets card number. * * @param cardNumber the card number */ public void setCardNumber(final String cardNumber) { this.cardNumber = cardNumber; } @Override public String toString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("Card Issuer = ").append(cardIssuer).append("\n"); stringBuilder.append("Card Number = ").append(cardNumber).append("\n"); stringBuilder.append("Is Valid = ").append(isValid).append("\n"); if (!isValid) { stringBuilder.append("Error Info = ").append(error).append("\n"); } return stringBuilder.toString(); } }
java
Apache-2.0
cfe7115d792a988dd8efee96468ad95223b65a5f
2026-01-05T02:38:00.782804Z
false
nisrulz/validatetor
https://github.com/nisrulz/validatetor/blob/cfe7115d792a988dd8efee96468ad95223b65a5f/validatetor/src/androidTest/java/com/raywenderlich/android/validatetor/ExampleInstrumentedTest.java
validatetor/src/androidTest/java/com/raywenderlich/android/validatetor/ExampleInstrumentedTest.java
package com.raywenderlich.android.validatetor; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.raywenderlich.android.validatetor.test", appContext.getPackageName()); } }
java
Apache-2.0
cfe7115d792a988dd8efee96468ad95223b65a5f
2026-01-05T02:38:00.782804Z
false
dailystudio/ml
https://github.com/dailystudio/ml/blob/e32c0bbcf77183ff2ee407b4f179a094f6fdb12a/deeplab/app/src/test/java/com/dailystudio/deeplab/ExampleUnitTest.java
deeplab/app/src/test/java/com/dailystudio/deeplab/ExampleUnitTest.java
package com.dailystudio.deeplab; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() { assertEquals(4, 2 + 2); } }
java
Apache-2.0
e32c0bbcf77183ff2ee407b4f179a094f6fdb12a
2026-01-05T02:37:31.908377Z
false
dailystudio/ml
https://github.com/dailystudio/ml/blob/e32c0bbcf77183ff2ee407b4f179a094f6fdb12a/deeplab/app/src/main/java/com/dailystudio/deeplab/DeeplabApplication.java
deeplab/app/src/main/java/com/dailystudio/deeplab/DeeplabApplication.java
package com.dailystudio.deeplab; import com.dailystudio.app.DevBricksApplication; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; public class DeeplabApplication extends DevBricksApplication { @Override public void onCreate() { super.onCreate(); ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this).build(); ImageLoader.getInstance().init(config); } @Override protected boolean isDebugBuild() { return BuildConfig.DEBUG; } }
java
Apache-2.0
e32c0bbcf77183ff2ee407b4f179a094f6fdb12a
2026-01-05T02:37:31.908377Z
false
dailystudio/ml
https://github.com/dailystudio/ml/blob/e32c0bbcf77183ff2ee407b4f179a094f6fdb12a/deeplab/app/src/main/java/com/dailystudio/deeplab/MainActivity.java
deeplab/app/src/main/java/com/dailystudio/deeplab/MainActivity.java
package com.dailystudio.deeplab; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.content.res.ColorStateList; import android.graphics.Bitmap; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.ActivityCompat; import android.support.v4.app.Fragment; import android.support.v4.content.ContextCompat; import android.view.View; import com.dailystudio.app.activity.ActionBarFragmentActivity; import com.dailystudio.app.utils.ActivityLauncher; import com.dailystudio.app.utils.ArrayUtils; import com.dailystudio.deeplab.ml.DeeplabModel; import com.dailystudio.development.Logger; public class MainActivity extends ActionBarFragmentActivity { private final static int REQUEST_REQUIRED_PERMISSION = 0x01; private final static int REQUEST_PICK_IMAGE = 0x02; private class InitializeModelAsyncTask extends AsyncTask<Void, Void, Boolean> { @Override protected Boolean doInBackground(Void... voids) { final boolean ret = DeeplabModel.getInstance().initialize( getApplicationContext()); Logger.debug("initialize deeplab model: %s", ret); return ret; } } private FloatingActionButton mFabPickImage; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setupViews(); } private void setupViews() { mFabPickImage = findViewById(R.id.fab_pick_image); if (mFabPickImage != null) { mFabPickImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent; if (Build.VERSION.SDK_INT >= 19) { intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, false); intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION); } else { intent = new Intent(Intent.ACTION_GET_CONTENT); } intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.setType("image/*"); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); ActivityLauncher.launchActivityForResult(MainActivity.this, Intent.createChooser(intent, getString(R.string.app_name)), REQUEST_PICK_IMAGE); } }); } } @Override protected void onStart() { super.onStart(); syncUIWithPermissions(true); } @Override protected void onResume() { super.onResume(); syncUIWithPermissions(false); } private void syncUIWithPermissions(boolean requestIfNeed) { final boolean granted = checkRequiredPermissions(requestIfNeed); setPickImageEnabled(granted); if (granted && !DeeplabModel.getInstance().isInitialized()) { initModel(); } } private boolean checkRequiredPermissions() { return checkRequiredPermissions(false); } private boolean checkRequiredPermissions(boolean requestIfNeed) { final boolean writeStoragePermGranted = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED; Logger.debug("storage permission granted: %s", writeStoragePermGranted); if (!writeStoragePermGranted && requestIfNeed) { requestRequiredPermissions(); } return writeStoragePermGranted; } private void requestRequiredPermissions() { ActivityCompat.requestPermissions(this, new String[]{ Manifest.permission.WRITE_EXTERNAL_STORAGE, }, REQUEST_REQUIRED_PERMISSION); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { Logger.debug("requestCode = 0x%02x, permission = [%s], grant = [%s]", requestCode, ArrayUtils.stringArrayToString(permissions, ","), ArrayUtils.intArrayToString(grantResults)); if (requestCode == REQUEST_REQUIRED_PERMISSION) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Logger.debug("permission granted, initialize model."); initModel(); if (mFabPickImage != null) { mFabPickImage.setEnabled(true); mFabPickImage.setBackgroundTintList( ColorStateList.valueOf(getColor(R.color.colorAccent))); } } else { Logger.debug("permission denied, disable fab."); } } else { super.onRequestPermissionsResult(requestCode, permissions, grantResults); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { Logger.debug("requestCode = %d, resultCode = %d, data = %s", requestCode, resultCode, data); if (requestCode == REQUEST_PICK_IMAGE && resultCode == RESULT_OK) { Uri pickedImageUri = data.getData(); Logger.debug("picked: %s", pickedImageUri); if (pickedImageUri != null) { if(Build.VERSION.SDK_INT >= 19){ final int takeFlags = data.getFlags() & Intent.FLAG_GRANT_READ_URI_PERMISSION; getContentResolver() .takePersistableUriPermission(pickedImageUri, takeFlags); } segmentImage(pickedImageUri); } } else { super.onActivityResult(requestCode, resultCode, data); } } private void segmentImage(Uri pickedImageUri) { Fragment fragment = findFragment(R.id.fragment_segment_bitmaps); if (fragment instanceof SegmentBitmapsFragment) { ((SegmentBitmapsFragment)fragment).segmentBitmap(pickedImageUri); } } private void initModel() { new InitializeModelAsyncTask().execute((Void)null); } private void setPickImageEnabled(boolean enabled) { if (mFabPickImage != null) { mFabPickImage.setEnabled(enabled); int resId = enabled ? R.color.colorAccent : R.color.light_gray; mFabPickImage.setBackgroundTintList( ColorStateList.valueOf(getColor(resId))); } } }
java
Apache-2.0
e32c0bbcf77183ff2ee407b4f179a094f6fdb12a
2026-01-05T02:37:31.908377Z
false
dailystudio/ml
https://github.com/dailystudio/ml/blob/e32c0bbcf77183ff2ee407b4f179a094f6fdb12a/deeplab/app/src/main/java/com/dailystudio/deeplab/SegmentBitmapsFragment.java
deeplab/app/src/main/java/com/dailystudio/deeplab/SegmentBitmapsFragment.java
package com.dailystudio.deeplab; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.content.Loader; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.dailystudio.app.fragment.AbsArrayRecyclerViewFragment; import com.dailystudio.app.ui.AbsArrayRecyclerAdapter; import com.dailystudio.development.Logger; import com.yarolegovich.discretescrollview.DSVOrientation; import com.yarolegovich.discretescrollview.DiscreteScrollView; import com.yarolegovich.discretescrollview.transform.ScaleTransformer; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import java.util.List; public class SegmentBitmapsFragment extends AbsArrayRecyclerViewFragment<SegmentBitmap, SegmentBitmapViewHolder> { private final static int LOADER_ID = 0x525; private DiscreteScrollView mRecyclerView; private Uri mImageUri = null; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); EventBus.getDefault().register(this); setShowLoadingView(false); } @Override public void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_segment_bitmaps, null); setupViews(view); return view; } private void setupViews(View fragmentView) { if (fragmentView == null) { return; } mRecyclerView = fragmentView.findViewById(android.R.id.list); if (mRecyclerView != null) { mRecyclerView.setSlideOnFling(true); mRecyclerView.setItemTransformer(new ScaleTransformer.Builder() .setMaxScale(1.0f) .setMinScale(0.8f) .build()); } } @Override protected RecyclerView.Adapter onCreateAdapter() { return new SegmentBitmapsRecyclerAdapter(getContext()); } @Override protected RecyclerView.LayoutManager onCreateLayoutManager() { return null; } @Override protected RecyclerView.ItemDecoration onCreateItemDecoration() { return null; } @Override protected int getLoaderId() { return LOADER_ID; } @Override protected Bundle createLoaderArguments() { return new Bundle(); } @Override public Loader<List<SegmentBitmap>> onCreateLoader(int id, Bundle args) { return new SegmentBitmapsLoader(getContext(), mImageUri); } public void segmentBitmap(Uri pickedImageUri) { mImageUri = pickedImageUri; fastDisplayOrigin(); restartLoader(); } private void fastDisplayOrigin() { if (mRecyclerView != null) { mRecyclerView.scrollToPosition(0); RecyclerView.Adapter adapter = mRecyclerView.getAdapter(); if (adapter instanceof AbsArrayRecyclerAdapter) { AbsArrayRecyclerAdapter bitmapsAdapter = (AbsArrayRecyclerAdapter)adapter; bitmapsAdapter.clear(); bitmapsAdapter.add(new SegmentBitmap(R.string.label_original, mImageUri)); bitmapsAdapter.add(new SegmentBitmap(R.string.label_mask, (Bitmap)null)); bitmapsAdapter.add(new SegmentBitmap(R.string.label_cropped, (Bitmap)null)); } } } @Subscribe(threadMode = ThreadMode.MAIN) public void onImageDimenEvent(ImageDimenEvent event) { Logger.debug("new dimen event: %s", event); if (event.imageUri == mImageUri) { if (mRecyclerView == null) { return; } RecyclerView.Adapter adapter = mRecyclerView.getAdapter(); if (adapter instanceof SegmentBitmapsRecyclerAdapter == false) { return; } DSVOrientation viewOrientation = (event.height > event.width ? DSVOrientation.HORIZONTAL : DSVOrientation.VERTICAL); DSVOrientation itemOrientation = (event.height > event.width ? DSVOrientation.VERTICAL : DSVOrientation.HORIZONTAL); mRecyclerView.setOrientation(viewOrientation); ((SegmentBitmapsRecyclerAdapter)adapter).setOrientation(itemOrientation); } } }
java
Apache-2.0
e32c0bbcf77183ff2ee407b4f179a094f6fdb12a
2026-01-05T02:37:31.908377Z
false
dailystudio/ml
https://github.com/dailystudio/ml/blob/e32c0bbcf77183ff2ee407b4f179a094f6fdb12a/deeplab/app/src/main/java/com/dailystudio/deeplab/SegmentBitmap.java
deeplab/app/src/main/java/com/dailystudio/deeplab/SegmentBitmap.java
package com.dailystudio.deeplab; import android.graphics.Bitmap; import android.net.Uri; public class SegmentBitmap { public Bitmap bitmap; public int labelResId; public Uri bitmapUri; public SegmentBitmap(int label, Bitmap bitmap) { this.bitmap = bitmap; this.labelResId = label; this.bitmapUri = null; } public SegmentBitmap(int label, Uri uri) { this.bitmap = null; this.labelResId = label; this.bitmapUri = uri; } }
java
Apache-2.0
e32c0bbcf77183ff2ee407b4f179a094f6fdb12a
2026-01-05T02:37:31.908377Z
false
dailystudio/ml
https://github.com/dailystudio/ml/blob/e32c0bbcf77183ff2ee407b4f179a094f6fdb12a/deeplab/app/src/main/java/com/dailystudio/deeplab/SegmentBitmapsRecyclerAdapter.java
deeplab/app/src/main/java/com/dailystudio/deeplab/SegmentBitmapsRecyclerAdapter.java
package com.dailystudio.deeplab; import android.content.Context; import android.view.View; import android.view.ViewGroup; import com.dailystudio.app.ui.AbsArrayRecyclerAdapter; import com.dailystudio.development.Logger; import com.yarolegovich.discretescrollview.DSVOrientation; public class SegmentBitmapsRecyclerAdapter extends AbsArrayRecyclerAdapter<SegmentBitmap, SegmentBitmapViewHolder> { private DSVOrientation mOrientation = DSVOrientation.VERTICAL; public SegmentBitmapsRecyclerAdapter(Context context) { super(context); } @Override public SegmentBitmapViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { Logger.debug("orientation of holder: %s", (mOrientation == DSVOrientation.VERTICAL ? "VERTICAL" : "HORIZONTAL")); View view = mLayoutInflater.inflate( mOrientation == DSVOrientation.VERTICAL ? R.layout.layout_segment_bitmap_v : R.layout.layout_segment_bitmap_h, null); return new SegmentBitmapViewHolder(view); } public void setOrientation(DSVOrientation orientation) { mOrientation = orientation; notifyDataSetChanged(); } }
java
Apache-2.0
e32c0bbcf77183ff2ee407b4f179a094f6fdb12a
2026-01-05T02:37:31.908377Z
false
dailystudio/ml
https://github.com/dailystudio/ml/blob/e32c0bbcf77183ff2ee407b4f179a094f6fdb12a/deeplab/app/src/main/java/com/dailystudio/deeplab/ImageDimenEvent.java
deeplab/app/src/main/java/com/dailystudio/deeplab/ImageDimenEvent.java
package com.dailystudio.deeplab; import android.net.Uri; public class ImageDimenEvent { public Uri imageUri; public int width; public int height; public ImageDimenEvent(Uri uri, int w, int h) { imageUri = uri; width = w; height = h; } @Override public String toString() { return String.format("image dimen: %s, [%d x %d]", imageUri, width, height); } }
java
Apache-2.0
e32c0bbcf77183ff2ee407b4f179a094f6fdb12a
2026-01-05T02:37:31.908377Z
false
dailystudio/ml
https://github.com/dailystudio/ml/blob/e32c0bbcf77183ff2ee407b4f179a094f6fdb12a/deeplab/app/src/main/java/com/dailystudio/deeplab/SegmentBitmapsLoader.java
deeplab/app/src/main/java/com/dailystudio/deeplab/SegmentBitmapsLoader.java
package com.dailystudio.deeplab; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.net.Uri; import android.support.annotation.Nullable; import android.text.TextUtils; import com.dailystudio.app.loader.AbsAsyncDataLoader; import com.dailystudio.app.utils.BitmapUtils; import com.dailystudio.deeplab.ml.DeeplabInterface; import com.dailystudio.deeplab.ml.DeeplabModel; import com.dailystudio.deeplab.ml.ImageUtils; import com.dailystudio.deeplab.utils.FilePickUtils; import com.dailystudio.development.Logger; import org.greenrobot.eventbus.EventBus; import java.util.ArrayList; import java.util.List; public class SegmentBitmapsLoader extends AbsAsyncDataLoader<List<SegmentBitmap>> { private Uri mImageUri; public SegmentBitmapsLoader(Context context, Uri imageUri) { super(context); mImageUri = imageUri; } @Nullable @Override public List<SegmentBitmap> loadInBackground() { final Context context = getContext(); if (context == null) { return null; } final Resources res = context.getResources(); if (res == null) { return null; } if (mImageUri == null) { return null; } DeeplabInterface deeplabInterface = DeeplabModel.getInstance(); final String filePath = FilePickUtils.getPath(context, mImageUri); Logger.debug("file to mask: %s", filePath); if (TextUtils.isEmpty(filePath)) { return null; } boolean vertical = checkAndReportDimen(filePath); final int dw = res.getDimensionPixelSize( vertical ? R.dimen.image_width_v : R.dimen.image_width_h); final int dh = res.getDimensionPixelSize( vertical ? R.dimen.image_height_v : R.dimen.image_height_h); Logger.debug("display image dimen: [%d x %d]", dw, dh); Bitmap bitmap = decodeBitmapFromFile(filePath, dw, dh); if (bitmap == null) { return null; } List<SegmentBitmap> bitmaps = new ArrayList<>(); bitmaps.add(new SegmentBitmap(R.string.label_original, bitmap)); final int w = bitmap.getWidth(); final int h = bitmap.getHeight(); Logger.debug("decoded file dimen: [%d x %d]", w, h); EventBus.getDefault().post(new ImageDimenEvent(mImageUri, w, h)); float resizeRatio = (float) deeplabInterface.getInputSize() / Math.max(bitmap.getWidth(), bitmap.getHeight()); int rw = Math.round(w * resizeRatio); int rh = Math.round(h * resizeRatio); Logger.debug("resize bitmap: ratio = %f, [%d x %d] -> [%d x %d]", resizeRatio, w, h, rw, rh); Bitmap resized = ImageUtils.tfResizeBilinear(bitmap, rw, rh); Bitmap mask = deeplabInterface.segment(resized); if (mask != null) { mask = BitmapUtils.createClippedBitmap(mask, (mask.getWidth() - rw) / 2, (mask.getHeight() - rh) / 2, rw, rh); mask = BitmapUtils.scaleBitmap(mask, w, h); bitmaps.add(new SegmentBitmap(R.string.label_mask, mask)); final Bitmap cropped = cropBitmapWithMask(bitmap, mask); bitmaps.add(new SegmentBitmap(R.string.label_cropped, cropped)); } else { bitmaps.add(new SegmentBitmap(R.string.label_mask, (Bitmap)null)); bitmaps.add(new SegmentBitmap(R.string.label_cropped, (Bitmap)null)); } return bitmaps; } private boolean checkAndReportDimen(String filePath) { if (TextUtils.isEmpty(filePath)) { return false; } // First decode with inJustDecodeBounds=true to check dimensions final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(filePath, options); final int width = options.outWidth; final int height = options.outHeight; Logger.debug("original image dimen: %d x %d", width, height); EventBus.getDefault().post(new ImageDimenEvent(mImageUri, width, height)); return (height > width); } private Bitmap cropBitmapWithMask(Bitmap original, Bitmap mask) { if (original == null || mask == null) { return null; } final int w = original.getWidth(); final int h = original.getHeight(); if (w <= 0 || h <= 0) { return null; } Bitmap cropped = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(cropped); Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN)); canvas.drawBitmap(original, 0, 0, null); canvas.drawBitmap(mask, 0, 0, paint); paint.setXfermode(null); return cropped; } public static Bitmap decodeBitmapFromFile(String filePath, int reqWidth, int reqHeight) { if (TextUtils.isEmpty(filePath)) { return null; } // First decode with inJustDecodeBounds=true to check dimensions final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(filePath, options); // Calculate inSampleSize options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; return BitmapFactory.decodeFile(filePath, options); } public static int calculateInSampleSize( BitmapFactory.Options options, int reqWidth, int reqHeight) { // Raw height and width of image final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { final int halfHeight = height / 2; final int halfWidth = width / 2; // Calculate the largest inSampleSize value that is a power of 2 and keeps both // height and width larger than the requested height and width. while ((halfHeight / inSampleSize) >= reqHeight && (halfWidth / inSampleSize) >= reqWidth) { inSampleSize *= 2; } } return inSampleSize; } }
java
Apache-2.0
e32c0bbcf77183ff2ee407b4f179a094f6fdb12a
2026-01-05T02:37:31.908377Z
false
dailystudio/ml
https://github.com/dailystudio/ml/blob/e32c0bbcf77183ff2ee407b4f179a094f6fdb12a/deeplab/app/src/main/java/com/dailystudio/deeplab/SegmentBitmapViewHolder.java
deeplab/app/src/main/java/com/dailystudio/deeplab/SegmentBitmapViewHolder.java
package com.dailystudio.deeplab; import android.content.Context; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.dailystudio.app.ui.AbsArrayItemViewHolder; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; public class SegmentBitmapViewHolder extends AbsArrayItemViewHolder<SegmentBitmap> { private final static DisplayImageOptions DEFAULT_IMAGE_LOADER_OPTIONS = new DisplayImageOptions.Builder() .cacheInMemory(true) .cacheOnDisk(true) .showImageOnLoading(null) .resetViewBeforeLoading(true) .build(); private ImageView mImageView; private TextView mLabelView; public SegmentBitmapViewHolder(View itemView) { super(itemView); setupViews(itemView); } private void setupViews(View itemView) { if (itemView == null) { return; } mImageView = itemView.findViewById(R.id.image); mLabelView = itemView.findViewById(R.id.label); } @Override public void bindItem(final Context context, SegmentBitmap segmentBitmap) { if (mImageView != null) { if (segmentBitmap.bitmapUri != null) { ImageLoader.getInstance().displayImage( segmentBitmap.bitmapUri.toString(), mImageView, DEFAULT_IMAGE_LOADER_OPTIONS); } else { mImageView.setImageBitmap(segmentBitmap.bitmap); } } if (mLabelView != null) { mLabelView.setText(segmentBitmap.labelResId); } } }
java
Apache-2.0
e32c0bbcf77183ff2ee407b4f179a094f6fdb12a
2026-01-05T02:37:31.908377Z
false
dailystudio/ml
https://github.com/dailystudio/ml/blob/e32c0bbcf77183ff2ee407b4f179a094f6fdb12a/deeplab/app/src/main/java/com/dailystudio/deeplab/ml/DeepLabLite.java
deeplab/app/src/main/java/com/dailystudio/deeplab/ml/DeepLabLite.java
package com.dailystudio.deeplab.ml; import android.content.Context; import android.content.res.AssetFileDescriptor; import android.graphics.Bitmap; import android.graphics.Color; import android.text.TextUtils; import com.dailystudio.app.utils.ArrayUtils; import com.dailystudio.app.utils.BitmapUtils; import com.dailystudio.development.Logger; import org.tensorflow.lite.Interpreter; import org.tensorflow.lite.Tensor; import org.tensorflow.lite.experimental.GpuDelegate; import java.io.FileInputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.util.Arrays; import java.util.Random; public class DeepLabLite implements DeeplabInterface { private final static String MODEL_PATH = "deeplabv3_257_mv_gpu.tflite"; private final static boolean USE_GPU = false; private static final float IMAGE_MEAN = 128.0f; private static final float IMAGE_STD = 128.0f; private final static int INPUT_SIZE = 257; private final static int NUM_CLASSES = 21; private final static int COLOR_CHANNELS = 3; private final static int BYTES_PER_POINT = 4; MappedByteBuffer mModelBuffer; private ByteBuffer mImageData; private ByteBuffer mOutputs; private int[][] mSegmentBits; private int[] mSegmentColors; private final static Random RANDOM = new Random(System.currentTimeMillis()); @Override public boolean initialize(Context context) { if (context == null) { return false; } mModelBuffer = loadModelFile(context, MODEL_PATH); if (mModelBuffer == null) { return false; } mImageData = ByteBuffer.allocateDirect( 1 * INPUT_SIZE * INPUT_SIZE * COLOR_CHANNELS * BYTES_PER_POINT); mImageData.order(ByteOrder.nativeOrder()); mOutputs = ByteBuffer.allocateDirect(1 * INPUT_SIZE * INPUT_SIZE * NUM_CLASSES * BYTES_PER_POINT); mOutputs.order(ByteOrder.nativeOrder()); mSegmentBits = new int[INPUT_SIZE][INPUT_SIZE]; mSegmentColors = new int[NUM_CLASSES]; for (int i = 0; i < NUM_CLASSES; i++) { if (i == 0) { mSegmentColors[i] = Color.TRANSPARENT; } else { mSegmentColors[i] = Color.rgb( (int)(255 * RANDOM.nextFloat()), (int)(255 * RANDOM.nextFloat()), (int)(255 * RANDOM.nextFloat())); } } return (mModelBuffer != null); } @Override public boolean isInitialized() { return (mModelBuffer != null); } @Override public int getInputSize() { return INPUT_SIZE; } @Override public Bitmap segment(Bitmap bitmap) { if (mModelBuffer == null) { Logger.warn("tf model is NOT initialized."); return null; } if (bitmap == null) { return null; } int w = bitmap.getWidth(); int h = bitmap.getHeight(); Logger.debug("bitmap: %d x %d,", w, h); if (w > INPUT_SIZE || h > INPUT_SIZE) { Logger.warn("invalid bitmap size: %d x %d [should be: %d x %d]", w, h, INPUT_SIZE, INPUT_SIZE); return null; } if (w < INPUT_SIZE || h < INPUT_SIZE) { bitmap = BitmapUtils.extendBitmap( bitmap, INPUT_SIZE, INPUT_SIZE, Color.BLACK); w = bitmap.getWidth(); h = bitmap.getHeight(); Logger.debug("extend bitmap: %d x %d,", w, h); } mImageData.rewind(); mOutputs.rewind(); int[] mIntValues = new int[w * h]; bitmap.getPixels(mIntValues, 0, w, 0, 0, w, h); int pixel = 0; for (int i = 0; i < INPUT_SIZE; ++i) { for (int j = 0; j < INPUT_SIZE; ++j) { if (pixel >= mIntValues.length) { break; } final int val = mIntValues[pixel++]; mImageData.putFloat((((val >> 16) & 0xFF) - IMAGE_MEAN) / IMAGE_STD); mImageData.putFloat((((val >> 8) & 0xFF) - IMAGE_MEAN) / IMAGE_STD); mImageData.putFloat(((val & 0xFF) - IMAGE_MEAN) / IMAGE_STD); } } Interpreter.Options options = new Interpreter.Options(); if (USE_GPU) { GpuDelegate delegate = new GpuDelegate(); options.addDelegate(delegate); } Interpreter interpreter = new Interpreter(mModelBuffer, options); debugInputs(interpreter); debugOutputs(interpreter); final long start = System.currentTimeMillis(); Logger.debug("inference starts %d", start); interpreter.run(mImageData, mOutputs); final long end = System.currentTimeMillis(); Logger.debug("inference finishes at %d", end); Logger.debug("%d millis per core segment call.", (end - start)); Bitmap maskBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); fillZeroes(mSegmentBits); float maxVal = 0; float val = 0; for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { mSegmentBits[x][y] = 0; for (int c = 0; c < NUM_CLASSES; c++) { val = mOutputs.getFloat((y * w * NUM_CLASSES + x * NUM_CLASSES + c) * BYTES_PER_POINT); if (c == 0 || val > maxVal) { maxVal = val; mSegmentBits[x][y] = c; } } maskBitmap.setPixel(x, y, mSegmentColors[mSegmentBits[x][y]]); } } return maskBitmap; } private void fillZeroes(int[][] array) { if (array == null) { return; } int r; for (r = 0; r < array.length; r++) { Arrays.fill(array[r], 0); } } private static void debugInputs(Interpreter interpreter) { if (interpreter == null) { return; } final int numOfInputs = interpreter.getInputTensorCount(); Logger.debug("[TF-LITE-MODEL] input tensors: [%d]",numOfInputs); for (int i = 0; i < numOfInputs; i++) { Tensor t = interpreter.getInputTensor(i); Logger.debug("[TF-LITE-MODEL] input tensor[%d[: shape[%s]", i, ArrayUtils.intArrayToString(t.shape())); } } private static void debugOutputs(Interpreter interpreter) { if (interpreter == null) { return; } final int numOfOutputs = interpreter.getOutputTensorCount(); Logger.debug("[TF-LITE-MODEL] output tensors: [%d]",numOfOutputs); for (int i = 0; i < numOfOutputs; i++) { Tensor t = interpreter.getOutputTensor(i); Logger.debug("[TF-LITE-MODEL] output tensor[%d[: shape[%s]", i, ArrayUtils.intArrayToString(t.shape())); } } private static MappedByteBuffer loadModelFile(Context context, String modelFile) { if (context == null || TextUtils.isEmpty(modelFile)) { return null; } MappedByteBuffer buffer = null; try { AssetFileDescriptor df = context.getAssets().openFd(modelFile); FileInputStream inputStream = new FileInputStream(df.getFileDescriptor()); FileChannel fileChannel = inputStream.getChannel(); long startOffset = df.getStartOffset(); long declaredLength = df.getDeclaredLength(); buffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, startOffset, declaredLength); } catch (IOException e) { Logger.debug("load tflite model from [%s] failed: %s", modelFile, e.toString()); buffer = null; } return buffer; } }
java
Apache-2.0
e32c0bbcf77183ff2ee407b4f179a094f6fdb12a
2026-01-05T02:37:31.908377Z
false
dailystudio/ml
https://github.com/dailystudio/ml/blob/e32c0bbcf77183ff2ee407b4f179a094f6fdb12a/deeplab/app/src/main/java/com/dailystudio/deeplab/ml/DeeplabInterface.java
deeplab/app/src/main/java/com/dailystudio/deeplab/ml/DeeplabInterface.java
package com.dailystudio.deeplab.ml; import android.content.Context; import android.graphics.Bitmap; public interface DeeplabInterface { boolean initialize(Context context); boolean isInitialized(); int getInputSize(); Bitmap segment(Bitmap bitmap); }
java
Apache-2.0
e32c0bbcf77183ff2ee407b4f179a094f6fdb12a
2026-01-05T02:37:31.908377Z
false
dailystudio/ml
https://github.com/dailystudio/ml/blob/e32c0bbcf77183ff2ee407b4f179a094f6fdb12a/deeplab/app/src/main/java/com/dailystudio/deeplab/ml/ImageUtils.java
deeplab/app/src/main/java/com/dailystudio/deeplab/ml/ImageUtils.java
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ package com.dailystudio.deeplab.ml; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Rect; /** * Utility class for manipulating images. **/ public class ImageUtils { public static Bitmap tfResizeBilinear(Bitmap bitmap, int w, int h) { if (bitmap == null) { return null; } Bitmap resized = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); final Canvas canvas = new Canvas(resized); canvas.drawBitmap(bitmap, new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()), new Rect(0, 0, w, h), null); return resized; } }
java
Apache-2.0
e32c0bbcf77183ff2ee407b4f179a094f6fdb12a
2026-01-05T02:37:31.908377Z
false
dailystudio/ml
https://github.com/dailystudio/ml/blob/e32c0bbcf77183ff2ee407b4f179a094f6fdb12a/deeplab/app/src/main/java/com/dailystudio/deeplab/ml/DeeplabModel.java
deeplab/app/src/main/java/com/dailystudio/deeplab/ml/DeeplabModel.java
package com.dailystudio.deeplab.ml; public class DeeplabModel { private final static Boolean USE_TF_LITE = true; private static DeeplabInterface sInterface = null; public synchronized static DeeplabInterface getInstance() { if (sInterface != null) { return sInterface; } if (USE_TF_LITE) { sInterface = new DeepLabLite(); } else { sInterface = new DeeplabMobile(); } return sInterface; } }
java
Apache-2.0
e32c0bbcf77183ff2ee407b4f179a094f6fdb12a
2026-01-05T02:37:31.908377Z
false
dailystudio/ml
https://github.com/dailystudio/ml/blob/e32c0bbcf77183ff2ee407b4f179a094f6fdb12a/deeplab/app/src/main/java/com/dailystudio/deeplab/ml/DeeplabMobile.java
deeplab/app/src/main/java/com/dailystudio/deeplab/ml/DeeplabMobile.java
package com.dailystudio.deeplab.ml; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Color; import android.text.TextUtils; import com.dailystudio.app.utils.ArrayUtils; import com.dailystudio.development.Logger; import org.tensorflow.Graph; import org.tensorflow.Operation; import org.tensorflow.Output; import org.tensorflow.contrib.android.TensorFlowInferenceInterface; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Iterator; public class DeeplabMobile implements DeeplabInterface { private final static String MODEL_FILE = "/sdcard/deeplab/frozen_inference_graph.pb"; private final static String INPUT_NAME = "ImageTensor"; private final static String OUTPUT_NAME = "SemanticPredictions"; public final static int INPUT_SIZE = 513; private volatile TensorFlowInferenceInterface sTFInterface = null; @Override public boolean initialize(Context context) { final File graphPath = new File(MODEL_FILE); FileInputStream graphStream; try { graphStream = new FileInputStream(graphPath); } catch (FileNotFoundException e) { Logger.error("create input stream from[%s] failed: %s", graphPath.getAbsoluteFile(), e.toString()); graphStream = null; } if (graphStream == null) { return false; } sTFInterface = new TensorFlowInferenceInterface(graphStream); if (sTFInterface == null) { Logger.warn("initialize Tensorflow model[%s] failed.", MODEL_FILE); return false; } // printGraph(sTFInterface.graph()); // printOp(sTFInterface.graph(), "ImageTensor"); if (graphStream != null) { try { graphStream.close(); } catch (IOException e) { } } return true; } @Override public boolean isInitialized() { return (sTFInterface != null); } @Override public int getInputSize() { return INPUT_SIZE; } @Override public Bitmap segment(final Bitmap bitmap) { if (sTFInterface == null) { Logger.warn("tf model is NOT initialized."); return null; } if (bitmap == null) { return null; } final int w = bitmap.getWidth(); final int h = bitmap.getHeight(); Logger.debug("bitmap: %d x %d,", w, h); if (w > INPUT_SIZE || h > INPUT_SIZE) { Logger.warn("invalid bitmap size: %d x %d [should be: %d x %d]", w, h, INPUT_SIZE, INPUT_SIZE); return null; } int[] mIntValues = new int[w * h]; byte[] mFlatIntValues = new byte[w * h * 3]; int[] mOutputs = new int[w * h]; bitmap.getPixels(mIntValues, 0, w, 0, 0, w, h); for (int i = 0; i < mIntValues.length; ++i) { final int val = mIntValues[i]; mFlatIntValues[i * 3 + 0] = (byte)((val >> 16) & 0xFF); mFlatIntValues[i * 3 + 1] = (byte)((val >> 8) & 0xFF); mFlatIntValues[i * 3 + 2] = (byte)(val & 0xFF); } final long start = System.currentTimeMillis(); sTFInterface.feed(INPUT_NAME, mFlatIntValues, 1, h, w, 3 ); sTFInterface.run(new String[] { OUTPUT_NAME }, true); sTFInterface.fetch(OUTPUT_NAME, mOutputs); final long end = System.currentTimeMillis(); Logger.debug("%d millis per core segment call.", (end - start)); // Logger.debug("outputs = %s", ArrayUtils.intArrayToString(mOutputs)); Bitmap output = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { output.setPixel(x, y, mOutputs[y * w + x] == 0 ? Color.TRANSPARENT : Color.BLACK); } } return output; } public static void printOp(Graph graph, String opName) { if (graph == null || TextUtils.isEmpty(opName)) { return; } Operation op = graph.operation(opName); Logger.debug("op[%s]: %s", opName, op); } public static void printGraph(Graph graph) { if (graph == null) { return; } Iterator<Operation> operations = graph.operations(); if (operations == null) { return; } Operation op; Output<?> output; int num; while (operations.hasNext()) { op = operations.next(); Logger.debug("op: [%s]", op); num = op.numOutputs(); for (int i = 0; i < num; i++) { output = op.output(i); Logger.debug("%s- [%d]: %s", (i == num - 1) ? "`" : "|", i, output); } } } }
java
Apache-2.0
e32c0bbcf77183ff2ee407b4f179a094f6fdb12a
2026-01-05T02:37:31.908377Z
false
dailystudio/ml
https://github.com/dailystudio/ml/blob/e32c0bbcf77183ff2ee407b4f179a094f6fdb12a/deeplab/app/src/main/java/com/dailystudio/deeplab/utils/FilePickUtils.java
deeplab/app/src/main/java/com/dailystudio/deeplab/utils/FilePickUtils.java
package com.dailystudio.deeplab.utils; import android.annotation.SuppressLint; import android.content.ContentUris; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.provider.DocumentsContract; import android.provider.MediaStore; public class FilePickUtils { private static String getPathDeprecated(Context ctx, Uri uri) { if( uri == null ) { return null; } String[] projection = { MediaStore.Images.Media.DATA }; Cursor cursor = ctx.getContentResolver().query(uri, projection, null, null, null); if( cursor != null ){ int column_index = cursor .getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); return cursor.getString(column_index); } return uri.getPath(); } public static String getSmartFilePath(Context ctx, Uri uri){ if (Build.VERSION.SDK_INT < 19) { return getPathDeprecated(ctx, uri); } return FilePickUtils.getPath(ctx, uri); } @SuppressLint("NewApi") public static String getPath(final Context context, final Uri uri) { final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT; // DocumentProvider if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) { // ExternalStorageProvider if (isExternalStorageDocument(uri)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; if ("primary".equalsIgnoreCase(type)) { return Environment.getExternalStorageDirectory() + "/" + split[1]; } // TODO handle non-primary volumes } // DownloadsProvider else if (isDownloadsDocument(uri)) { final String id = DocumentsContract.getDocumentId(uri); final Uri contentUri = ContentUris.withAppendedId( Uri.parse("content://downloads/public_downloads"), Long.valueOf(id)); return getDataColumn(context, contentUri, null, null); } // MediaProvider else if (isMediaDocument(uri)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; Uri contentUri = null; if ("image".equals(type)) { contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; } else if ("video".equals(type)) { contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; } else if ("audio".equals(type)) { contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; } final String selection = "_id=?"; final String[] selectionArgs = new String[] { split[1] }; return getDataColumn(context, contentUri, selection, selectionArgs); } } // MediaStore (and general) else if ("content".equalsIgnoreCase(uri.getScheme())) { return getDataColumn(context, uri, null, null); } // File else if ("file".equalsIgnoreCase(uri.getScheme())) { return uri.getPath(); } return null; } /** * Get the value of the data column for this Uri. This is useful for * MediaStore Uris, and other file-based ContentProviders. * * @param context The context. * @param uri The Uri to query. * @param selection (Optional) Filter used in the query. * @param selectionArgs (Optional) Selection arguments used in the query. * @return The value of the _data column, which is typically a file path. */ public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) { Cursor cursor = null; final String column = "_data"; final String[] projection = { column }; try { cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null); if (cursor != null && cursor.moveToFirst()) { final int column_index = cursor.getColumnIndexOrThrow(column); return cursor.getString(column_index); } } finally { if (cursor != null) cursor.close(); } return null; } /** * @param uri The Uri to check. * @return Whether the Uri authority is ExternalStorageProvider. */ public static boolean isExternalStorageDocument(Uri uri) { return "com.android.externalstorage.documents".equals(uri.getAuthority()); } /** * @param uri The Uri to check. * @return Whether the Uri authority is DownloadsProvider. */ public static boolean isDownloadsDocument(Uri uri) { return "com.android.providers.downloads.documents".equals(uri.getAuthority()); } /** * @param uri The Uri to check. * @return Whether the Uri authority is MediaProvider. */ public static boolean isMediaDocument(Uri uri) { return "com.android.providers.media.documents".equals(uri.getAuthority()); } }
java
Apache-2.0
e32c0bbcf77183ff2ee407b4f179a094f6fdb12a
2026-01-05T02:37:31.908377Z
false
dailystudio/ml
https://github.com/dailystudio/ml/blob/e32c0bbcf77183ff2ee407b4f179a094f6fdb12a/deeplab/app/src/androidTest/java/com/dailystudio/deeplab/ExampleInstrumentedTest.java
deeplab/app/src/androidTest/java/com/dailystudio/deeplab/ExampleInstrumentedTest.java
package com.dailystudio.deeplab; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.dailystudio.deeplab", appContext.getPackageName()); } }
java
Apache-2.0
e32c0bbcf77183ff2ee407b4f179a094f6fdb12a
2026-01-05T02:37:31.908377Z
false
dailystudio/ml
https://github.com/dailystudio/ml/blob/e32c0bbcf77183ff2ee407b4f179a094f6fdb12a/object_detection/app/src/test/java/com/dailystudio/objectdetection/ExampleUnitTest.java
object_detection/app/src/test/java/com/dailystudio/objectdetection/ExampleUnitTest.java
package com.dailystudio.objectdetection; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() { assertEquals(4, 2 + 2); } }
java
Apache-2.0
e32c0bbcf77183ff2ee407b4f179a094f6fdb12a
2026-01-05T02:37:31.908377Z
false
dailystudio/ml
https://github.com/dailystudio/ml/blob/e32c0bbcf77183ff2ee407b4f179a094f6fdb12a/object_detection/app/src/main/java/com/dailystudio/objectdetection/MainActivity.java
object_detection/app/src/main/java/com/dailystudio/objectdetection/MainActivity.java
package com.dailystudio.objectdetection; import android.Manifest; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.res.ColorStateList; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.ActivityCompat; import android.support.v4.app.Fragment; import android.support.v4.content.ContextCompat; import android.text.TextUtils; import android.view.View; import android.widget.ImageView; import com.dailystudio.app.activity.ActionBarFragmentActivity; import com.dailystudio.app.utils.ActivityLauncher; import com.dailystudio.app.utils.ArrayUtils; import com.dailystudio.development.Logger; import com.dailystudio.objectdetection.api.ObjectDetectionModel; import com.dailystudio.objectdetection.database.DetectedImage; import com.dailystudio.objectdetection.fragment.DetectedImagesFragment; import com.dailystudio.objectdetection.ui.ImageDetectionEvent; import com.dailystudio.objectdetection.ui.ImageSelectedEvent; import com.dailystudio.objectdetection.utils.FilePickUtils; import com.nostra13.universalimageloader.core.ImageLoader; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; public class MainActivity extends ActionBarFragmentActivity { private final static int REQUEST_REQUIRED_PERMISSION = 0x01; private final static int REQUEST_PICK_IMAGE = 0x02; private class InitializeModelAsyncTask extends AsyncTask<Context, Void, Boolean> { @Override protected Boolean doInBackground(Context... contexts) { if (contexts == null || contexts.length <= 0) { return false; } final Context context = contexts[0]; final long start = System.currentTimeMillis(); final boolean ret = ObjectDetectionModel.initialize(context); final long end = System.currentTimeMillis(); Logger.debug("Initializing Object-Detection model is %s in %dms", ret ? "succeed" : "failed", (end - start)); return ret; } } private FloatingActionButton mFabPickImage; private ImageView mSelectedImagePreview; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setupViews(); } private void setupViews() { mSelectedImagePreview = findViewById(R.id.selected_preview); mFabPickImage = findViewById(R.id.fab_pick_image); if (mFabPickImage != null) { mFabPickImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent; if (Build.VERSION.SDK_INT >= 19) { intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, false); intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION); } else { intent = new Intent(Intent.ACTION_GET_CONTENT); } intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.setType("image/*"); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); ActivityLauncher.launchActivityForResult(MainActivity.this, Intent.createChooser(intent, getString(R.string.app_name)), REQUEST_PICK_IMAGE); } }); } } @Override protected void onStart() { super.onStart(); if (!EventBus.getDefault().isRegistered(this)) { EventBus.getDefault().register(this); } syncUIWithPermissions(true); } @Override protected void onDestroy() { super.onDestroy(); if (EventBus.getDefault().isRegistered(this)) { EventBus.getDefault().unregister(this); } } private void syncUIWithPermissions(boolean requestIfNeed) { final boolean granted = checkRequiredPermissions(requestIfNeed); setPickImageEnabled(granted); if (granted && !ObjectDetectionModel.isInitialized()) { initModel(); } } private boolean checkRequiredPermissions() { return checkRequiredPermissions(false); } private boolean checkRequiredPermissions(boolean requestIfNeed) { final boolean writeStoragePermGranted = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED; Logger.debug("storage permission granted: %s", writeStoragePermGranted); if (!writeStoragePermGranted && requestIfNeed) { requestRequiredPermissions(); } return writeStoragePermGranted; } private void requestRequiredPermissions() { ActivityCompat.requestPermissions(this, new String[]{ Manifest.permission.WRITE_EXTERNAL_STORAGE, }, REQUEST_REQUIRED_PERMISSION); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { Logger.debug("requestCode = 0x%02x, permission = [%s], grant = [%s]", requestCode, ArrayUtils.stringArrayToString(permissions, ","), ArrayUtils.intArrayToString(grantResults)); if (requestCode == REQUEST_REQUIRED_PERMISSION) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Logger.debug("permission granted, initialize model."); initModel(); if (mFabPickImage != null) { mFabPickImage.setEnabled(true); mFabPickImage.setBackgroundTintList( ColorStateList.valueOf(getColor(R.color.colorAccent))); } } else { Logger.debug("permission denied, disable fab."); } } else { super.onRequestPermissionsResult(requestCode, permissions, grantResults); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { Logger.debug("requestCode = %d, resultCode = %d, data = %s", requestCode, resultCode, data); if (requestCode == REQUEST_PICK_IMAGE && resultCode == RESULT_OK) { Uri pickedImageUri = data.getData(); Logger.debug("picked: %s", pickedImageUri); if (pickedImageUri != null) { if(Build.VERSION.SDK_INT >= 19){ final int takeFlags = data.getFlags() & Intent.FLAG_GRANT_READ_URI_PERMISSION; getContentResolver() .takePersistableUriPermission(pickedImageUri, takeFlags); } analyzeImage(pickedImageUri); } } else { super.onActivityResult(requestCode, resultCode, data); } } private void analyzeImage(Uri pickedImageUri) { final String filePath = FilePickUtils.getPath(this, pickedImageUri); Logger.debug("file to detect: %s", filePath); if (TextUtils.isEmpty(filePath)) { return; } new DetectAsyncTask(filePath).execute(getApplicationContext()); } private void initModel() { new InitializeModelAsyncTask().execute(this); } private void setPickImageEnabled(boolean enabled) { if (mFabPickImage != null) { mFabPickImage.setEnabled(enabled); int resId = enabled ? R.color.colorAccent : R.color.light_gray; mFabPickImage.setBackgroundTintList( ColorStateList.valueOf(getColor(resId))); } } @Subscribe(threadMode = ThreadMode.MAIN) public void onImageSelectedEvent(ImageSelectedEvent event) { Fragment fragment = findFragment(R.id.fragment_detected_images); if (fragment instanceof DetectedImagesFragment == false) { return; } DetectedImage styledImage = ((DetectedImagesFragment)fragment).getImageOnPosition( event.selectedPosition); Logger.debug("selected image: %s", styledImage); if (mSelectedImagePreview != null && styledImage != null) { ImageLoader.getInstance().displayImage( "file://" + styledImage.getDetectedPath(), mSelectedImagePreview, Constants.PREVIEW_IMAGE_LOADER_OPTIONS); } } @Subscribe(threadMode = ThreadMode.MAIN) public void onImageDetectionEvent(ImageDetectionEvent event) { Logger.debug("new detection state: %s", event.state); switch (event.state) { case DECODING: showPrompt(getString(R.string.prompt_decoding)); break; case DETECTING: showPrompt(getString(R.string.prompt_detecting)); break; case TAGGING: showPrompt(getString(R.string.prompt_tagging)); break; case DONE: hidePrompt(); break; } } }
java
Apache-2.0
e32c0bbcf77183ff2ee407b4f179a094f6fdb12a
2026-01-05T02:37:31.908377Z
false
dailystudio/ml
https://github.com/dailystudio/ml/blob/e32c0bbcf77183ff2ee407b4f179a094f6fdb12a/object_detection/app/src/main/java/com/dailystudio/objectdetection/ViewDetectedImageActivity.java
object_detection/app/src/main/java/com/dailystudio/objectdetection/ViewDetectedImageActivity.java
package com.dailystudio.objectdetection; import android.os.Bundle; import com.dailystudio.app.activity.ActionBarFragmentActivity; /** * Created by nanye on 18/3/6. */ public class ViewDetectedImageActivity extends ActionBarFragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_view_detected_image); setupViews(); } private void setupViews() { } }
java
Apache-2.0
e32c0bbcf77183ff2ee407b4f179a094f6fdb12a
2026-01-05T02:37:31.908377Z
false
dailystudio/ml
https://github.com/dailystudio/ml/blob/e32c0bbcf77183ff2ee407b4f179a094f6fdb12a/object_detection/app/src/main/java/com/dailystudio/objectdetection/Directories.java
object_detection/app/src/main/java/com/dailystudio/objectdetection/Directories.java
package com.dailystudio.objectdetection; import android.content.Context; import android.text.TextUtils; import com.dailystudio.GlobalContextWrapper; import com.dailystudio.app.utils.FileUtils; import java.io.File; public class Directories { private final static String DIRECTORY_NULL = ""; private final static String DETECTED = "detected"; public static String getRootDir() { final Context context = GlobalContextWrapper.getContext(); if (context == null) { return null; } File rootDir = context.getExternalFilesDir(DIRECTORY_NULL); if (rootDir == null) { return null; } return rootDir.toString(); } public static String getDetectedDir() { String rootDir = getRootDir(); if (TextUtils.isEmpty(rootDir)) { return null; } File assetsDir = new File(rootDir, DETECTED); return assetsDir.toString(); } public static String getDetectedFilePath(String filename) { String detectedDir = getDetectedDir(); if (!FileUtils.isFileExisted(detectedDir)) { FileUtils.checkOrCreateNoMediaDirectory(detectedDir); } File downloadFile = new File(detectedDir, filename); return downloadFile.toString(); } }
java
Apache-2.0
e32c0bbcf77183ff2ee407b4f179a094f6fdb12a
2026-01-05T02:37:31.908377Z
false
dailystudio/ml
https://github.com/dailystudio/ml/blob/e32c0bbcf77183ff2ee407b4f179a094f6fdb12a/object_detection/app/src/main/java/com/dailystudio/objectdetection/DetectAsyncTask.java
object_detection/app/src/main/java/com/dailystudio/objectdetection/DetectAsyncTask.java
package com.dailystudio.objectdetection; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.RectF; import android.os.AsyncTask; import com.dailystudio.app.utils.BitmapUtils; import com.dailystudio.app.utils.TextUtils; import com.dailystudio.development.Logger; import com.dailystudio.objectdetection.api.Classifier; import com.dailystudio.objectdetection.api.ObjectDetectionModel; import com.dailystudio.objectdetection.database.DetectedImage; import com.dailystudio.objectdetection.database.DetectedImageDatabaseModel; import com.dailystudio.objectdetection.ui.ImageDetectionEvent; import org.greenrobot.eventbus.EventBus; import java.util.List; public class DetectAsyncTask extends AsyncTask<Context, Void, List<Classifier.Recognition>> { private final static int MAX_OUTPUT_SIZE = 1920; private final static int[] FRAME_COLORS = { R.color.md_red_400, R.color.md_orange_400, R.color.md_amber_400, R.color.md_green_400, R.color.md_teal_400, R.color.md_blue_400, R.color.md_purple_400, }; private String mFilePath; public DetectAsyncTask(String filePath) { mFilePath = filePath; } @Override protected List<Classifier.Recognition> doInBackground(Context... contexts) { if (contexts == null || contexts.length <= 0) { return null; } notifyDetectionState(ImageDetectionEvent.State.DECODING); final Context context = contexts[0]; final long start = System.currentTimeMillis(); Bitmap bitmap; try { bitmap = BitmapFactory.decodeFile(mFilePath); bitmap = BitmapUtils.scaleBitmapRatioLocked(bitmap, MAX_OUTPUT_SIZE, MAX_OUTPUT_SIZE); } catch (OutOfMemoryError e) { Logger.error("decode and crop image[%s] failed: %s", mFilePath, e.toString()); bitmap = null; } if (bitmap == null) { return null; } DetectedImage.Orientation orientation = DetectedImage.Orientation.LANDSCAPE; if (bitmap.getWidth() < bitmap.getHeight()) { orientation = DetectedImage.Orientation.PORTRAIT; } notifyDetectionState(ImageDetectionEvent.State.DETECTING); final long startOfAnalysis = System.currentTimeMillis(); List<Classifier.Recognition> results = ObjectDetectionModel.detectImage(bitmap, .2f); final long startOfTagging = System.currentTimeMillis(); final String outputPath = Directories.getDetectedFilePath(String.format("%d.jpg", startOfTagging)); notifyDetectionState(ImageDetectionEvent.State.TAGGING); final Bitmap tagBitmap = tagRecognitionOnBitmap(context, bitmap, results); if (tagBitmap != null) { BitmapUtils.saveBitmap(tagBitmap, outputPath); DetectedImageDatabaseModel.saveDetectedImage(context, mFilePath, outputPath, orientation); } final long end = System.currentTimeMillis(); final long duration = (end - start); final long durationOfTagging = end - startOfTagging; final long durationOfAnalysis = startOfTagging - startOfAnalysis; final long durationOfDecode = startOfAnalysis - start; Logger.debug("detection is accomplished in %sms [decode: %dms, detect: %dms, tag: %dms].", duration, durationOfDecode, durationOfAnalysis, durationOfTagging); return results; } private Bitmap tagRecognitionOnBitmap(Context context, Bitmap origBitmap, List<Classifier.Recognition> recognitions) { if (context == null || origBitmap == null || recognitions == null || recognitions.size() <= 0) { return origBitmap; } final Resources res = context.getResources(); if (res == null) { return origBitmap; } Bitmap taggedBitmap = origBitmap.copy(Bitmap.Config.ARGB_8888, true); final int width = taggedBitmap.getWidth(); final int height = taggedBitmap.getHeight(); final Canvas canvas = new Canvas(taggedBitmap); final int corner = res.getDimensionPixelSize(R.dimen.detect_info_round_corner); final int N = recognitions.size(); int colorIndex = 0; final Paint framePaint = new Paint(); framePaint.setStyle(Paint.Style.STROKE); framePaint.setStrokeWidth(10.0f); Classifier.Recognition r; for (int i = 0; i < N; i++) { r = recognitions.get(i); framePaint.setColor(res.getColor(FRAME_COLORS[colorIndex], context.getTheme())); final RectF location = r.getLocation(); canvas.drawRoundRect(location, corner, corner, framePaint); colorIndex++; if (colorIndex >= FRAME_COLORS.length) { break; } } final Paint textPaint = new Paint(); int legendFontSize = res.getDimensionPixelSize(R.dimen.detect_info_font_size); int legendIndSize = res.getDimensionPixelSize(R.dimen.detect_info_font_size); int legendFramePadding = res.getDimensionPixelSize(R.dimen.detect_info_padding); textPaint.setTextSize(legendFontSize); RectF legendIndFrame = new RectF(); final float legendTextWidth = width * .3f; final float legendHeight = legendIndSize * 1.2f; final float legendEnd = width * .95f; final float legendIndStart = legendEnd - legendTextWidth - legendIndSize * 1.2f; float legendBottom = height * .95f; float legendTop = legendBottom - colorIndex * legendHeight; framePaint.setStyle(Paint.Style.FILL_AND_STROKE); framePaint.setColor(res.getColor(R.color.semi_black, context.getTheme())); canvas.drawRoundRect(legendIndStart - legendFramePadding, legendTop - legendFramePadding, legendEnd + legendFramePadding, legendBottom + legendFramePadding, corner, corner, framePaint); float legendTextStart; float legendTextTop; float legendIndTop; colorIndex = 0; String legendText; for (int i = 0; i < N; i++) { r = recognitions.get(i); legendIndTop = legendTop + 0.1f * legendIndSize; legendTextStart = legendEnd - legendTextWidth; legendTextTop = legendIndTop + (legendIndSize - (textPaint.descent() + textPaint.ascent())) / 2; legendIndFrame.set(legendIndStart, legendIndTop, legendIndStart + legendIndSize, legendIndTop + legendIndSize); textPaint.setColor(res.getColor(FRAME_COLORS[colorIndex], context.getTheme())); legendText = String.format("%s (%3.1f%%)", TextUtils.capitalize(r.getTitle()), r.getConfidence() * 100); canvas.drawRoundRect(legendIndFrame, corner, corner, textPaint); canvas.drawText(legendText, legendTextStart, legendTextTop, textPaint); colorIndex++; if (colorIndex >= FRAME_COLORS.length) { break; } legendTop += legendHeight; } return taggedBitmap; } @Override protected void onPostExecute(List<Classifier.Recognition> recognitions) { super.onPostExecute(recognitions); notifyDetectionState(ImageDetectionEvent.State.DONE); Logger.debug("recognitions: %s", recognitions); } private void notifyDetectionState(ImageDetectionEvent.State state) { EventBus.getDefault().post(new ImageDetectionEvent(state)); } }
java
Apache-2.0
e32c0bbcf77183ff2ee407b4f179a094f6fdb12a
2026-01-05T02:37:31.908377Z
false
dailystudio/ml
https://github.com/dailystudio/ml/blob/e32c0bbcf77183ff2ee407b4f179a094f6fdb12a/object_detection/app/src/main/java/com/dailystudio/objectdetection/Constants.java
object_detection/app/src/main/java/com/dailystudio/objectdetection/Constants.java
package com.dailystudio.objectdetection; import android.content.Context; import com.nostra13.universalimageloader.core.DisplayImageOptions; public class Constants { private final static String FILE_PROVIDER_AUTHORITY_SUFFIX = ".fileprovider"; public final static String getFileProvideAuthority(Context context) { if (context == null) { return null; } StringBuilder builder = new StringBuilder(context.getPackageName()); builder.append(FILE_PROVIDER_AUTHORITY_SUFFIX); return builder.toString(); } public static final String EXTRA_SRC_PATH = "freestyles.intent.EXTRA_SRC_PATH"; public final static DisplayImageOptions DEFAULT_IMAGE_LOADER_OPTIONS = new DisplayImageOptions.Builder() .cacheInMemory(true) .cacheOnDisk(true) .showImageOnLoading(null) .resetViewBeforeLoading(true) .build(); public final static DisplayImageOptions PREVIEW_IMAGE_LOADER_OPTIONS = new DisplayImageOptions.Builder() .cacheInMemory(true) .cacheOnDisk(true) .build(); public final static DisplayImageOptions STYLE_THUMB_IMAGE_LOADER_OPTIONS = new DisplayImageOptions.Builder() .cacheInMemory(true) .cacheOnDisk(true) .showImageOnLoading(R.mipmap.ic_launcher) .build(); }
java
Apache-2.0
e32c0bbcf77183ff2ee407b4f179a094f6fdb12a
2026-01-05T02:37:31.908377Z
false
dailystudio/ml
https://github.com/dailystudio/ml/blob/e32c0bbcf77183ff2ee407b4f179a094f6fdb12a/object_detection/app/src/main/java/com/dailystudio/objectdetection/ObjectDetectionApplication.java
object_detection/app/src/main/java/com/dailystudio/objectdetection/ObjectDetectionApplication.java
package com.dailystudio.objectdetection; import com.dailystudio.app.DevBricksApplication; import com.facebook.stetho.Stetho; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; public class ObjectDetectionApplication extends DevBricksApplication { @Override public void onCreate() { super.onCreate(); if (BuildConfig.USE_STETHO) { Stetho.initializeWithDefaults(this); } ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this).build(); ImageLoader.getInstance().init(config); } @Override protected boolean isDebugBuild() { return BuildConfig.DEBUG; } }
java
Apache-2.0
e32c0bbcf77183ff2ee407b4f179a094f6fdb12a
2026-01-05T02:37:31.908377Z
false
dailystudio/ml
https://github.com/dailystudio/ml/blob/e32c0bbcf77183ff2ee407b4f179a094f6fdb12a/object_detection/app/src/main/java/com/dailystudio/objectdetection/ObjectDetectionDatabaseContentProvider.java
object_detection/app/src/main/java/com/dailystudio/objectdetection/ObjectDetectionDatabaseContentProvider.java
package com.dailystudio.objectdetection; import com.dailystudio.dataobject.database.DatabaseConnectivityProvider; /** * Created by nanye on 16/3/4. */ public class ObjectDetectionDatabaseContentProvider extends DatabaseConnectivityProvider { }
java
Apache-2.0
e32c0bbcf77183ff2ee407b4f179a094f6fdb12a
2026-01-05T02:37:31.908377Z
false
dailystudio/ml
https://github.com/dailystudio/ml/blob/e32c0bbcf77183ff2ee407b4f179a094f6fdb12a/object_detection/app/src/main/java/com/dailystudio/objectdetection/fragment/DetectedImagesFragment.java
object_detection/app/src/main/java/com/dailystudio/objectdetection/fragment/DetectedImagesFragment.java
package com.dailystudio.objectdetection.fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.content.Loader; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.dailystudio.app.fragment.AbsArrayRecyclerViewFragment; import com.dailystudio.app.ui.AbsArrayRecyclerAdapter; import com.dailystudio.development.Logger; import com.dailystudio.objectdetection.R; import com.dailystudio.objectdetection.database.DetectedImage; import com.dailystudio.objectdetection.loader.LoaderIds; import com.dailystudio.objectdetection.loader.StyledImagesLoader; import com.dailystudio.objectdetection.ui.DetectedImageViewHolder; import com.dailystudio.objectdetection.ui.DetectedImagesRecyclerAdapter; import com.dailystudio.objectdetection.ui.ImageSelectedEvent; import com.yarolegovich.discretescrollview.DiscreteScrollView; import com.yarolegovich.discretescrollview.transform.ScaleTransformer; import org.greenrobot.eventbus.EventBus; import java.util.List; /** * Created by nanye on 18/2/26. */ public class DetectedImagesFragment extends AbsArrayRecyclerViewFragment<DetectedImage, DetectedImageViewHolder> { private DiscreteScrollView mRecyclerView; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_detected_images, null); setupViews(view); return view; } private void setupViews(View fragmentView) { if (fragmentView == null) { return; } mRecyclerView = fragmentView.findViewById(android.R.id.list); if (mRecyclerView != null) { mRecyclerView.setSlideOnFling(true); mRecyclerView.setItemTransformer(new ScaleTransformer.Builder() .setMaxScale(1.0f) .setMinScale(0.8f) .build()); mRecyclerView.addOnItemChangedListener(new DiscreteScrollView.OnItemChangedListener<RecyclerView.ViewHolder>() { @Override public void onCurrentItemChanged(@Nullable RecyclerView.ViewHolder viewHolder, int adapterPosition) { Logger.debug("change to pos: %d", adapterPosition); EventBus.getDefault().post(new ImageSelectedEvent(adapterPosition)); } }); } } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setShowLoadingView(false); } @Override protected int getLoaderId() { return LoaderIds.LOADER_DETECTED_IMAGES; } @Override protected Bundle createLoaderArguments() { return new Bundle(); } @Override protected RecyclerView.Adapter onCreateAdapter() { return new DetectedImagesRecyclerAdapter(getContext()); } @Override protected RecyclerView.LayoutManager onCreateLayoutManager() { return null; } @Override protected RecyclerView.ItemDecoration onCreateItemDecoration() { return null; } @Override public Loader<List<DetectedImage>> onCreateLoader(int id, Bundle args) { return new StyledImagesLoader(getContext()); } public DetectedImage getImageOnPosition(int position) { RecyclerView.Adapter adapter = getAdapter(); if (adapter instanceof AbsArrayRecyclerAdapter == false) { return null; } AbsArrayRecyclerAdapter recyclerAdapter = (AbsArrayRecyclerAdapter)adapter; if (position < 0 || position >= adapter.getItemCount()) { return null; } return (DetectedImage) recyclerAdapter.getItem(position); } }
java
Apache-2.0
e32c0bbcf77183ff2ee407b4f179a094f6fdb12a
2026-01-05T02:37:31.908377Z
false
dailystudio/ml
https://github.com/dailystudio/ml/blob/e32c0bbcf77183ff2ee407b4f179a094f6fdb12a/object_detection/app/src/main/java/com/dailystudio/objectdetection/fragment/ViewDetectedImageFragment.java
object_detection/app/src/main/java/com/dailystudio/objectdetection/fragment/ViewDetectedImageFragment.java
package com.dailystudio.objectdetection.fragment; import android.app.Activity; import android.content.Intent; import android.content.pm.ActivityInfo; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.content.Loader; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.dailystudio.app.fragment.AbsLoaderFragment; import com.dailystudio.development.Logger; import com.dailystudio.objectdetection.Constants; import com.dailystudio.objectdetection.R; import com.dailystudio.objectdetection.database.DetectedImage; import com.dailystudio.objectdetection.loader.LoaderIds; import com.dailystudio.objectdetection.loader.ViewDetectedImageLoader; import com.nostra13.universalimageloader.core.ImageLoader; /** * Created by nanye on 18/2/26. */ public class ViewDetectedImageFragment extends AbsLoaderFragment<DetectedImage> { private String mSrcPath; private ImageView mImageView; private DetectedImage mCurrentImage = null; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_view_detected_image, null); setupViews(view); return view; } @Override public void bindIntent(Intent intent) { super.bindIntent(intent); if (intent == null) { return; } String srcPath = intent.getStringExtra(Constants.EXTRA_SRC_PATH); if (TextUtils.isEmpty(srcPath)) { Logger.warn("srcPath is missing."); return; } mSrcPath = srcPath; restartLoader(); } private void setupViews(View fragmentView) { if (fragmentView == null) { return; } mImageView = fragmentView.findViewById(R.id.detected_image); } @Override protected int getLoaderId() { return LoaderIds.LOADER_VIEW_IMAGE; } @Override protected Bundle createLoaderArguments() { return new Bundle(); } @Override public Loader<DetectedImage> onCreateLoader(int id, Bundle args) { return new ViewDetectedImageLoader(getContext(), mSrcPath); } @Override public void onLoadFinished(Loader<DetectedImage> loader, DetectedImage image) { super.onLoadFinished(loader, image); mCurrentImage = image; syncImageDisplay(); } private void syncImageDisplay() { if (mImageView != null && mCurrentImage != null) { final String imagePath = mCurrentImage.getDetectedPath(); ImageLoader.getInstance().displayImage( "file://" + imagePath, mImageView, Constants.DEFAULT_IMAGE_LOADER_OPTIONS); if (mCurrentImage.getOrientation() == DetectedImage.Orientation.LANDSCAPE) { Activity activity = getActivity(); if (activity != null) { activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); } } } } }
java
Apache-2.0
e32c0bbcf77183ff2ee407b4f179a094f6fdb12a
2026-01-05T02:37:31.908377Z
false
dailystudio/ml
https://github.com/dailystudio/ml/blob/e32c0bbcf77183ff2ee407b4f179a094f6fdb12a/object_detection/app/src/main/java/com/dailystudio/objectdetection/loader/StyledImagesLoader.java
object_detection/app/src/main/java/com/dailystudio/objectdetection/loader/StyledImagesLoader.java
package com.dailystudio.objectdetection.loader; import android.content.Context; import com.dailystudio.app.dataobject.loader.DatabaseObjectsLoader; import com.dailystudio.dataobject.query.OrderingToken; import com.dailystudio.dataobject.query.Query; import com.dailystudio.objectdetection.database.DetectedImage; public class StyledImagesLoader extends DatabaseObjectsLoader<DetectedImage> { public StyledImagesLoader(Context context) { super(context); } @Override protected Class<DetectedImage> getObjectClass() { return DetectedImage.class; } @Override protected Query getQuery(Class<DetectedImage> klass) { Query query = super.getQuery(klass); OrderingToken orderByToken = DetectedImage.COLUMN_TIME.orderByDescending(); if (orderByToken != null) { query.setOrderBy(orderByToken); } return query; } }
java
Apache-2.0
e32c0bbcf77183ff2ee407b4f179a094f6fdb12a
2026-01-05T02:37:31.908377Z
false
dailystudio/ml
https://github.com/dailystudio/ml/blob/e32c0bbcf77183ff2ee407b4f179a094f6fdb12a/object_detection/app/src/main/java/com/dailystudio/objectdetection/loader/ViewDetectedImageLoader.java
object_detection/app/src/main/java/com/dailystudio/objectdetection/loader/ViewDetectedImageLoader.java
package com.dailystudio.objectdetection.loader; import android.content.Context; import android.support.annotation.Nullable; import android.text.TextUtils; import com.dailystudio.app.loader.AbsAsyncDataLoader; import com.dailystudio.objectdetection.database.DetectedImage; import com.dailystudio.objectdetection.database.DetectedImageDatabaseModel; public class ViewDetectedImageLoader extends AbsAsyncDataLoader<DetectedImage> { private String mSrcPath; public ViewDetectedImageLoader(Context context, String srcPath) { super(context); mSrcPath = srcPath; } @Nullable @Override public DetectedImage loadInBackground() { if (TextUtils.isEmpty(mSrcPath)) { return null; } return DetectedImageDatabaseModel.getDetectedImage( getContext(), mSrcPath); } }
java
Apache-2.0
e32c0bbcf77183ff2ee407b4f179a094f6fdb12a
2026-01-05T02:37:31.908377Z
false
dailystudio/ml
https://github.com/dailystudio/ml/blob/e32c0bbcf77183ff2ee407b4f179a094f6fdb12a/object_detection/app/src/main/java/com/dailystudio/objectdetection/loader/LoaderIds.java
object_detection/app/src/main/java/com/dailystudio/objectdetection/loader/LoaderIds.java
package com.dailystudio.objectdetection.loader; /** * Created by nanye on 18/2/26. */ public class LoaderIds { public final static int LOADER_DETECTED_IMAGES = 0x01; public final static int LOADER_VIEW_IMAGE = 0x02; }
java
Apache-2.0
e32c0bbcf77183ff2ee407b4f179a094f6fdb12a
2026-01-05T02:37:31.908377Z
false
dailystudio/ml
https://github.com/dailystudio/ml/blob/e32c0bbcf77183ff2ee407b4f179a094f6fdb12a/object_detection/app/src/main/java/com/dailystudio/objectdetection/utils/ImageUtils.java
object_detection/app/src/main/java/com/dailystudio/objectdetection/utils/ImageUtils.java
package com.dailystudio.objectdetection.utils; import android.graphics.Matrix; import com.dailystudio.development.Logger; public class ImageUtils { /** * Returns a transformation matrix from one reference frame into another. * Handles cropping (if maintaining aspect ratio is desired) and rotation. * * @param srcWidth Width of source frame. * @param srcHeight Height of source frame. * @param dstWidth Width of destination frame. * @param dstHeight Height of destination frame. * @param applyRotation Amount of rotation to apply from one frame to another. * Must be a multiple of 90. * @param maintainAspectRatio If true, will ensure that scaling in x and y remains constant, * cropping the image if necessary. * @return The transformation fulfilling the desired requirements. */ public static Matrix getTransformationMatrix( final int srcWidth, final int srcHeight, final int dstWidth, final int dstHeight, final int applyRotation, final boolean maintainAspectRatio) { final Matrix matrix = new Matrix(); if (applyRotation != 0) { if (applyRotation % 90 != 0) { Logger.debug("Rotation of %d % 90 != 0", applyRotation); } // Translate so center of image is at origin. matrix.postTranslate(-srcWidth / 2.0f, -srcHeight / 2.0f); // Rotate around origin. matrix.postRotate(applyRotation); } // Account for the already applied rotation, if any, and then determine how // much scaling is needed for each axis. final boolean transpose = (Math.abs(applyRotation) + 90) % 180 == 0; final int inWidth = transpose ? srcHeight : srcWidth; final int inHeight = transpose ? srcWidth : srcHeight; // Apply scaling if necessary. if (inWidth != dstWidth || inHeight != dstHeight) { final float scaleFactorX = dstWidth / (float) inWidth; final float scaleFactorY = dstHeight / (float) inHeight; if (maintainAspectRatio) { // Scale by minimum factor so that dst is filled completely while // maintaining the aspect ratio. Some image may fall off the edge. final float scaleFactor = Math.max(scaleFactorX, scaleFactorY); matrix.postScale(scaleFactor, scaleFactor); } else { // Scale exactly to fill dst from src. matrix.postScale(scaleFactorX, scaleFactorY); } } if (applyRotation != 0) { // Translate back from origin centered reference to destination frame. matrix.postTranslate(dstWidth / 2.0f, dstHeight / 2.0f); } return matrix; } }
java
Apache-2.0
e32c0bbcf77183ff2ee407b4f179a094f6fdb12a
2026-01-05T02:37:31.908377Z
false
dailystudio/ml
https://github.com/dailystudio/ml/blob/e32c0bbcf77183ff2ee407b4f179a094f6fdb12a/object_detection/app/src/main/java/com/dailystudio/objectdetection/utils/FilePickUtils.java
object_detection/app/src/main/java/com/dailystudio/objectdetection/utils/FilePickUtils.java
package com.dailystudio.objectdetection.utils; import android.annotation.SuppressLint; import android.content.ContentUris; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.provider.DocumentsContract; import android.provider.MediaStore; public class FilePickUtils { private static String getPathDeprecated(Context ctx, Uri uri) { if( uri == null ) { return null; } String[] projection = { MediaStore.Images.Media.DATA }; Cursor cursor = ctx.getContentResolver().query(uri, projection, null, null, null); if( cursor != null ){ int column_index = cursor .getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); return cursor.getString(column_index); } return uri.getPath(); } public static String getSmartFilePath(Context ctx, Uri uri){ if (Build.VERSION.SDK_INT < 19) { return getPathDeprecated(ctx, uri); } return FilePickUtils.getPath(ctx, uri); } @SuppressLint("NewApi") public static String getPath(final Context context, final Uri uri) { final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT; // DocumentProvider if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) { // ExternalStorageProvider if (isExternalStorageDocument(uri)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; if ("primary".equalsIgnoreCase(type)) { return Environment.getExternalStorageDirectory() + "/" + split[1]; } // TODO handle non-primary volumes } // DownloadsProvider else if (isDownloadsDocument(uri)) { final String id = DocumentsContract.getDocumentId(uri); final Uri contentUri = ContentUris.withAppendedId( Uri.parse("content://downloads/public_downloads"), Long.valueOf(id)); return getDataColumn(context, contentUri, null, null); } // MediaProvider else if (isMediaDocument(uri)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; Uri contentUri = null; if ("image".equals(type)) { contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; } else if ("video".equals(type)) { contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; } else if ("audio".equals(type)) { contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; } final String selection = "_id=?"; final String[] selectionArgs = new String[] { split[1] }; return getDataColumn(context, contentUri, selection, selectionArgs); } } // MediaStore (and general) else if ("content".equalsIgnoreCase(uri.getScheme())) { return getDataColumn(context, uri, null, null); } // File else if ("file".equalsIgnoreCase(uri.getScheme())) { return uri.getPath(); } return null; } /** * Get the value of the data column for this Uri. This is useful for * MediaStore Uris, and other file-based ContentProviders. * * @param context The context. * @param uri The Uri to query. * @param selection (Optional) Filter used in the query. * @param selectionArgs (Optional) Selection arguments used in the query. * @return The value of the _data column, which is typically a file path. */ public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) { Cursor cursor = null; final String column = "_data"; final String[] projection = { column }; try { cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null); if (cursor != null && cursor.moveToFirst()) { final int column_index = cursor.getColumnIndexOrThrow(column); return cursor.getString(column_index); } } finally { if (cursor != null) cursor.close(); } return null; } /** * @param uri The Uri to check. * @return Whether the Uri authority is ExternalStorageProvider. */ public static boolean isExternalStorageDocument(Uri uri) { return "com.android.externalstorage.documents".equals(uri.getAuthority()); } /** * @param uri The Uri to check. * @return Whether the Uri authority is DownloadsProvider. */ public static boolean isDownloadsDocument(Uri uri) { return "com.android.providers.downloads.documents".equals(uri.getAuthority()); } /** * @param uri The Uri to check. * @return Whether the Uri authority is MediaProvider. */ public static boolean isMediaDocument(Uri uri) { return "com.android.providers.media.documents".equals(uri.getAuthority()); } }
java
Apache-2.0
e32c0bbcf77183ff2ee407b4f179a094f6fdb12a
2026-01-05T02:37:31.908377Z
false
dailystudio/ml
https://github.com/dailystudio/ml/blob/e32c0bbcf77183ff2ee407b4f179a094f6fdb12a/object_detection/app/src/main/java/com/dailystudio/objectdetection/api/ObjectDetectionModel.java
object_detection/app/src/main/java/com/dailystudio/objectdetection/api/ObjectDetectionModel.java
package com.dailystudio.objectdetection.api; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.RectF; import com.dailystudio.development.Logger; import com.dailystudio.objectdetection.utils.ImageUtils; import java.io.IOException; import java.util.LinkedList; import java.util.List; public class ObjectDetectionModel { // Configuration values for the prepackaged SSD model. private static final int TF_OD_API_INPUT_SIZE = 300; private static final boolean TF_OD_API_IS_QUANTIZED = true; private static final String TF_OD_API_MODEL_FILE = "detect.tflite"; private static final String TF_OD_API_LABELS_FILE = "file:///android_asset/coco_labels_list.txt"; private static final float MINIMUM_CONFIDENCE_TF_OD_API = 0.6f; private static Classifier sDetector = null; private static Bitmap croppedBitmap = null; private static Matrix frameToCropTransform; private static Matrix cropToFrameTransform; public synchronized static boolean isInitialized() { return (sDetector != null); } public static boolean initialize(Context context) { if (context == null) { return false; } boolean success = false; try { sDetector = TFLiteObjectDetectionAPIModel.create( context.getAssets(), TF_OD_API_MODEL_FILE, TF_OD_API_LABELS_FILE, TF_OD_API_INPUT_SIZE, TF_OD_API_IS_QUANTIZED); success = true; } catch (final IOException e) { Logger.error("Initializing classifier failed: %s", e.toString()); sDetector = null; success = false; } croppedBitmap = Bitmap.createBitmap( TF_OD_API_INPUT_SIZE, TF_OD_API_INPUT_SIZE, Bitmap.Config.ARGB_8888); return success; } public static List<Classifier.Recognition> detectImage(Bitmap bitmap) { return detectImage(bitmap, 0); } public static List<Classifier.Recognition> detectImage(Bitmap bitmap, float minimumConfidence) { if (bitmap == null) { return null; } if (minimumConfidence <= 0 || minimumConfidence > 1) { minimumConfidence = MINIMUM_CONFIDENCE_TF_OD_API; } if (!ObjectDetectionModel.isInitialized()) { Logger.warn("object detection model is NOT initialized yet."); return null; } final int width = bitmap.getWidth(); final int height = bitmap.getHeight(); frameToCropTransform = ImageUtils.getTransformationMatrix( width, height, TF_OD_API_INPUT_SIZE, TF_OD_API_INPUT_SIZE, 0, true); cropToFrameTransform = new Matrix(); frameToCropTransform.invert(cropToFrameTransform); final Canvas canvas = new Canvas(croppedBitmap); canvas.drawBitmap(bitmap, frameToCropTransform, null); List<Classifier.Recognition> results = sDetector.recognizeImage(croppedBitmap); final List<Classifier.Recognition> mappedRecognitions = new LinkedList<>(); for (final Classifier.Recognition recognition: results) { final RectF loc = recognition.getLocation(); if (loc != null && recognition.getConfidence() >= minimumConfidence) { cropToFrameTransform.mapRect(loc); recognition.setLocation(loc); mappedRecognitions.add(recognition); Logger.debug("add satisfied recognition: %s", recognition); } else { Logger.warn("skip unsatisfied recognition: %s", recognition); } } return mappedRecognitions; } }
java
Apache-2.0
e32c0bbcf77183ff2ee407b4f179a094f6fdb12a
2026-01-05T02:37:31.908377Z
false
dailystudio/ml
https://github.com/dailystudio/ml/blob/e32c0bbcf77183ff2ee407b4f179a094f6fdb12a/object_detection/app/src/main/java/com/dailystudio/objectdetection/api/Classifier.java
object_detection/app/src/main/java/com/dailystudio/objectdetection/api/Classifier.java
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ package com.dailystudio.objectdetection.api; import android.graphics.Bitmap; import android.graphics.RectF; import java.util.List; /** * Generic interface for interacting with different recognition engines. */ public interface Classifier { /** * An immutable result returned by a Classifier describing what was recognized. */ public class Recognition { /** * A unique identifier for what has been recognized. Specific to the class, not the instance of * the object. */ private final String id; /** * Display name for the recognition. */ private final String title; /** * A sortable score for how good the recognition is relative to others. Higher should be better. */ private final Float confidence; /** Optional location within the source image for the location of the recognized object. */ private RectF location; public Recognition( final String id, final String title, final Float confidence, final RectF location) { this.id = id; this.title = title; this.confidence = confidence; this.location = location; } public String getId() { return id; } public String getTitle() { return title; } public Float getConfidence() { return confidence; } public RectF getLocation() { return new RectF(location); } public void setLocation(RectF location) { this.location = location; } @Override public String toString() { String resultString = ""; if (id != null) { resultString += "[" + id + "] "; } if (title != null) { resultString += title + " "; } if (confidence != null) { resultString += String.format("(%.1f%%) ", confidence * 100.0f); } if (location != null) { resultString += location + " "; } return resultString.trim(); } } List<Recognition> recognizeImage(Bitmap bitmap); void enableStatLogging(final boolean debug); String getStatString(); void close(); }
java
Apache-2.0
e32c0bbcf77183ff2ee407b4f179a094f6fdb12a
2026-01-05T02:37:31.908377Z
false
dailystudio/ml
https://github.com/dailystudio/ml/blob/e32c0bbcf77183ff2ee407b4f179a094f6fdb12a/object_detection/app/src/main/java/com/dailystudio/objectdetection/api/TFLiteObjectDetectionAPIModel.java
object_detection/app/src/main/java/com/dailystudio/objectdetection/api/TFLiteObjectDetectionAPIModel.java
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ package com.dailystudio.objectdetection.api; import android.content.res.AssetFileDescriptor; import android.content.res.AssetManager; import android.graphics.Bitmap; import android.graphics.RectF; import android.os.Trace; import com.dailystudio.development.Logger; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Vector; import org.tensorflow.lite.Interpreter; /** * Wrapper for frozen detection models trained using the Tensorflow Object Detection API: * github.com/tensorflow/models/tree/master/research/object_detection */ public class TFLiteObjectDetectionAPIModel implements Classifier { // Only return this many results. private static final int NUM_DETECTIONS = 10; private boolean isModelQuantized; // Float model private static final float IMAGE_MEAN = 128.0f; private static final float IMAGE_STD = 128.0f; // Number of threads in the java app private static final int NUM_THREADS = 4; // Config values. private int inputSize; // Pre-allocated buffers. private Vector<String> labels = new Vector<String>(); private int[] intValues; // outputLocations: array of shape [Batchsize, NUM_DETECTIONS,4] // contains the location of detected boxes private float[][][] outputLocations; // outputClasses: array of shape [Batchsize, NUM_DETECTIONS] // contains the classes of detected boxes private float[][] outputClasses; // outputScores: array of shape [Batchsize, NUM_DETECTIONS] // contains the scores of detected boxes private float[][] outputScores; // numDetections: array of shape [Batchsize] // contains the number of detected boxes private float[] numDetections; private ByteBuffer imgData; private Interpreter tfLite; /** Memory-map the model file in Assets. */ private static MappedByteBuffer loadModelFile(AssetManager assets, String modelFilename) throws IOException { AssetFileDescriptor fileDescriptor = assets.openFd(modelFilename); FileInputStream inputStream = new FileInputStream(fileDescriptor.getFileDescriptor()); FileChannel fileChannel = inputStream.getChannel(); long startOffset = fileDescriptor.getStartOffset(); long declaredLength = fileDescriptor.getDeclaredLength(); return fileChannel.map(FileChannel.MapMode.READ_ONLY, startOffset, declaredLength); } /** * Initializes a native TensorFlow session for classifying images. * * @param assetManager The asset manager to be used to load assets. * @param modelFilename The filepath of the model GraphDef protocol buffer. * @param labelFilename The filepath of label file for classes. * @param inputSize The size of image input * @param isQuantized Boolean representing model is quantized or not */ public static Classifier create( final AssetManager assetManager, final String modelFilename, final String labelFilename, final int inputSize, final boolean isQuantized) throws IOException { final TFLiteObjectDetectionAPIModel d = new TFLiteObjectDetectionAPIModel(); InputStream labelsInput = null; String actualFilename = labelFilename.split("file:///android_asset/")[1]; labelsInput = assetManager.open(actualFilename); BufferedReader br = null; br = new BufferedReader(new InputStreamReader(labelsInput)); String line; while ((line = br.readLine()) != null) { Logger.warn(line); d.labels.add(line); } br.close(); d.inputSize = inputSize; try { d.tfLite = new Interpreter(loadModelFile(assetManager, modelFilename)); } catch (Exception e) { throw new RuntimeException(e); } d.isModelQuantized = isQuantized; // Pre-allocate buffers. int numBytesPerChannel; if (isQuantized) { numBytesPerChannel = 1; // Quantized } else { numBytesPerChannel = 4; // Floating point } d.imgData = ByteBuffer.allocateDirect(1 * d.inputSize * d.inputSize * 3 * numBytesPerChannel); d.imgData.order(ByteOrder.nativeOrder()); d.intValues = new int[d.inputSize * d.inputSize]; d.tfLite.setNumThreads(NUM_THREADS); d.outputLocations = new float[1][NUM_DETECTIONS][4]; d.outputClasses = new float[1][NUM_DETECTIONS]; d.outputScores = new float[1][NUM_DETECTIONS]; d.numDetections = new float[1]; return d; } private TFLiteObjectDetectionAPIModel() {} @Override public List<Recognition> recognizeImage(final Bitmap bitmap) { // Log this method so that it can be analyzed with systrace. Trace.beginSection("recognizeImage"); Trace.beginSection("preprocessBitmap"); // Preprocess the image data from 0-255 int to normalized float based // on the provided parameters. bitmap.getPixels(intValues, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight()); imgData.rewind(); for (int i = 0; i < inputSize; ++i) { for (int j = 0; j < inputSize; ++j) { int pixelValue = intValues[i * inputSize + j]; if (isModelQuantized) { // Quantized model imgData.put((byte) ((pixelValue >> 16) & 0xFF)); imgData.put((byte) ((pixelValue >> 8) & 0xFF)); imgData.put((byte) (pixelValue & 0xFF)); } else { // Float model imgData.putFloat((((pixelValue >> 16) & 0xFF) - IMAGE_MEAN) / IMAGE_STD); imgData.putFloat((((pixelValue >> 8) & 0xFF) - IMAGE_MEAN) / IMAGE_STD); imgData.putFloat(((pixelValue & 0xFF) - IMAGE_MEAN) / IMAGE_STD); } } } Trace.endSection(); // preprocessBitmap // Copy the input data into TensorFlow. Trace.beginSection("feed"); outputLocations = new float[1][NUM_DETECTIONS][4]; outputClasses = new float[1][NUM_DETECTIONS]; outputScores = new float[1][NUM_DETECTIONS]; numDetections = new float[1]; Object[] inputArray = {imgData}; Map<Integer, Object> outputMap = new HashMap<>(); outputMap.put(0, outputLocations); outputMap.put(1, outputClasses); outputMap.put(2, outputScores); outputMap.put(3, numDetections); Trace.endSection(); // Run the inference call. Trace.beginSection("run"); tfLite.runForMultipleInputsOutputs(inputArray, outputMap); Trace.endSection(); // Show the best detections. // after scaling them back to the input size. final ArrayList<Recognition> recognitions = new ArrayList<>(NUM_DETECTIONS); for (int i = 0; i < NUM_DETECTIONS; ++i) { final RectF detection = new RectF( outputLocations[0][i][1] * inputSize, outputLocations[0][i][0] * inputSize, outputLocations[0][i][3] * inputSize, outputLocations[0][i][2] * inputSize); // SSD Mobilenet V1 Model assumes class 0 is background class // in label file and class labels start from 1 to number_of_classes+1, // while outputClasses correspond to class index from 0 to number_of_classes int labelOffset = 1; recognitions.add( new Recognition( "" + i, labels.get((int) outputClasses[0][i] + labelOffset), outputScores[0][i], detection)); } Trace.endSection(); // "recognizeImage" return recognitions; } @Override public void enableStatLogging(final boolean logStats) { } @Override public String getStatString() { return ""; } @Override public void close() { } }
java
Apache-2.0
e32c0bbcf77183ff2ee407b4f179a094f6fdb12a
2026-01-05T02:37:31.908377Z
false
dailystudio/ml
https://github.com/dailystudio/ml/blob/e32c0bbcf77183ff2ee407b4f179a094f6fdb12a/object_detection/app/src/main/java/com/dailystudio/objectdetection/database/DetectedImageDatabaseModel.java
object_detection/app/src/main/java/com/dailystudio/objectdetection/database/DetectedImageDatabaseModel.java
package com.dailystudio.objectdetection.database; import android.content.Context; import android.support.annotation.NonNull; import android.text.TextUtils; import com.dailystudio.dataobject.DatabaseObjectKeys; import com.dailystudio.dataobject.query.ExpressionToken; import com.dailystudio.datetime.dataobject.AbsTimeCapsuleModel; import com.dailystudio.development.Logger; import java.util.List; /** * Created by nanye on 18/1/12. */ public class DetectedImageDatabaseModel extends AbsTimeCapsuleModel<DetectedImage> { private final static String GET_DETECTED_IMAGE = "get-styled-image"; public DetectedImageDatabaseModel(@NonNull Class<DetectedImage> objectClass) { super(objectClass); } @Override protected ExpressionToken objectExistenceToken(DatabaseObjectKeys keys) { if (keys == null || keys.hasValue(DetectedImage.COLUMN_SOURCE) == false) { return null; } String srcPath = (String) keys.getValue(DetectedImage.COLUMN_SOURCE); ExpressionToken selToken = DetectedImage.COLUMN_SOURCE.eq(srcPath); return selToken; } @Override protected void applyArgsOnObject(DetectedImage object, DatabaseObjectKeys keys) { if (object == null || keys == null || keys.hasValue(DetectedImage.COLUMN_SOURCE) == false || keys.hasValue(DetectedImage.COLUMN_DETECTED_PATH) == false || keys.hasValue(DetectedImage.COLUMN_ORIENTATION, true) == false) { return; } object.setTime(System.currentTimeMillis()); object.setSourcePath((String)keys.getValue(DetectedImage.COLUMN_SOURCE)); object.setStyledPath((String)keys.getValue(DetectedImage.COLUMN_DETECTED_PATH)); object.setOrientation((DetectedImage.Orientation) keys.getValue(DetectedImage.COLUMN_ORIENTATION)); } @Override protected ExpressionToken objectsToken(DatabaseObjectKeys keys, @NonNull String tokenType) { if (GET_DETECTED_IMAGE.equals(tokenType)) { if (keys != null && keys.hasValue(DetectedImage.COLUMN_SOURCE)) { final String srcPath = (String) keys.getValue(DetectedImage.COLUMN_SOURCE); return DetectedImage.COLUMN_SOURCE.eq(srcPath); } else { return null; } } return super.objectsToken(keys, tokenType); } @Override protected ExpressionToken objectsDeletionToken(DatabaseObjectKeys keys) { if (keys == null || keys.hasValue(DetectedImage.COLUMN_SOURCE) == false) { return null; } final String srcPath = (String) keys.getValue(DetectedImage.COLUMN_SOURCE); ExpressionToken selToken = DetectedImage.COLUMN_SOURCE.eq(srcPath); return selToken; } private final static DetectedImageDatabaseModel INSTANCE = new DetectedImageDatabaseModel(DetectedImage.class); public final static DetectedImage saveDetectedImage(Context context, String srcPath, String detectedPath, DetectedImage.Orientation orientation) { Logger.debug("save detected image: srcPath = %s, detectedPath = %s, orientation = %s", srcPath, detectedPath, orientation); if (context == null || TextUtils.isEmpty(srcPath) || TextUtils.isEmpty(detectedPath) || orientation == null) { return null; } DatabaseObjectKeys keys = new DatabaseObjectKeys(); keys.putValue(DetectedImage.COLUMN_SOURCE, srcPath); keys.putValue(DetectedImage.COLUMN_DETECTED_PATH, detectedPath); keys.putValue(DetectedImage.COLUMN_ORIENTATION, orientation); return INSTANCE.addOrUpdateObject(context, keys); } public final static DetectedImage getDetectedImage(Context context, String srcPath) { DatabaseObjectKeys keys = new DatabaseObjectKeys(); keys.putValue(DetectedImage.COLUMN_SOURCE, srcPath); List<DetectedImage> images = INSTANCE.listObjects(context, keys, GET_DETECTED_IMAGE); if (images == null || images.size() <= 0) { return null; } return images.get(0); } }
java
Apache-2.0
e32c0bbcf77183ff2ee407b4f179a094f6fdb12a
2026-01-05T02:37:31.908377Z
false
dailystudio/ml
https://github.com/dailystudio/ml/blob/e32c0bbcf77183ff2ee407b4f179a094f6fdb12a/object_detection/app/src/main/java/com/dailystudio/objectdetection/database/DetectedImage.java
object_detection/app/src/main/java/com/dailystudio/objectdetection/database/DetectedImage.java
package com.dailystudio.objectdetection.database; import android.content.Context; import android.text.TextUtils; import com.dailystudio.dataobject.Column; import com.dailystudio.dataobject.Template; import com.dailystudio.dataobject.TextColumn; import com.dailystudio.datetime.dataobject.TimeCapsule; import com.dailystudio.development.Logger; /** * Created by nanye on 18/1/12. */ public class DetectedImage extends TimeCapsule { public enum Orientation { LANDSCAPE, PORTRAIT, } public static final Column COLUMN_SOURCE = new TextColumn("source", false); public static final Column COLUMN_DETECTED_PATH = new TextColumn("detected_path", false); public static final Column COLUMN_ORIENTATION = new TextColumn("orientation", false); private final static Column[] sCloumns = { COLUMN_SOURCE, COLUMN_DETECTED_PATH, COLUMN_ORIENTATION, }; public DetectedImage(Context context) { super(context); initMembers(); } public DetectedImage(Context context, int version) { super(context, version); initMembers(); } private void initMembers() { final Template templ = getTemplate(); templ.addColumns(sCloumns); } public void setSourcePath(String srcPath) { setValue(COLUMN_SOURCE, srcPath); } public String getSourcePath() { return getTextValue(COLUMN_SOURCE); } public void setStyledPath(String styledPath) { setValue(COLUMN_DETECTED_PATH, styledPath); } public String getDetectedPath() { return getTextValue(COLUMN_DETECTED_PATH); } public void setOrientation(Orientation orientation) { setValue(COLUMN_ORIENTATION, String.valueOf(orientation)); } public Orientation getOrientation() { final String str = getTextValue(COLUMN_ORIENTATION); if (TextUtils.isEmpty(str)) { return Orientation.LANDSCAPE; } Orientation orientation; try { orientation = Orientation.valueOf(str); } catch (Exception e) { Logger.error("parse orientation from string[%s] failed: %s", str, e.toString()); orientation = Orientation.LANDSCAPE; } return orientation; } @Override public String toString() { return String.format("%s(0x%08x): source(%s), detected(%s), orientation(%s)", getClass().getSimpleName(), hashCode(), getSourcePath(), getDetectedPath(), getOrientation()); } }
java
Apache-2.0
e32c0bbcf77183ff2ee407b4f179a094f6fdb12a
2026-01-05T02:37:31.908377Z
false
dailystudio/ml
https://github.com/dailystudio/ml/blob/e32c0bbcf77183ff2ee407b4f179a094f6fdb12a/object_detection/app/src/main/java/com/dailystudio/objectdetection/ui/DetectedImageViewHolder.java
object_detection/app/src/main/java/com/dailystudio/objectdetection/ui/DetectedImageViewHolder.java
package com.dailystudio.objectdetection.ui; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.support.v4.content.FileProvider; import android.view.View; import android.widget.ImageView; import com.dailystudio.app.ui.AbsArrayItemViewHolder; import com.dailystudio.app.utils.ActivityLauncher; import com.dailystudio.development.Logger; import com.dailystudio.objectdetection.Constants; import com.dailystudio.objectdetection.R; import com.dailystudio.objectdetection.ViewDetectedImageActivity; import com.dailystudio.objectdetection.database.DetectedImage; import com.nostra13.universalimageloader.core.ImageLoader; import java.io.File; /** * Created by nanye on 18/1/4. */ public class DetectedImageViewHolder extends AbsArrayItemViewHolder<DetectedImage> { private ImageView mStyledThumb; private View mShareView; public DetectedImageViewHolder(View itemView) { super(itemView); setupViews(itemView); } private void setupViews(View itemView) { if (itemView == null) { return; } mStyledThumb = itemView.findViewById(R.id.detected_thumb); mShareView = itemView.findViewById(R.id.share_image); if (mShareView != null) { mShareView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Object o = v.getTag(); Logger.debug("share image: %s", o); if (o instanceof DetectedImage == false) { return; } final Context context = v.getContext(); if (context == null) { return; } DetectedImage DetectedImage = (DetectedImage)o; File sharedFile = new File(DetectedImage.getDetectedPath()); Uri imageUri = FileProvider.getUriForFile(context, Constants.getFileProvideAuthority(context), sharedFile); Intent share = new Intent(Intent.ACTION_SEND); share.setType("image/*"); share.putExtra(Intent.EXTRA_TEXT, context.getString(R.string.prompt_image_share)); share.putExtra(Intent.EXTRA_STREAM, imageUri); ActivityLauncher.launchActivity(context, Intent.createChooser(share, "Share Image")); } }); } } @Override public void bindItem(final Context context, final DetectedImage image) { if (image == null) { return; } final String styledPath = image.getDetectedPath(); if (mShareView != null) { mShareView.setTag(image); } if (mStyledThumb != null) { ImageLoader.getInstance().displayImage( "file://" + styledPath, mStyledThumb, Constants.DEFAULT_IMAGE_LOADER_OPTIONS); mStyledThumb.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Logger.debug("click on image: %s", image); Intent i = new Intent(); i.setClass(context.getApplicationContext(), ViewDetectedImageActivity.class); i.putExtra(Constants.EXTRA_SRC_PATH, image.getSourcePath()); ActivityLauncher.launchActivity(context, i); } }); } } }
java
Apache-2.0
e32c0bbcf77183ff2ee407b4f179a094f6fdb12a
2026-01-05T02:37:31.908377Z
false
dailystudio/ml
https://github.com/dailystudio/ml/blob/e32c0bbcf77183ff2ee407b4f179a094f6fdb12a/object_detection/app/src/main/java/com/dailystudio/objectdetection/ui/ImageSelectedEvent.java
object_detection/app/src/main/java/com/dailystudio/objectdetection/ui/ImageSelectedEvent.java
package com.dailystudio.objectdetection.ui; public class ImageSelectedEvent { public int selectedPosition; public ImageSelectedEvent(int index) { selectedPosition = index; } }
java
Apache-2.0
e32c0bbcf77183ff2ee407b4f179a094f6fdb12a
2026-01-05T02:37:31.908377Z
false
dailystudio/ml
https://github.com/dailystudio/ml/blob/e32c0bbcf77183ff2ee407b4f179a094f6fdb12a/object_detection/app/src/main/java/com/dailystudio/objectdetection/ui/ImageDetectionEvent.java
object_detection/app/src/main/java/com/dailystudio/objectdetection/ui/ImageDetectionEvent.java
package com.dailystudio.objectdetection.ui; public class ImageDetectionEvent { public enum State { DECODING, DETECTING, TAGGING, DONE } public State state; public ImageDetectionEvent(State state) { this.state = state; } }
java
Apache-2.0
e32c0bbcf77183ff2ee407b4f179a094f6fdb12a
2026-01-05T02:37:31.908377Z
false
dailystudio/ml
https://github.com/dailystudio/ml/blob/e32c0bbcf77183ff2ee407b4f179a094f6fdb12a/object_detection/app/src/main/java/com/dailystudio/objectdetection/ui/DetectedImagesRecyclerAdapter.java
object_detection/app/src/main/java/com/dailystudio/objectdetection/ui/DetectedImagesRecyclerAdapter.java
package com.dailystudio.objectdetection.ui; import android.content.Context; import android.view.View; import android.view.ViewGroup; import com.dailystudio.app.ui.AbsArrayRecyclerAdapter; import com.dailystudio.objectdetection.R; import com.dailystudio.objectdetection.database.DetectedImage; /** * Created by nanye on 16/6/9. */ public class DetectedImagesRecyclerAdapter extends AbsArrayRecyclerAdapter<DetectedImage, DetectedImageViewHolder> { public DetectedImagesRecyclerAdapter(Context context) { super(context); } @Override public DetectedImageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = mLayoutInflater.inflate(R.layout.layout_detected_image , null); return new DetectedImageViewHolder(view); } }
java
Apache-2.0
e32c0bbcf77183ff2ee407b4f179a094f6fdb12a
2026-01-05T02:37:31.908377Z
false
dailystudio/ml
https://github.com/dailystudio/ml/blob/e32c0bbcf77183ff2ee407b4f179a094f6fdb12a/object_detection/app/src/androidTest/java/com/dailystudio/objectdetection/ExampleInstrumentedTest.java
object_detection/app/src/androidTest/java/com/dailystudio/objectdetection/ExampleInstrumentedTest.java
package com.dailystudio.objectdetection; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.dailystudio.objectdetection", appContext.getPackageName()); } }
java
Apache-2.0
e32c0bbcf77183ff2ee407b4f179a094f6fdb12a
2026-01-05T02:37:31.908377Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-api/src/test/java/com/fnproject/fn/api/flow/FlowsTest.java
flow-api/src/test/java/com/fnproject/fn/api/flow/FlowsTest.java
/* * Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fnproject.fn.api.flow; import org.junit.Test; import java.lang.reflect.Modifier; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class FlowsTest { public FlowsTest() { } /** People shall not be allowed to create subclasses of {@code Flow}: * <pre> * static class MyFlows extends Flows { * } * </pre> */ @Test public void dontSubclassFlows() { assertTrue("Flows is final", Modifier.isFinal(Flows.class.getModifiers())); assertEquals("No visible constructors", 0, Flows.class.getConstructors().length); } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-api/src/main/java/com/fnproject/fn/api/flow/HttpResponse.java
flow-api/src/main/java/com/fnproject/fn/api/flow/HttpResponse.java
/* * Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fnproject.fn.api.flow; import com.fnproject.fn.api.Headers; /** * A FunctionResponse represents the HTTP response from an external function invocation * (e.g. execute by {@code rt.invokeFunction(id, data)} */ public interface HttpResponse { /** * Return the HTTP status code of the function response * * @return the HTTP status code */ int getStatusCode(); /** * Return the headers on the HTTP function response * * @return the headers */ Headers getHeaders(); /** * Returns the body of the function result as a byte array * * @return the function response body */ byte[] getBodyAsBytes(); }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-api/src/main/java/com/fnproject/fn/api/flow/InvalidStageResponseException.java
flow-api/src/main/java/com/fnproject/fn/api/flow/InvalidStageResponseException.java
/* * Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fnproject.fn.api.flow; /** * Exception thrown when a completion stage responds with an incompatible datum type for its corresponding completion * graph stage. */ public class InvalidStageResponseException extends PlatformException { public InvalidStageResponseException(String reason) { super(reason); } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-api/src/main/java/com/fnproject/fn/api/flow/ResultSerializationException.java
flow-api/src/main/java/com/fnproject/fn/api/flow/ResultSerializationException.java
/* * Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fnproject.fn.api.flow; /** * Exception thrown when a result returned by a completion stage fails to be serialized. */ public class ResultSerializationException extends FlowCompletionException { public ResultSerializationException(String message, Throwable e) { super(message, e); } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-api/src/main/java/com/fnproject/fn/api/flow/HttpRequest.java
flow-api/src/main/java/com/fnproject/fn/api/flow/HttpRequest.java
/* * Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fnproject.fn.api.flow; import com.fnproject.fn.api.Headers; /** * An abstract HTTP request details (without location) */ public interface HttpRequest { /** * Return the HTTP method used to supply this value * * @return the HTTP method */ HttpMethod getMethod(); /** * Return the headers on the HTTP request * * @return the headers */ Headers getHeaders(); /** * Returns the body of the request as a byte array * * @return the function request body */ byte[] getBodyAsBytes(); }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-api/src/main/java/com/fnproject/fn/api/flow/StageLostException.java
flow-api/src/main/java/com/fnproject/fn/api/flow/StageLostException.java
/* * Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fnproject.fn.api.flow; /** * Exception thrown when a stage failed after an internal error in the flow server, the stage may or may not have been * invoked and that invocation may or may not have completed. */ public class StageLostException extends PlatformException { public StageLostException(String reason) { super(reason); } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-api/src/main/java/com/fnproject/fn/api/flow/FunctionInvocationException.java
flow-api/src/main/java/com/fnproject/fn/api/flow/FunctionInvocationException.java
/* * Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fnproject.fn.api.flow; /** * Exception thrown when an external function invocation returns a failure. * * This includes when the function returns a result but has a non-successful HTTP error status * */ public class FunctionInvocationException extends RuntimeException { private final HttpResponse functionResponse; public FunctionInvocationException(HttpResponse functionResponse) { super(new String(functionResponse.getBodyAsBytes())); this.functionResponse = functionResponse; } /** * The HTTP details returned from the function invocation * @return an http response from the an external function */ public HttpResponse getFunctionResponse() { return functionResponse; } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-api/src/main/java/com/fnproject/fn/api/flow/LambdaSerializationException.java
flow-api/src/main/java/com/fnproject/fn/api/flow/LambdaSerializationException.java
/* * Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fnproject.fn.api.flow; /** * Exception thrown when a lambda or any referenced objects fail to be serialized. * The cause will typically be a {@link java.io.NotSerializableException} or other {@link java.io.IOException} detailing what could not be serialized */ public class LambdaSerializationException extends FlowCompletionException { public LambdaSerializationException(String message) { super(message); } public LambdaSerializationException(String message, Exception e) { super(message, e); } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-api/src/main/java/com/fnproject/fn/api/flow/package-info.java
flow-api/src/main/java/com/fnproject/fn/api/flow/package-info.java
/* * Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * SDK for creating and running asynchronous processes from within fn for Java. */ package com.fnproject.fn.api.flow;
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-api/src/main/java/com/fnproject/fn/api/flow/PlatformException.java
flow-api/src/main/java/com/fnproject/fn/api/flow/PlatformException.java
/* * Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fnproject.fn.api.flow; /** * Exception thrown when the completion facility fails to operate on a completion graph */ public class PlatformException extends FlowCompletionException { public PlatformException(Throwable t) { super(t); } public PlatformException(String message) { super(message); } public PlatformException(String message, Throwable t) { super(message, t); } /** * These are manufactured exceptions that arise outside the current runtime; therefore, * the notion of an embedded stack trace is meaningless. * * @return this */ @Override public synchronized Throwable fillInStackTrace() { return this; } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-api/src/main/java/com/fnproject/fn/api/flow/FunctionTimeoutException.java
flow-api/src/main/java/com/fnproject/fn/api/flow/FunctionTimeoutException.java
/* * Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fnproject.fn.api.flow; /** * Exception thrown when a function execution exceeds its configured timeout. * * When this exception is raised the fn server has terminated the container hosting the function. */ public class FunctionTimeoutException extends PlatformException { public FunctionTimeoutException(String reason) { super(reason); } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-api/src/main/java/com/fnproject/fn/api/flow/Flows.java
flow-api/src/main/java/com/fnproject/fn/api/flow/Flows.java
/* * Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fnproject.fn.api.flow; import java.io.Serializable; import java.util.Objects; import java.util.concurrent.Callable; import java.util.function.*; /** * Fn Flow API entry point class - this provides access to the current {@link Flow} for the current function invocation. */ public final class Flows { private Flows() { } private static FlowSource flowSource; /** * Gets the current supplier of the flow runtime * * @return the current supplier of the flow runtime */ public static synchronized FlowSource getCurrentFlowSource() { return flowSource; } /** * Defines a supplier for the current runtime- */ public interface FlowSource { Flow currentFlow(); } /** * Return the current flow runtime - this will create a new flow if the current is not already bound to the invocation or * an existing flow if one is already bound to the current invocation or if the invocation was triggered from within a flow stage. * * @return the current flow runtime */ public synchronized static Flow currentFlow() { Objects.requireNonNull(flowSource, "Flows.flowSource is not set - Flows.currentFlow() is the @FnFeature(FlowFeature.class) annotation set on your function?"); return flowSource.currentFlow(); } /** * Set the current runtime source - this determines how {@link #currentFlow()} behaves * <p> * This is provided for testing and internal use - users should not normally need to modify the runtime source. * * @param flowSource a function that instantiates a runtime on demand */ public synchronized static void setCurrentFlowSource(FlowSource flowSource) { Flows.flowSource = flowSource; } /** * Version of {@link Callable} that is implicitly serializable. */ @FunctionalInterface public interface SerCallable<V> extends Callable<V>, Serializable { } /** * Version of {@link Supplier} that is implicitly serializable. */ @FunctionalInterface public interface SerSupplier<V> extends Supplier<V>, Serializable { } /** * Version of {@link Consumer} that is implicitly serializable. */ @FunctionalInterface public interface SerConsumer<V> extends Consumer<V>, Serializable { } /** * Version of {@link Function} that is implicitly serializable. */ @FunctionalInterface public interface SerFunction<T, V> extends Function<T, V>, Serializable { } /** * Version of {@link BiFunction} that is implicitly serializable. */ @FunctionalInterface public interface SerBiFunction<T, U, R> extends BiFunction<T, U, R>, Serializable { } /** * Version of {@link BiConsumer} that is implicitly serializable. */ @FunctionalInterface public interface SerBiConsumer<T, U> extends BiConsumer<T, U>, Serializable { } /** * Version of {@link Runnable} that is implicitly serializable. */ @FunctionalInterface public interface SerRunnable extends Runnable, Serializable { } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-api/src/main/java/com/fnproject/fn/api/flow/FunctionInvokeFailedException.java
flow-api/src/main/java/com/fnproject/fn/api/flow/FunctionInvokeFailedException.java
/* * Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fnproject.fn.api.flow; /** * Exception thrown when a function call failed within the fn platform - the function may or may not have been invoked and * that invocation may or may not have completed. */ public class FunctionInvokeFailedException extends PlatformException { public FunctionInvokeFailedException(String reason) { super(reason); } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-api/src/main/java/com/fnproject/fn/api/flow/FlowFuture.java
flow-api/src/main/java/com/fnproject/fn/api/flow/FlowFuture.java
/* * Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fnproject.fn.api.flow; import java.io.Serializable; import java.util.concurrent.CompletionStage; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; /** * This class exposes operations (with a similar API to {@link java.util.concurrent.CompletionStage}) that allow * asynchronous computation to be chained into the current execution graph of a Flow. * <p> * All asynchronous operations start with a call to an operation on {@link Flow} - for instance to create a simple asynchronous step call : * <blockquote><pre>{@code * Flow fl = Flows.currentFlow(); * int var = 100; * // Create a deferred asynchronous computation * FlowFuture<Integer> intFuture = fl.supply(() -> { return 10 * var ;}); * // Chain future computation onto the completion of the previous computation * FlowFuture<String> stringFuture = intFuture.thenApply(String::valueOf); * }</pre></blockquote> * <p> * FlowFutures are non-blocking by default - once a chained computation has been added to the current flow it will run independently of the calling thread once any * dependent FlowFutures are complete (or immediately if it has no dependencies or dependent stages are already completed). * <p> * As computation is executed remotely (in the form of a captured lambda passed as an argument to a FlowFuture method), the <em>captured context</em> of each of the * chained lambdas must be serializable. This includes any captured variables passed into the lambda. * <p> * For instance, in the above example, the variable {@code x} will be serialized and copied into the execution of the captured lambda. * <p> * Generally, if a FlowFuture completes exceptionally, it will propagate its exception to any chained dependencies, however {@link #handle(Flows.SerBiFunction)}, * {@link #whenComplete(Flows.SerBiConsumer)} and {@link #exceptionally(Flows.SerFunction)} allow errors to be caught and handled and * {@link #applyToEither(FlowFuture, Flows.SerFunction)} and {@link #acceptEither(FlowFuture, Flows.SerConsumer)} will only propagate errors if all * dependent futures fail with an error. * * @param <T> the type of this future. All concrete instances of this type must be serializable */ public interface FlowFuture<T> extends Serializable { /** * Applies a transformation to the successfully completed value of this future. * <p> * This method allows simple sequential chaining of functions together - each stage may be executed independently * in a different environment. * <blockquote><pre>{@code * Flow fl = Flows.currentFlow(); * fl.supply(() -> { * }) * }</pre></blockquote> * * @param fn a serializable function to perform once this future is complete * @param <X> the returning type of the function * @return a new future which will complete with the value of this future transformed by {@code fn} * @see java.util.concurrent.CompletionStage#thenApply(java.util.function.Function) */ <X> FlowFuture<X> thenApply(Flows.SerFunction<T, X> fn); /** * Compose a new computation on to the completion of this future * <p> * {@code thenCompose} allows you to dynamically compose one or more steps onto a computation dependent on the value * of a previous step while treating the result of those steps as a single future. * <p> * For instance you may create tail-recursive loops or retrying operations with this call: * <blockquote><pre>{@code * private static FlowFuture<String> doSomethingWithRetry(String input, int attemptsLeft) { * Flow fl = Flows.currentFlow(); * try{ * // some computation that may thrown an error * String result = someUnreliableComputation(input); * return fl.completedValue(result); * }catch(Exception e){ * if(attemptsLeft > 0){ * // delay and retry the computation later. * return rt.delay(5000) * .thenCompose((ignored) -> doSomethingWithRetry(input, attemptsLeft - 1)); * }else{ * throw new RuntimeException("Could not do unreliable computation", e); * } * } * } * }</pre></blockquote> * * If the lambda returns null then the compose stage will fail with a {@link InvalidStageResponseException}. * * @param fn a serializable function that returns a new computation to chain after the completion of this future * @param <X> the type of the future that the composed operation returns * @return a new future which will complete in the same way as the future returned by {@code fn} * @see java.util.concurrent.CompletionStage#thenCompose(java.util.function.Function) */ <X> FlowFuture<X> thenCompose(Flows.SerFunction<T, FlowFuture<X>> fn); /** * Compose a new computation on to the completion of this future to handle errors, * * <p> * {@code exceptionallyCompose} works like a combination of {@link #thenCompose(Flows.SerFunction)} and {@link #exceptionally(Flows.SerFunction)}. This allows an error handler to compose a new computation into the graph in order to recover from errors. * <p> * For instance you may use this to re-try a call : * <blockquote><pre>{@code * private static FlowFuture<String> retryOnError(String input, int attemptsLeft) { * Flow fl = Flows.currentFlow(); * fl.invokeFunction("./unreliableFunction") * .exceptionallyCompose((t)->{ * if(isRecoverable(t) && attemptsLeft > 0){ * return retryOnError(input,attemptsLeft -1); * }else{ * return fl.failedFuture(t); * } * }); * } * }</pre></blockquote> * * If the lambda returns null then the compose stage will fail with a {@link InvalidStageResponseException}. * * @param fn a serializable function that returns a new computation to chain after the completion of this future * @return a new future which will complete in the same way as the future returned by {@code fn} * @see java.util.concurrent.CompletionStage#thenCompose(java.util.function.Function) */ FlowFuture<T> exceptionallyCompose(Flows.SerFunction<Throwable, FlowFuture<T>> fn); /** * Combine the result of this future and another future into a single value when both have completed normally: * <blockquote><pre>{@code * Flow fl = Flows.currentFlow(); * FlowFuture<Integer> f1 = fl.supply(() -> { * int x; * // some complex computation * return x; * }); * * FlowFuture<String> combinedResult = fl.supply(() -> { * int y; * // some complex computation * return x; * }).thenCombine(f1, (a, b) -> return "Result :" + a + ":" + b); * }</pre></blockquote> * <p> * In the case that either future completes with an exception (regardless of whether the other computation succeeded) * or the handler throws an exception then the returned future will complete exceptionally . * * @param other a future to combine with this future * @param fn a function to transform the results of the two futures * @param <U> the type of composed future * @param <X> the return type of the combined value * @return a new future that completes with the result of {@code fn} when both {@code this} and {@code other} have * completed and {@code fn} has been run. * @see java.util.concurrent.CompletionStage#thenCombine(CompletionStage, BiFunction) */ <U, X> FlowFuture<X> thenCombine(FlowFuture<? extends U> other, Flows.SerBiFunction<? super T, ? super U, ? extends X> fn); /** * Perform an action when a computation is complete, regardless of whether it completed successfully or with an error. * <p> * Tha action takes two parameters - representing either the value of the current future or an error if this or any * dependent futures failed. * <p> * Only one of these two parameters will be set, with the other being null. * <blockquote><pre>{@code * Flow fl = Flows.currentFlow(); * FlowFuture<Integer> f1 = fl.supply(() -> { * if(System.currentTimeMillis() % 2L == 0L) { * throw new RuntimeException("Error in stage"); * } * return 100; * }); * f1.whenComplete((val, err) -> { * if(err != null){ * // an error occurred in upstream stage; * }else{ * // the preceding stage was successful * } * }); * }</pre></blockquote> * <p> * {@code whenComplete} is always called when the current stage is complete and does not change the value of current * future - to optionally change the value or to use {@link #handle(Flows.SerBiFunction)} * * @param fn a handler to call when this stage completes * @return a new future that completes as per this future once the action has run. * @see java.util.concurrent.CompletionStage#whenComplete(BiConsumer) */ FlowFuture<T> whenComplete(Flows.SerBiConsumer<T, Throwable> fn); /** * If not already completed, completes this future with the given value. * * <p> * An example is where you want to complete a future with a default value * if it doesn't complete within a given time. * </p> * <blockquote><pre>{@code * * Flow flow = Flows.currentFlow(); * FlowFuture<Integer> f = flow.supply(() -> { * // some computation * }); * * // Complete the future with a default value after a timeout * flow.delay(10, TimeUnit.SECONDS) * .thenAccept(v -> f.complete(1)); * }</pre></blockquote> * * @param value the value to assign to the future * @return true if this invocation caused this future to transition to a completed state, else false */ boolean complete(T value); /** * If not already completed, completes this future exceptionally with the supplied {@link Throwable}. * * <p> * An example is where you want to complete a future exceptionally with a custom * exception if it doesn't complete within a given time. * </p> * <blockquote><pre>{@code * * Flow flow = Flows.currentFlow(); * FlowFuture<Integer> f = flow.supply(() -> { * // some computation * }); * flow.delay(10, TimeUnit.SECONDS) * .thenAccept(v -> f.completeExceptionally(new ComputationTimeoutException())); * }</pre></blockquote> * * @param throwable the @{link Throwable} to complete the future exceptionally with * @return true if this invocation caused this future to transition to a completed state, else false */ boolean completeExceptionally(Throwable throwable); /** * If not already completed, completes this future exceptionally with a @{link java.util.concurrent.CancellationException} * * <p> * An example is where you want to cancel the execution of a future and its * dependents if it doesn't complete within a given time. * </p> * <blockquote><pre>{@code * * Flow flow = Flows.currentFlow(); * FlowFuture<Integer> f = flow.supply(() -> { * // some computation * }).thenAccept(x -> { * // some action * }); * flow.delay(10, TimeUnit.SECONDS) * .thenAccept(v -> f.cancel()); * }</pre></blockquote> * * @return true if this invocation caused this future to transition to a completed state, else false */ boolean cancel(); /** * Perform an action when this future completes successfully. * <p> * This allows you to consume the successful result of a future without returning a new value to future stages. * <blockquote><pre>{@code * Flow fl = Flows.currentFlow(); * DataBase db; * FlowFuture<Integer> f1 = fl.supply(() -> { * int var; * // some computation * return var; * }); * f1.thenAccept((var) -> { * db.storeValue("result", var); * }); * }</pre></blockquote> * <p> * If this or a preceding future completes exceptionally then the resulting future will complete exceptionally * without the handler being called. * * @param fn a handler to call when this future completes successfully * @return a new future that completes when {@code this} has completed and {@code fn} has been run. * @see java.util.concurrent.CompletionStage#thenAccept(Consumer) */ FlowFuture<Void> thenAccept(Flows.SerConsumer<T> fn); /** * Run an action when the first of two futures completes successfully. * <blockquote><pre>{@code * Flow fl = Flows.currentFlow(); * FlowFuture<Integer> f1 = fl.supply(() -> { * int var; * // some long-running computation * return var; * }); * FlowFuture<Integer> f2 = fl.supply(() -> { * int var; * // some long-running computation * return var; * }); * f1.acceptEither(f2, (val) -> { * DataBase db = .... ; * db.storeValue("result", var); * }); * }</pre></blockquote> * <p> * In the case that one future completes exceptionally but the other succeeds then the successful value will be used. * <p> * When both futures complete exceptionally then the returned future will complete exceptionally with one or other of * the exception values (which exception is not defined). * <p> * To transform the value and return it in the future use {@link #applyToEither(FlowFuture, Flows.SerFunction)}. * * @param alt a future to combine with this future * @param fn a handler to call when the first of this and {@code alt} completes successfully * @return a new future that completes normally when either this or {@code alt} completes successfully or completes * exceptionally when both this and {@code alt} complete exceptionally. * @see CompletionStage#acceptEither(CompletionStage, Consumer) */ FlowFuture<Void> acceptEither(FlowFuture<? extends T> alt, Flows.SerConsumer<T> fn); /** * Transform the outcome of the first of two futures to complete successfully. * <blockquote><pre>{@code * Flow fl = Flows.currentFlow(); * FlowFuture<Integer> f1 = fl.supply(() -> { * int var; * // some long-running computation * return var; * }); * FlowFuture<Integer> f2 = fl.supply(() -> { * int var; * // some long-running computation * return var; * }); * f1.applyToEither(f2, (val) -> { * return "Completed result: " + val; * }); * }</pre></blockquote> * <p> * In the case that one future completes exceptionally but the other succeeds then the successful value will be used. * <p> * When both futures complete exceptionally then the returned future will complete exceptionally with one or other * of the exception values (which exception is not defined). * <p> * To accept a value without transforming it use {@link #acceptEither(FlowFuture, Flows.SerConsumer)} * * @param alt a future to combine with this one * @param fn a function to transform the first result of this or {@code alt} with * @param <U> the returned type of the transformation * @return a new future that completes normally when either this or {@code alt} has completed and {@code fn } has * been completed successfully. * @see CompletionStage#applyToEither(CompletionStage, Function) */ <U> FlowFuture<U> applyToEither(FlowFuture<? extends T> alt, Flows.SerFunction<T, U> fn); /** * Perform an action when this and another future have both completed normally: * <blockquote><pre>{@code * Flow fl = Flows.currentFlow(); * FlowFuture<Integer> f1 = fl.supply(() -> { * int x; * // some complex computation * return x; * }); * FlowFuture<String> combinedResult = fl.supply(() -> { * int y; * // some complex computation * return x; * }).thenAcceptBoth(f1, (a, b) -> { * Database db = ....; * db.store("Result", a + b); * }); * }</pre></blockquote> * <p> * In the case that either future completes with an exception (regardless of whether the other computation succeeded) * or the handler throws an exception then the returned future will complete exceptionally. * * @param other a future to combine with this future * @param fn a consumer that accepts the results of {@code this} and {@code other} when both have completed * @param <U> the type of the composed future * @return a new future that completes with the result of {@code fn} when both {@code this} and {@code other} have * completed and {@code fn} has been run. * @see CompletionStage#thenAcceptBoth(CompletionStage, BiConsumer) */ <U> FlowFuture<Void> thenAcceptBoth(FlowFuture<U> other, Flows.SerBiConsumer<T, U> fn); /** * Run an action when this future has completed normally. * <blockquote><pre>{@code * Flow fl = Flows.currentFlow(); * FlowFuture<Integer> f1 = fl.supply(() -> { * int x; * // some complex computation * return x; * }); * f1.thenRun(() -> System.err.println("computation completed")); * }</pre></blockquote> * <p> * When this future completes exceptionally then the returned future will complete exceptionally. * * @param fn a runnable to run when this future has completed normally * @return a future that will complete after this future has completed and {@code fn} has been run * @see CompletionStage#thenRun(Runnable) */ FlowFuture<Void> thenRun(Flows.SerRunnable fn); /** * Invoke a handler when a computation is complete, regardless of whether it completed successfully or with an error - * optionally transforming the resulting value or error to a new value. * <p> * Tha action takes two parameters - representing either the value of the current future or an error if this or any * dependent futures failed. * <p> * Only one of these two parameters will be set, with the other being null. * <blockquote><pre>{@code * Flow fl = Flows.currentFlow(); * FlowFuture<String> f1 = fl.supply(() -> { * if(System.currentTimeMillis() % 2L == 0L) { * throw new RuntimeException("Error in stage"); * } * return 100; * }).handle((val, err) -> { * if(err != null){ * return "An error occurred in this function"; * }else{ * return "The result was good :" + val; * } * }); * }</pre></blockquote> * <p> * {@code handle} is always called when the current stage is complete and may change the value of the returned future - * if you do not need to change this value use {@link #whenComplete(Flows.SerBiConsumer)} * * @param fn a handler to call when this stage completes successfully or with an error * @param <X> The type of the transformed output * @return a new future that completes as per this future once the action has run. * @see java.util.concurrent.CompletionStage#handle(BiFunction) */ <X> FlowFuture<X> handle(Flows.SerBiFunction<? super T, Throwable, ? extends X> fn); /** * Handle exceptional completion of this future and convert exceptions to the original type of this future. * <p> * When an exception occurs within this future (or in a dependent future) - this method allows you to trap and handle * that exception (similarly to a catch block) yeilding a new value to return in place of the error. * <p> * Unlike {@link #handle(Flows.SerBiFunction)} and {@link #whenComplete(Flows.SerBiConsumer)} the handler * function is only called when an exception is raised, otherwise the returned future completes with the same value as * this future. * * <blockquote><pre>{@code * Flow fl = Flows.currentFlow(); * FlowFuture<Integer> f1 = fl.supply(() -> { * if(System.currentTimeMillis() % 2L == 0L) { * throw new RuntimeException("Error in stage"); * } * return 100; * }).exceptionally((err)->{ * return - 1; * }); * }</pre></blockquote> * * @param fn a handler to trap errors * @return a new future that completes with the original value if this future completes successfully or with the * result of calling {@code fn} on the exception value if it completes exceptionally. * @see java.util.concurrent.CompletionStage#exceptionally(Function) */ FlowFuture<T> exceptionally(Flows.SerFunction<Throwable, ? extends T> fn); /** * Get the result of this future * <p> * This method blocks until the current future completes successfully or with an error. * <p> * <em> Warning: </em> This method should be used carefully. Blocking within a fn call (triggered by a HTTP request) * will result in the calling function remaining active while the underlying computation completes. * * @return the completed value of this future. * @throws FlowCompletionException when this future fails with an exception; */ T get(); /** * Get the result of this future, indicating not to wait over the specified timeout. * <p> * This method blocks until either the current future completes or the given timeout period elapses, * in which case it throws a TimeoutException. * <p> * <em> Warning: </em> This method should be used carefully. Blocking within a fn call (triggered by a HTTP request) * will result in the calling function remaining active while the underlying computation completes. * * @param timeout the time period after which this blocking get may time out * @param unit the time unit of the timeout argument * @return the completed value of this future. * @throws FlowCompletionException when this future fails with an exception; * @throws TimeoutException if the future did not complete within at least the specified timeout */ T get(long timeout, TimeUnit unit) throws TimeoutException; /** * Get the result of this future if completed or the provided value if absent. * <p> * This method returns the result of the current future if it is complete. Otherwise, it returns the given * valueIfAbsent. * <p> * * @param valueIfAbsent the value to return if not completed * @return the value of this future, if completed, else the given valueIfAbsent * @throws FlowCompletionException when this future fails with an exception; */ T getNow(T valueIfAbsent); }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-api/src/main/java/com/fnproject/fn/api/flow/HttpMethod.java
flow-api/src/main/java/com/fnproject/fn/api/flow/HttpMethod.java
/* * Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fnproject.fn.api.flow; /** * Enum representing the different HTTP types that can be used to invoke an external function * * @see Flow#invokeFunction */ public enum HttpMethod { GET("GET"), HEAD("HEAD"), POST("POST"), PUT("PUT"), DELETE("DELETE"), OPTIONS("OPTIONS"), PATCH("PATCH"); private final String verb; HttpMethod(String verb) { this.verb = verb; } @Override public String toString() { return this.verb; } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-api/src/main/java/com/fnproject/fn/api/flow/StageTimeoutException.java
flow-api/src/main/java/com/fnproject/fn/api/flow/StageTimeoutException.java
/* * Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fnproject.fn.api.flow; /** * Exception thrown when a completion stage function execution exceeds it configured timeout - * the stage may or may not have completed normally. * * When this exception is raised the fn server has terminated the container hosting the function. */ public class StageTimeoutException extends PlatformException { public StageTimeoutException(String reason) { super(reason); } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-api/src/main/java/com/fnproject/fn/api/flow/Flow.java
flow-api/src/main/java/com/fnproject/fn/api/flow/Flow.java
/* * Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fnproject.fn.api.flow; import com.fnproject.fn.api.Headers; import java.io.Serializable; import java.util.concurrent.TimeUnit; /** * A reference to the Flow object attached to the current invocation context. * <p> * This provides an API that can be used to trigger asynchronous work within a flow. * <p> * The methods return {@link FlowFuture} objects that act as the root of an asynchronous computation * <p> * * @see FlowFuture for details of how to chain subsequent work onto these initial methods. */ public interface Flow extends Serializable { /** * Invoke a fn function and yield the result * <p> * When this function is called, the flow server will send a request with the body to the given function ID within * the fn and provide a future that can chain on the response of the function. * <blockquote><pre>{@code * Flow fl = Flows.currentFlow(); * fl.invokeFunction("myapp/myfn", HttpMethod.GET, Headers.emptyHeaders(), "input".getBytes()) * .thenAccept((result)->{ * System.err.println("Result was " + new String(result)); * }); * <p> * }</pre></blockquote> * <p> * Function IDs should be of the form "APPID/path/in/app" (without leading slash) where APPID may either be a named application or ".", indicating the appID of the current (calling) function. * * @param functionId Function ID of function to invoke - this should be the function ID returned by `fn inspect function appName fnName` * @param method HTTP method to invoke function * @param headers Headers to add to the HTTP request representing the function invocation * @param data input data to function as a byte array - * @return a future which completes normally if the function succeeded and fails if it fails */ FlowFuture<HttpResponse> invokeFunction(String functionId, HttpMethod method, Headers headers, byte[] data); /** * Invoke a function by ID with headers and an empty body * <p> * * @param functionId Function ID of function to invoke - this should be the function ID returned by `fn inspect function appName fnName` * @param method HTTP method to invoke function * @param headers Headers to add to the HTTP request representing the function invocation * @return a future which completes normally if the function succeeded and fails if it fails * @see #invokeFunction(String, HttpMethod, Headers, byte[]) */ default FlowFuture<HttpResponse> invokeFunction(String functionId, HttpMethod method, Headers headers) { return invokeFunction(functionId, method, headers, new byte[]{}); } /** * Invoke a function by ID using input and output coercion * <p> * This currently only maps to JSON via the default JSON mapper in the FDK * * @param functionId Function ID of function to invoke - this should be the function ID returned by `fn inspect function appName fnName` * @param input The input object to send to the function input * @param responseType The expected response type of the target function * @param <T> The Response type * @param <U> The Input type of the function * @return a flow future that completes with the result of the function, or an error if the function invocation failed * @throws IllegalArgumentException if the input cannot be coerced to the callA */ default <T extends Serializable, U> FlowFuture<T> invokeFunction(String functionId, U input, Class<T> responseType) { return invokeFunction(functionId, HttpMethod.POST, Headers.emptyHeaders(), input, responseType); } /** * Invoke a function by ID using input and output coercion and a specified method and headers * <p> * This currently only maps to JSON via the default JSON mapper in the FDK * * @param functionId Function ID of function to invoke - this should be the function ID returned by `fn inspect function appName fnName` * @param method the HTTP method to use for this call * @param headers additional HTTP headers to pass to this function - * @param input The input object to send to the function input * @param responseType The expected response type of the target function * @param <T> The Response type * @param <U> The Input type of the function * @return a flow future that completes with the result of the function, or an error if the function invocation failed * @throws IllegalArgumentException if the input cannot be coerced to the call */ <T extends Serializable, U> FlowFuture<T> invokeFunction(String functionId, HttpMethod method, Headers headers, U input, Class<T> responseType); /** * Invoke a function by ID using input and output coercion, default method (POST) and no response type * <p> * Returns a future that completes with the HttpResponse of the function on success * if the function returns a successful http response, and completes with an {@link FunctionInvocationException} if the function invocation fails with a non-succesful http status * <p> * This currently only maps to JSON via the default JSON mapper in the FDK * * @param functionId Function ID of function to invoke - this should be the function ID returned by `fn inspect function appName fnName` * @param input The input object to send to the function input * @param <U> The Input type of the function * @return a flow future that completes with the result of the function, or an error if the function invocation failed * @throws IllegalArgumentException if the input cannot be coerced to the call */ default <U> FlowFuture<HttpResponse> invokeFunction(String functionId, U input) { return invokeFunction(functionId, HttpMethod.POST, Headers.emptyHeaders(), input); } /** * Invoke a function by ID using input and output coercion and a specified method and headers * <p> * Returns a future that completes with the HttpResponse of the function on success * if the function returns a successful http response, and completes with an {@link FunctionInvocationException} if the function invocation fails with a non-succesful http status * <p> * This currently only maps to JSON via the default JSON mapper in the FDK * * @param functionId Function ID of function to invoke - this should be the function ID returned by `fn inspect function appName fnName` * @param method the HTTP method to use for this call * @param headers additional HTTP headers to pass to this function - * @param input The input object to send to the function input * @param <U> The Input type of the function * @return a flow future that completes with the result of the function, or an error if the function invocation failed * @throws IllegalArgumentException if the input cannot be coerced to the call */ <U> FlowFuture<HttpResponse> invokeFunction(String functionId, HttpMethod method, Headers headers, U input); /** * Invoke a function by ID with no headers * <p> * * @param functionId Function ID of function to invoke - this should be the function ID returned by `fn inspect function appName fnName` * @param method HTTP method to invoke function * @return a future which completes normally if the function succeeded and fails if it fails * @see #invokeFunction(String, HttpMethod, Headers, byte[]) */ default FlowFuture<HttpResponse> invokeFunction(String functionId, HttpMethod method) { return invokeFunction(functionId, method, Headers.emptyHeaders(), new byte[]{}); } /** * Invoke an asynchronous task that yields a value * <blockquote><pre>{@code * Flow fl = Flows.currentFlow(); * fl.supply(()->{ * int someVal * someVal = ... // some long running computation. * return someVal; * }).thenAccept((val)->{ * System.err.println("Result was " + val); * }); * }</pre></blockquote> * * @param c a callable value to invoke via a flow * @param <T> the type of the future * @return a com.fnproject.fn.api.flow.FlowFuture on */ <T> FlowFuture<T> supply(Flows.SerCallable<T> c); /** * Invoke an asynchronous task that does not yield a value * <blockquote><pre>{@code * Flow fl = Flows.currentFlow(); * fl.supply(()->{ * System.err.println("I have run asynchronously"); * }); * <p> * }</pre></blockquote> * * @param runnable a serializable runnable object * @return a completable future that yields when the runnable completes */ FlowFuture<Void> supply(Flows.SerRunnable runnable); /** * Create a future that completes successfully after a specified delay * <blockquote><pre>{@code * Flow fl = Flows.currentFlow(); * fl.delay(5,TimeUnit.Seconds) * .thenAccept((ignored)->{ * System.err.println("I have run asynchronously"); * }); * }</pre></blockquote> * * @param i amount to delay * @param tu time unit * @return a completable future that completes when the delay expires */ FlowFuture<Void> delay(long i, TimeUnit tu); /** * Create a completed future for a specified value. * <blockquote><pre>{@code * Flow fl = Flows.currentFlow(); * fl.delay(5,TimeUnit.Seconds) * .thenCompose((ignored)->{ * if(shouldRunFn){ * return rt.invokeAsync("testapp/testfn","input".getBytes()).thenApply(String::new); * }else{ * return rt.completedValue("some value"); * } * }) * .thenAccept((x)->System.err.println("Result " + x)); * }</pre></blockquote> * * @param value a value to assign to the futures * @param <T> the type of the future value * @return a completed flow future based on the specified value */ <T> FlowFuture<T> completedValue(T value); /** * Create a completed future that propagates a failed value * <blockquote><pre>{@code * Flow fl = Flows.currentFlow(); * fl.delay(5,TimeUnit.Seconds) * .thenCompose((ignored)->{ * if(shouldRunFn){ * return rt.invokeAsync("testapp/testfn","input".getBytes()).thenApply(String::new); * }else{ * return rt.failedFuture(new RuntimeException("Immediate Failure")); * } * }) * .whenComplete((x,t)->{ * if (t !=null){ * // Will print "Immediate Failure"; * System.err.println("error in flow", t.getMessage()); * }else{ * System.err.println("Success! , x); * } * }); * }</pre></blockquote> * * @param ex an exception to publish to the future * @param <T> the type of the future * @return a future that always completes with the specified exception */ <T> FlowFuture<T> failedFuture(Throwable ex); /** * Create an uncompleted future * * @param <T> the type of the future * @return a flow future that can only be completed via {@link FlowFuture#complete(Object)} or {@link FlowFuture#completeExceptionally(Throwable)} */ <T> FlowFuture<T> createFlowFuture(); /** * Wait for all a list of tasks to complete * <blockquote><pre>{@code * Flow fl = Flows.currentFlow(); * FlowFuture<Integer> f1 = fl.delay(5, TimeUnit.SECONDS).thenApply((ignored)-> 10); * FlowFuture<String> f2 = fl.delay(3, TimeUnit.SECONDS).thenApply((ignored)-> "Hello"); * FlowFuture<Void> f3 = fl.delay(1, TimeUnit.SECONDS); * fl.allOf(f1,f2,f3) * .thenAccept((ignored)->{ * System.err.println("all done"); * }); * }</pre></blockquote> * The resulting future will complete successfully if all provided futures complete successfully and will complete exception as soon as any of the provided futures do. * * @param flowFutures a list of futures to aggregate, must contain at least one future. * @return a future that completes when all futures are complete and fails when any one fails */ FlowFuture<Void> allOf(FlowFuture<?>... flowFutures); /** * Wait for any of a list of tasks to complete * <blockquote><pre>{@code * Flow fl = Flows.currentFlow(); * FlowFuture<Integer> f1 = fl.delay(5, TimeUnit.SECONDS).thenApply((ignored)-> 10); * FlowFuture<String> f2 = fl.delay(3, TimeUnit.SECONDS).thenApply((ignored)-> "Hello"); * FlowFuture<Void> f3 = fl.supply(()->throw new RuntimeException("err")); * fl.anyOf(f1,f2,f3) * .thenAccept((ignored)->{ * System.err.println("at least one done"); * }); * }</pre></blockquote> * The resulting future will complete successfully as soon as any of the provided futures completes successfully and only completes exceptionally if all provided futures do. * * @param flowFutures a list of futures to aggregate, must contain at least one future * @return a future that completes when all futures are complete and fails when any one fails */ FlowFuture<Object> anyOf(FlowFuture<?>... flowFutures); /** * Represents the possible end states of a Flow object, i.e. of the whole collection of tasks in the flow. * <ul> * <li>UNKNOWN indicates that the state of the flow is unknown or invalid</li> * <li>SUCCEEDED indicates that the flow ran to completion (i.e. all stages completed successfully or exceptionally)</li> * <li>FAILED indicates that the flow failed during its execution, e.g. due to corrupted internal state</li> * <li>CANCELLED indicates that the flow was cancelled by the user</li> * <li>KILLED indicates that the flow was killed by the user</li> * </ul> */ enum FlowState { UNKNOWN, SUCCEEDED, FAILED, CANCELLED, KILLED } /** * Adds a termination hook that will be executed upon completion of the whole flow; the provided hook will * received input according to how the flow terminated. * <p> * The framework will make a best effort attempt to execute the termination hooks in LIFO order with respect to when * they were added. * <blockquote><pre>{@code * Flow fl = Flows.currentFlow(); * fl.addTerminationHook( (ignored) -> { System.err.println("Flow terminated"); } ) * .addTerminationHook( (endState) -> { System.err.println("End state was " + endState.asText()); } ); * }</pre></blockquote> * This example will first run a stage that prints the end state, and then run a stage that prints 'Flow terminated'. * * @param hook The code to execute * @return This same Flow, so that calls can be chained */ Flow addTerminationHook(Flows.SerConsumer<FlowState> hook); }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-api/src/main/java/com/fnproject/fn/api/flow/FlowCompletionException.java
flow-api/src/main/java/com/fnproject/fn/api/flow/FlowCompletionException.java
/* * Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fnproject.fn.api.flow; /** * Exception thrown when a blocking operation on a flow fails - this corresponds to a * {@link java.util.concurrent.CompletionException} in {@link java.util.concurrent.CompletableFuture} calls */ public class FlowCompletionException extends RuntimeException { /** * If an exception was raised from within a stage, this will be the wrapped cause. * @param t The user exception */ public FlowCompletionException(Throwable t) { super(t); } public FlowCompletionException(String message) { super(message); } public FlowCompletionException(String message, Throwable t) { super(message, t); } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-api/src/main/java/com/fnproject/fn/api/flow/WrappedFunctionException.java
flow-api/src/main/java/com/fnproject/fn/api/flow/WrappedFunctionException.java
/* * Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fnproject.fn.api.flow; import java.io.Serializable; /** * Wrapped exception where the root cause of a function failure was not serializable. * * This exposes the type of the original exception via {@link #getOriginalExceptionType()} and preserves the original exception stacktrace. * */ public final class WrappedFunctionException extends RuntimeException implements Serializable { private final Class<?> originalExceptionType; public WrappedFunctionException(Throwable cause){ super(cause.getMessage()); this.setStackTrace(cause.getStackTrace()); this.originalExceptionType = cause.getClass(); } /** * Exposes the type of the original error * @return the class of the opriginal exception type; */ public Class<?> getOriginalExceptionType() { return originalExceptionType; } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/flow-api/src/main/java/com/fnproject/fn/api/flow/StageInvokeFailedException.java
flow-api/src/main/java/com/fnproject/fn/api/flow/StageInvokeFailedException.java
/* * Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fnproject.fn.api.flow; /** * Exception thrown when a a completion stage invocation failed within Fn - the stage may or may not have been invoked * and that invocation may or may not have completed. */ public class StageInvokeFailedException extends PlatformException { public StageInvokeFailedException(String reason) { super(reason); } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events/src/test/java/com/fnproject/events/APIGatewayFunctionTest.java
fn-events/src/test/java/com/fnproject/events/APIGatewayFunctionTest.java
package com.fnproject.events; import static org.junit.Assert.assertEquals; import com.fnproject.events.testfns.apigatewayfns.APIGatewayTestFunction; import com.fnproject.events.testfns.apigatewayfns.ListAPIGatewayTestFunction; import com.fnproject.events.testfns.apigatewayfns.StringAPIGatewayTestFunction; import com.fnproject.events.testfns.apigatewayfns.UncheckedAPIGatewayTestFunction; import com.fnproject.fn.testing.FnTestingRule; import org.junit.Rule; import org.junit.Test; public class APIGatewayFunctionTest { @Rule public final FnTestingRule fnRule = FnTestingRule.createDefault(); @Test public void testStringHandler() { fnRule .givenEvent() .withHeader("Fn-Http-H-Custom-Header", "headerValue") .withHeader("Fn-Http-Method", "POST") .withHeader("Fn-Http-Request-Url", "/v1?param1=value%20with%20spaces") .withBody("plain string body") .enqueue(); fnRule.thenRun(StringAPIGatewayTestFunction.class, "handler"); assertEquals("test response", fnRule.getOnlyResult().getBodyAsString()); assertEquals("200", fnRule.getOnlyResult().getHeaders().get("Fn-Http-Status").get()); assertEquals("headerValue", fnRule.getOnlyResult().getHeaders().get("Fn-Http-H-Custom-Header").get()); } @Test public void testObjectHandler() { fnRule .givenEvent() .withHeader("Fn-Http-H-Custom-Header", "headerValue") .withHeader("Fn-Http-Method", "POST") .withHeader("Fn-Http-Request-Url", "/v1?param1=value%20with%20spaces") .withBody("{\"name\":\"chicken\",\"age\":2}") .enqueue(); fnRule.thenRun(APIGatewayTestFunction.class, "handler"); assertEquals("{\"brand\":\"ford\",\"wheels\":4}", fnRule.getOnlyResult().getBodyAsString()); } @Test public void testNullObjectPropertyHandler() { fnRule .givenEvent() .withHeader("Fn-Http-H-Custom-Header", "headerValue") .withHeader("Fn-Http-Method", "POST") .withHeader("Fn-Http-Request-Url", "/v1?param1=value%20with%20spaces") .withBody("{\"age\":2}") .enqueue(); fnRule.thenRun(APIGatewayTestFunction.class, "handler"); assertEquals("{\"brand\":\"ford\",\"wheels\":4}", fnRule.getOnlyResult().getBodyAsString()); } @Test public void testListObjectHandler() { fnRule .givenEvent() .withHeader("Fn-Http-H-Custom-Header", "headerValue") .withHeader("Fn-Http-Method", "POST") .withHeader("Fn-Http-Request-Url", "/v1?param1=value%20with%20spaces") .withBody("[{\"name\":\"chicken\",\"age\":2}]") .enqueue(); fnRule.thenRun(ListAPIGatewayTestFunction.class, "handler"); assertEquals("[{\"brand\":\"ford\",\"wheels\":4}]", fnRule.getOnlyResult().getBodyAsString()); } @Test public void testUncheckedHandler() { fnRule .givenEvent() .withHeader("Fn-Http-H-Custom-Header", "headerValue") .withHeader("Fn-Http-Method", "POST") .withHeader("Fn-Http-Request-Url", "/v1?param1=value%20with%20spaces") .withBody("plain string body") .enqueue(); fnRule.thenRun(UncheckedAPIGatewayTestFunction.class, "handler"); assertEquals("test response", fnRule.getOnlyResult().getBodyAsString()); } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events/src/test/java/com/fnproject/events/NotificationFunctionTest.java
fn-events/src/test/java/com/fnproject/events/NotificationFunctionTest.java
package com.fnproject.events; import static org.junit.Assert.assertEquals; import com.fnproject.events.testfns.notification.NotificationObjectTestFunction; import com.fnproject.events.testfns.notification.NotificationStringTestFunction; import com.fnproject.fn.testing.FnTestingRule; import org.junit.Rule; import org.junit.Test; public class NotificationFunctionTest { @Rule public final FnTestingRule fnRule = FnTestingRule.createDefault(); @Test public void testNotificationTestFunction() { fnRule .givenEvent() .withBody("{\"name\":\"foo\",\"age\":3}") .enqueue(); fnRule.thenRun(NotificationObjectTestFunction.class, "handler"); int exitCode = fnRule.getLastExitCode(); assertEquals(0, exitCode); } @Test public void testNotificationStringTestFunction() { fnRule .givenEvent() .withBody("test string") .enqueue(); fnRule.thenRun(NotificationStringTestFunction.class, "handler"); int exitCode = fnRule.getLastExitCode(); assertEquals(0, exitCode); } @Test public void testBlankNotificationStringTestFunction() { fnRule .givenEvent() .withBody("") .enqueue(); fnRule.thenRun(NotificationStringTestFunction.class, "handler"); int exitCode = fnRule.getLastExitCode(); assertEquals(0, exitCode); } @Test public void testBlankNotificationWithoutBodyTestFunction() { fnRule .givenEvent() .enqueue(); fnRule.thenRun(NotificationStringTestFunction.class, "handler"); int exitCode = fnRule.getLastExitCode(); assertEquals(0, exitCode); } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events/src/test/java/com/fnproject/events/ConnectorHubFunctionTest.java
fn-events/src/test/java/com/fnproject/events/ConnectorHubFunctionTest.java
package com.fnproject.events; import static org.junit.Assert.assertEquals; import java.util.Base64; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fnproject.events.testfns.Animal; import com.fnproject.events.testfns.connectorhub.LoggingSourceTestFunction; import com.fnproject.events.testfns.connectorhub.MonitorSourceTestFunction; import com.fnproject.events.testfns.connectorhub.QueueSourceObjectTestFunction; import com.fnproject.events.testfns.connectorhub.QueueSourceStringTestFunction; import com.fnproject.events.testfns.connectorhub.StreamingSourceObjectTestFunction; import com.fnproject.events.testfns.connectorhub.StreamingSourceStringTestFunction; import com.fnproject.fn.testing.FnTestingRule; import org.junit.Rule; import org.junit.Test; public class ConnectorHubFunctionTest { @Rule public final FnTestingRule fnRule = FnTestingRule.createDefault(); @Test public void testMonitorSourceTestFunction() { fnRule .givenEvent() .withBody("[\n" + " {\n" + " \"namespace\":\"oci_computeagent\",\n" + " \"compartmentId\":\"ocid1.tenancy.oc1..exampleuniqueID\",\n" + " \"name\":\"DiskBytesRead\",\n" + " \"dimensions\":{\n" + " \"resourceId\":\"ocid1.instance.region1.phx.exampleuniqueID\"\n" + " },\n" + " \"metadata\":{\n" + " \"unit\":\"bytes\"\n" + " },\n" + " \"datapoints\":[\n" + " {\n" + " \"timestamp\":\"1761318377414\",\n" + " \"value\":10.4\n" + " },\n" + " {\n" + " \"timestamp\":\"1761318377414\",\n" + " \"value\":11.3\n" + " }\n" + " ]\n" + " }\n" + "]") .enqueue(); fnRule.thenRun(MonitorSourceTestFunction.class, "handler"); int exitCode = fnRule.getLastExitCode(); assertEquals(0, exitCode); } @Test public void testEmptyMonitorSourceTestFunction() { fnRule .givenEvent() .withBody("[]") .enqueue(); fnRule.thenRun(MonitorSourceTestFunction.class, "handler"); int exitCode = fnRule.getLastExitCode(); assertEquals(0, exitCode); } @Test public void testLoggingSourceTestFunction() { fnRule .givenEvent() .withBody("[\n" + " {\n" + " \"data\": {\n" + " \"applicationId\": \"ocid1.fnapp.oc1.abc\",\n" + " \"containerId\": \"n/a\",\n" + " \"functionId\": \"ocid1.fnfunc.oc1.abc\",\n" + " \"message\": \"Received function invocation request\",\n" + " \"opcRequestId\": \"/abc/def\",\n" + " \"requestId\": \"/def/abc\",\n" + " \"src\": \"stdout\"\n" + " },\n" + " \"id\": \"abc-zyx\",\n" + " \"oracle\": {\n" + " \"compartmentid\": \"ocid1.tenancy.oc1..xyz\",\n" + " \"ingestedtime\": \"2025-10-23T15:45:19.457Z\",\n" + " \"loggroupid\": \"ocid1.loggroup.oc1.abc\",\n" + " \"logid\": \"ocid1.log.oc1.def\",\n" + " \"tenantid\": \"ocid1.tenancy.oc1..xyz\"\n" + " },\n" + " \"source\": \"your-log\",\n" + " \"specversion\": \"1.0\",\n" + " \"subject\": \"schedule\",\n" + " \"time\": \"2025-10-23T15:45:17.239Z\",\n" + " \"type\": \"com.oraclecloud.functions.application.functioninvoke\"\n" + " }\n" + "]") .enqueue(); fnRule.thenRun(LoggingSourceTestFunction.class, "handler"); int exitCode = fnRule.getLastExitCode(); assertEquals(0, exitCode); } @Test public void testEmptyLoggingSourceTestFunction() { fnRule .givenEvent() .withBody("[]") .enqueue(); fnRule.thenRun(LoggingSourceTestFunction.class, "handler"); int exitCode = fnRule.getLastExitCode(); assertEquals(0, exitCode); } @Test public void testStreamingSourceStringTestFunction() { fnRule .givenEvent() .withBody("[" + "{\"stream\":\"stream-name\"," + "\"partition\":\"0\"," + "\"key\":null," + "\"value\":\"U2VudCBhIHBsYWluIG1lc3NhZ2U=\"," + "\"offset\":3," + "\"timestamp\":1761223385480" + "}" + "]") .enqueue(); fnRule.thenRun(StreamingSourceStringTestFunction.class, "handler"); int exitCode = fnRule.getLastExitCode(); assertEquals(0, exitCode); } @Test public void testEmptyStreamingSourceStringTestFunction() { fnRule .givenEvent() .withBody("[]") .enqueue(); fnRule.thenRun(StreamingSourceStringTestFunction.class, "handler"); int exitCode = fnRule.getLastExitCode(); assertEquals(0, exitCode); } @Test public void testStreamingSourceObjectTestFunction() throws JsonProcessingException { Animal animal = new Animal("foo", 4); String encodedAnimal = Base64.getEncoder().encodeToString(new ObjectMapper().writeValueAsBytes(animal)); fnRule .givenEvent() .withBody("[" + "{\"stream\":\"stream-name\"," + "\"partition\":\"0\"," + "\"key\":null," + "\"value\":\"" + encodedAnimal + "\"," + "\"offset\":3," + "\"timestamp\":1761223385480" + "}" + "]") .enqueue(); fnRule.thenRun(StreamingSourceObjectTestFunction.class, "handler"); int exitCode = fnRule.getLastExitCode(); assertEquals(0, exitCode); } @Test public void testQueueSourceStringTestFunction() { fnRule .givenEvent() .withBody("[\"a plain string, end\", \"another string\"]") .enqueue(); fnRule.thenRun(QueueSourceStringTestFunction.class, "handler"); int exitCode = fnRule.getLastExitCode(); assertEquals(0, exitCode); } @Test public void testInvalidQueueSourceStringTestFunction() { fnRule .givenEvent() .withBody("[a plain string, end, another string]") .enqueue(); fnRule.thenRun(QueueSourceStringTestFunction.class, "handler"); int exitCode = fnRule.getLastExitCode(); assertEquals(2, exitCode); } @Test public void testQueueSourceEmptyTestFunction() { fnRule .givenEvent() .withBody("[]") .enqueue(); fnRule.thenRun(QueueSourceStringTestFunction.class, "handler"); int exitCode = fnRule.getLastExitCode(); assertEquals(0, exitCode); } @Test public void testQueueSourceObjectTestFunction() { fnRule .givenEvent() .withBody("[{\"name\":\"foo\",\"age\":3}]") .enqueue(); fnRule.thenRun(QueueSourceObjectTestFunction.class, "handler"); int exitCode = fnRule.getLastExitCode(); assertEquals(0, exitCode); } @Test public void testSourceWithoutBodyThrows() { fnRule .givenEvent() .enqueue(); fnRule.thenRun(QueueSourceStringTestFunction.class, "handler"); int exitCode = fnRule.getLastExitCode(); assertEquals(2, exitCode); } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events/src/test/java/com/fnproject/events/testfns/Animal.java
fn-events/src/test/java/com/fnproject/events/testfns/Animal.java
package com.fnproject.events.testfns; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; public class Animal { private final String name; private final int age; @JsonCreator public Animal(@JsonProperty("name") String name, @JsonProperty("age") int age) { this.name = name; this.age = age; } public int getAge() { return age; } public String getName() { return name; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Animal animal = (Animal) o; return age == animal.age && Objects.equals(name, animal.name); } @Override public int hashCode() { return Objects.hash(name, age); } @Override public String toString() { return "Animal{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events/src/test/java/com/fnproject/events/testfns/Car.java
fn-events/src/test/java/com/fnproject/events/testfns/Car.java
package com.fnproject.events.testfns; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; public class Car { private final String brand; private final int wheels; @JsonCreator public Car(@JsonProperty("brand") String brand, @JsonProperty("wheels") int wheels) { this.brand = brand; this.wheels = wheels; } public int getWheels() { return wheels; } public String getBrand() { return brand; } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events/src/test/java/com/fnproject/events/testfns/notification/NotificationObjectTestFunction.java
fn-events/src/test/java/com/fnproject/events/testfns/notification/NotificationObjectTestFunction.java
package com.fnproject.events.testfns.notification; import com.fnproject.events.NotificationFunction; import com.fnproject.events.input.NotificationMessage; import com.fnproject.events.testfns.Animal; public class NotificationObjectTestFunction extends NotificationFunction<Animal> { @Override public void handler(NotificationMessage<Animal> batch) { } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events/src/test/java/com/fnproject/events/testfns/notification/NotificationStringTestFunction.java
fn-events/src/test/java/com/fnproject/events/testfns/notification/NotificationStringTestFunction.java
package com.fnproject.events.testfns.notification; import com.fnproject.events.NotificationFunction; import com.fnproject.events.input.NotificationMessage; public class NotificationStringTestFunction extends NotificationFunction<String> { @Override public void handler(NotificationMessage<String> batch) { } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events/src/test/java/com/fnproject/events/testfns/apigatewayfns/ListAPIGatewayTestFunction.java
fn-events/src/test/java/com/fnproject/events/testfns/apigatewayfns/ListAPIGatewayTestFunction.java
package com.fnproject.events.testfns.apigatewayfns; import java.util.Collections; import java.util.List; import com.fnproject.events.APIGatewayFunction; import com.fnproject.events.input.APIGatewayRequestEvent; import com.fnproject.events.output.APIGatewayResponseEvent; import com.fnproject.events.testfns.Animal; import com.fnproject.events.testfns.Car; public class ListAPIGatewayTestFunction extends APIGatewayFunction<List<Animal>, List<Car>> { @Override public APIGatewayResponseEvent<List<Car>> handler(APIGatewayRequestEvent<List<Animal>> requestEvent) { return new APIGatewayResponseEvent.Builder<List<Car>>() .body(Collections.singletonList(new Car("ford", 4))) .build(); } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events/src/test/java/com/fnproject/events/testfns/apigatewayfns/UncheckedAPIGatewayTestFunction.java
fn-events/src/test/java/com/fnproject/events/testfns/apigatewayfns/UncheckedAPIGatewayTestFunction.java
package com.fnproject.events.testfns.apigatewayfns; import com.fnproject.events.APIGatewayFunction; import com.fnproject.events.input.APIGatewayRequestEvent; import com.fnproject.events.output.APIGatewayResponseEvent; public class UncheckedAPIGatewayTestFunction extends APIGatewayFunction { @Override public APIGatewayResponseEvent handler(APIGatewayRequestEvent requestEvent) { return new APIGatewayResponseEvent.Builder() .body("test response") .build(); } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events/src/test/java/com/fnproject/events/testfns/apigatewayfns/APIGatewayTestFunction.java
fn-events/src/test/java/com/fnproject/events/testfns/apigatewayfns/APIGatewayTestFunction.java
package com.fnproject.events.testfns.apigatewayfns; import com.fnproject.events.APIGatewayFunction; import com.fnproject.events.input.APIGatewayRequestEvent; import com.fnproject.events.output.APIGatewayResponseEvent; import com.fnproject.events.testfns.Animal; import com.fnproject.events.testfns.Car; public class APIGatewayTestFunction extends APIGatewayFunction<Animal, Car> { @Override public APIGatewayResponseEvent<Car> handler(APIGatewayRequestEvent<Animal> requestEvent) { return new APIGatewayResponseEvent.Builder<Car>() .body(new Car("ford", 4)) .build(); } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events/src/test/java/com/fnproject/events/testfns/apigatewayfns/GrandChildGatewayTestFunction.java
fn-events/src/test/java/com/fnproject/events/testfns/apigatewayfns/GrandChildGatewayTestFunction.java
package com.fnproject.events.testfns.apigatewayfns; import com.fnproject.events.input.APIGatewayRequestEvent; import com.fnproject.events.output.APIGatewayResponseEvent; public class GrandChildGatewayTestFunction extends StringAPIGatewayTestFunction { @Override public APIGatewayResponseEvent<String> handler(APIGatewayRequestEvent<String> requestEvent) { return super.handler(requestEvent); } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events/src/test/java/com/fnproject/events/testfns/apigatewayfns/StringAPIGatewayTestFunction.java
fn-events/src/test/java/com/fnproject/events/testfns/apigatewayfns/StringAPIGatewayTestFunction.java
package com.fnproject.events.testfns.apigatewayfns; import com.fnproject.events.APIGatewayFunction; import com.fnproject.events.input.APIGatewayRequestEvent; import com.fnproject.events.output.APIGatewayResponseEvent; public class StringAPIGatewayTestFunction extends APIGatewayFunction<String, String> { @Override public APIGatewayResponseEvent<String> handler(APIGatewayRequestEvent<String> requestEvent) { return new APIGatewayResponseEvent.Builder<String>() .body("test response") .statusCode(200) .headers(requestEvent.getHeaders()) .build(); } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events/src/test/java/com/fnproject/events/testfns/connectorhub/QueueSourceStringTestFunction.java
fn-events/src/test/java/com/fnproject/events/testfns/connectorhub/QueueSourceStringTestFunction.java
package com.fnproject.events.testfns.connectorhub; import com.fnproject.events.ConnectorHubFunction; import com.fnproject.events.input.ConnectorHubBatch; public class QueueSourceStringTestFunction extends ConnectorHubFunction<String> { @Override public void handler(ConnectorHubBatch<String> batch) { } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events/src/test/java/com/fnproject/events/testfns/connectorhub/StreamingSourceObjectTestFunction.java
fn-events/src/test/java/com/fnproject/events/testfns/connectorhub/StreamingSourceObjectTestFunction.java
package com.fnproject.events.testfns.connectorhub; import com.fnproject.events.ConnectorHubFunction; import com.fnproject.events.input.ConnectorHubBatch; import com.fnproject.events.input.sch.StreamingData; import com.fnproject.events.testfns.Animal; public class StreamingSourceObjectTestFunction extends ConnectorHubFunction<StreamingData<Animal>> { @Override public void handler(ConnectorHubBatch<StreamingData<Animal>> batch) { } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events/src/test/java/com/fnproject/events/testfns/connectorhub/QueueSourceObjectTestFunction.java
fn-events/src/test/java/com/fnproject/events/testfns/connectorhub/QueueSourceObjectTestFunction.java
package com.fnproject.events.testfns.connectorhub; import com.fnproject.events.ConnectorHubFunction; import com.fnproject.events.input.ConnectorHubBatch; import com.fnproject.events.testfns.Animal; public class QueueSourceObjectTestFunction extends ConnectorHubFunction<Animal> { @Override public void handler(ConnectorHubBatch<Animal> batch) { } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events/src/test/java/com/fnproject/events/testfns/connectorhub/StreamingSourceStringTestFunction.java
fn-events/src/test/java/com/fnproject/events/testfns/connectorhub/StreamingSourceStringTestFunction.java
package com.fnproject.events.testfns.connectorhub; import com.fnproject.events.ConnectorHubFunction; import com.fnproject.events.input.ConnectorHubBatch; import com.fnproject.events.input.sch.StreamingData; import com.fnproject.events.testfns.Animal; public class StreamingSourceStringTestFunction extends ConnectorHubFunction<StreamingData<String >> { @Override public void handler(ConnectorHubBatch<StreamingData<String>> batch) { } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events/src/test/java/com/fnproject/events/testfns/connectorhub/MonitorSourceTestFunction.java
fn-events/src/test/java/com/fnproject/events/testfns/connectorhub/MonitorSourceTestFunction.java
package com.fnproject.events.testfns.connectorhub; import com.fnproject.events.ConnectorHubFunction; import com.fnproject.events.input.ConnectorHubBatch; import com.fnproject.events.input.sch.MetricData; public class MonitorSourceTestFunction extends ConnectorHubFunction<MetricData> { @Override public void handler(ConnectorHubBatch<MetricData> batch) { } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events/src/test/java/com/fnproject/events/testfns/connectorhub/LoggingSourceTestFunction.java
fn-events/src/test/java/com/fnproject/events/testfns/connectorhub/LoggingSourceTestFunction.java
package com.fnproject.events.testfns.connectorhub; import com.fnproject.events.ConnectorHubFunction; import com.fnproject.events.input.ConnectorHubBatch; import com.fnproject.events.input.sch.LoggingData; public class LoggingSourceTestFunction extends ConnectorHubFunction<LoggingData> { @Override public void handler(ConnectorHubBatch<LoggingData> batch) { } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events/src/test/java/com/fnproject/events/testfns/connectorhub/GrandChildMonitorSourceTestFunction.java
fn-events/src/test/java/com/fnproject/events/testfns/connectorhub/GrandChildMonitorSourceTestFunction.java
package com.fnproject.events.testfns.connectorhub; import com.fnproject.events.input.ConnectorHubBatch; import com.fnproject.events.input.sch.MetricData; public class GrandChildMonitorSourceTestFunction extends MonitorSourceTestFunction { @Override public void handler(ConnectorHubBatch<MetricData> batch) { super.handler(batch); } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false
fnproject/fdk-java
https://github.com/fnproject/fdk-java/blob/6275fbbe73c167c221e8be5ab4b838c68966ea5e/fn-events/src/test/java/com/fnproject/events/mapper/APIGatewayRequestEventMapperTest.java
fn-events/src/test/java/com/fnproject/events/mapper/APIGatewayRequestEventMapperTest.java
package com.fnproject.events.mapper; import static org.junit.Assert.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.fnproject.events.input.APIGatewayRequestEvent; import com.fnproject.events.testfns.Animal; import com.fnproject.fn.api.Headers; import com.fnproject.fn.api.QueryParameters; import com.fnproject.fn.api.httpgateway.HTTPGatewayContext; import com.fnproject.fn.runtime.httpgateway.QueryParametersImpl; import org.junit.Before; import org.junit.Test; public class APIGatewayRequestEventMapperTest { private APIGatewayRequestEventMapper mapper; @Before public void setUp() { mapper = new APIGatewayRequestEventMapper(); } @Test public void testQueryParameter() { Map<String, List<String>> params = new HashMap<>(); List<String> paramValues = new ArrayList<>(); paramValues.add("value"); paramValues.add("value2"); params.put("keyTest", paramValues); QueryParametersImpl qp = new QueryParametersImpl(params); HTTPGatewayContext httpGatewayContextMock = mock(HTTPGatewayContext.class); when(httpGatewayContextMock.getQueryParameters()).thenReturn(qp); APIGatewayRequestEvent<String> event = mapper.toApiGatewayRequestEvent(httpGatewayContextMock, ""); QueryParameters queryParameters = event.getQueryParameters(); assertEquals("value", queryParameters.getValues("keyTest").get(0)); assertEquals("value2", queryParameters.getValues("keyTest").get(1)); } @Test public void testGetBody() { String payload = "value"; HTTPGatewayContext httpGatewayContextMock = mock(HTTPGatewayContext.class); APIGatewayRequestEvent<String> event = mapper.toApiGatewayRequestEvent(httpGatewayContextMock, payload); String body = event.getBody(); assertEquals("value", body); } @Test public void testGetBodyObject() { Animal request = new Animal("value", 1); HTTPGatewayContext httpGatewayContextMock = mock(HTTPGatewayContext.class); APIGatewayRequestEvent<Animal> event = mapper.toApiGatewayRequestEvent(httpGatewayContextMock, request); Animal body = event.getBody(); assertEquals(request, body); } @Test public void testGetNullBodyObject() { HTTPGatewayContext httpGatewayContextMock = mock(HTTPGatewayContext.class); APIGatewayRequestEvent<Animal> event = mapper.toApiGatewayRequestEvent(httpGatewayContextMock, null); Animal body = event.getBody(); assertNull(body); } @Test public void testGetMethod() { HTTPGatewayContext httpGatewayContextMock = mock(HTTPGatewayContext.class); when(httpGatewayContextMock.getMethod()).thenReturn("GET"); APIGatewayRequestEvent<String> event = mapper.toApiGatewayRequestEvent(httpGatewayContextMock, ""); String method = event.getMethod(); assertEquals("GET", method); } @Test public void testGetHeaders() { HTTPGatewayContext httpGatewayContextMock = mock(HTTPGatewayContext.class); Headers headers = Headers.emptyHeaders().addHeader("key1", "value1"); when(httpGatewayContextMock.getHeaders()).thenReturn(headers); APIGatewayRequestEvent<String> event = mapper.toApiGatewayRequestEvent(httpGatewayContextMock, ""); Headers eventHeaders = event.getHeaders(); assertEquals("value1", eventHeaders.get("key1").get()); } @Test public void testGetRepeatedHeaders() { HTTPGatewayContext httpGatewayContextMock = mock(HTTPGatewayContext.class); Headers headers = Headers.emptyHeaders().addHeader("repeat", "1", "2"); when(httpGatewayContextMock.getHeaders()).thenReturn(headers); APIGatewayRequestEvent<String> event = mapper.toApiGatewayRequestEvent(httpGatewayContextMock, ""); Headers eventHeaders = event.getHeaders(); assertEquals("1", eventHeaders.getAllValues("repeat").get(0)); assertEquals("2", eventHeaders.getAllValues("repeat").get(1)); } }
java
Apache-2.0
6275fbbe73c167c221e8be5ab4b838c68966ea5e
2026-01-05T02:37:41.914759Z
false