com.facebook.react.bridge.ReadableMap Java Examples

The following examples show how to use com.facebook.react.bridge.ReadableMap. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: QtalkPlugin.java    From imsdk-android with MIT License 6 votes vote down vote up
/**
     * 进行网络请求
     */
    @ReactMethod
    public void getSearchInfo(String url, ReadableMap params, ReadableMap cookie, Callback callback1, final Callback callback2) {
        final WritableNativeMap map = new WritableNativeMap();

        HttpUtil.PostUrl(url, params.toHashMap(), cookie.toHashMap(), new ProtocolCallback.UnitCallback<String>() {
            @Override
            public void onCompleted(String s) {
                map.putBoolean("isOk", true);
                map.putString("responseJson", s);
                callback2.invoke(map);
            }

            @Override
            public void onFailure(String errMsg) {
                map.putBoolean("isOk", false);
                map.putString("message", errMsg);
                callback2.invoke(map);
            }
        });


//
    }
 
Example #2
Source File: OAuthManagerProviders.java    From react-native-oauth with MIT License 6 votes vote down vote up
static public OAuthRequest getRequestForProvider(
  final String providerName,
  final Verb httpVerb,
  final OAuth2AccessToken oa2token,
  final URL url,
  final HashMap<String,Object> cfg,
  @Nullable final ReadableMap params
) {
  final OAuth20Service service =
      OAuthManagerProviders.getApiFor20Provider(providerName, cfg, null, null);

  OAuthConfig config = service.getConfig();
  OAuthRequest request = new OAuthRequest(httpVerb, url.toString(), config);
  String token = oa2token.getAccessToken();

  request = OAuthManagerProviders.addParametersToRequest(request, token, params);

  //
  Log.d(TAG, "Making request for " + providerName + " to add token " + token);
  // Need a way to standardize this, but for now
  if (providerName.equalsIgnoreCase("slack")) {
    request.addParameter("token", token);
  }

  return request;
}
 
Example #3
Source File: SocketClient.java    From react-native-sockets with MIT License 6 votes vote down vote up
SocketClient(ReadableMap params, ReactContext reactContext) {
    //String addr, int port, boolean autoReconnect
    mReactContext = reactContext;
    dstAddress = params.getString("address");
    dstPort = params.getInt("port");
    if (params.hasKey("timeout")) {
        timeout = params.getInt("timeout");
    } else {
        timeout = 60000;
    }
    if (params.hasKey("reconnect")) {
        reconnectOnClose = params.getBoolean("reconnect");
    }
    if (params.hasKey("maxReconnectAttempts")) {
        maxReconnectAttempts = params.getInt("maxReconnectAttempts");
    }
    if (params.hasKey("reconnectDelay")) {
        reconnectDelay = params.getInt("reconnectDelay");
    }

    Thread socketClientThread = new Thread(new SocketClientThread());
    socketClientThread.start();
}
 
Example #4
Source File: ApiMagnetReact.java    From magnet-client with Mozilla Public License 2.0 6 votes vote down vote up
@ReactMethod
public void post(String path, ReadableMap map, final Promise promise) {
    Log.d(TAG, "post");
    Object data = fromReactArgument(map);

    if (data == null) {
        promise.reject("invalid-data-type", "invalid data type");
        return;
    }

    mApiMagnet.post(path, data, new Api.Callback() {
        @Override
        public void resolve(Object result) {
            promise.resolve(toReactArgument(result));
        }

        @Override
        public void reject(String error) {
            promise.reject(error, error);
        }
    });
}
 
Example #5
Source File: UIImplementation.java    From react-native-GPay with MIT License 6 votes vote down vote up
/**
 * Invoked by React to create a new node with a given tag has its properties changed.
 */
public void updateView(int tag, String className, ReadableMap props) {
  ViewManager viewManager = mViewManagers.get(className);
  if (viewManager == null) {
    throw new IllegalViewOperationException("Got unknown view type: " + className);
  }
  ReactShadowNode cssNode = mShadowNodeRegistry.getNode(tag);
  if (cssNode == null) {
    throw new IllegalViewOperationException("Trying to update non-existent view with tag " + tag);
  }

  if (props != null) {
    ReactStylesDiffMap styles = new ReactStylesDiffMap(props);
    cssNode.updateProperties(styles);
    handleUpdateView(cssNode, className, styles);
  }
}
 
Example #6
Source File: RNAGSGraphicsOverlay.java    From react-native-arcgis-mapview with MIT License 6 votes vote down vote up
public RNAGSGraphicsOverlay(ReadableMap rawData, GraphicsOverlay graphicsOverlay) {
    this.referenceId = rawData.getString("referenceId");
    ReadableArray pointImageDictionaryRaw = rawData.getArray("pointGraphics");
    pointImageDictionary = new HashMap<>();
    this.graphicsOverlay = graphicsOverlay;

    for (int i = 0; i < pointImageDictionaryRaw.size(); i++) {
        ReadableMap item = pointImageDictionaryRaw.getMap(i);
        if (item.hasKey("graphicId")) {
            String graphicId = item.getString("graphicId");
            String uri = item.getMap("graphic").getString("uri");
            pointImageDictionary.put(graphicId, uri);
        }
    }
    // Create graphics within overlay
    ReadableArray rawPoints = rawData.getArray("points");
    for (int i = 0; i < rawPoints.size(); i++) {
        addGraphicsLoop(rawPoints.getMap(i));

    }
}
 
Example #7
Source File: PiliStreamingViewManager.java    From react-native-pili with MIT License 6 votes vote down vote up
@ReactProp(name = "profile")
public void setProfile(AspectFrameLayout view, @Nullable ReadableMap profile) {
    ReadableMap video = profile.getMap("video");
    ReadableMap audio = profile.getMap("audio");
    int encodingSize = profile.getInt("encodingSize");

    StreamingProfile.AudioProfile aProfile =
            new StreamingProfile.AudioProfile(audio.getInt("rate"), audio.getInt("bitrate")); //audio sample rate, audio bitrate
    StreamingProfile.VideoProfile vProfile =
            new StreamingProfile.VideoProfile(video.getInt("fps"), video.getInt("bps"), video.getInt("maxFrameInterval"));//fps bps maxFrameInterval
    StreamingProfile.AVProfile avProfile = new StreamingProfile.AVProfile(vProfile, aProfile);
    mProfile.setAVProfile(avProfile);
    mProfile.setEncodingSizeLevel(encodingSize);
    mMediaStreamingManager.setStreamingProfile(mProfile);

}
 
Example #8
Source File: RNTesseractOcrModule.java    From react-native-tesseract-ocr with MIT License 6 votes vote down vote up
@ReactMethod
public void recognize(String path, String lang, @Nullable ReadableMap tessOptions, Promise promise) {
	prepareTesseract();

	Log.d(REACT_CLASS, "Start ocr images");

	try {
		BitmapFactory.Options options = new BitmapFactory.Options();

		// TODO:
		// Check image size before use inSampleSize (maybe this could help) --> https://goo.gl/4MvBvB
		// considering that when inSampleSize is used (usually to save memory) the ocr quality decreases

		//options.inSampleSize = 4; //inSampleSize documentation --> http://goo.gl/KRrlvi
		Bitmap bitmap = BitmapFactory.decodeFile(path, options);

		String result = extractText(bitmap, lang, tessOptions);

		promise.resolve(result);

	} catch (Exception e) {
		Log.e(REACT_CLASS, e.getMessage());
		promise.reject("An error occurred", e.getMessage());
	}
}
 
Example #9
Source File: FileReaderModule.java    From react-native-GPay with MIT License 6 votes vote down vote up
@ReactMethod
public void readAsText(ReadableMap blob, String encoding, Promise promise) {

  byte[] bytes = getBlobModule().resolve(
      blob.getString("blobId"),
      blob.getInt("offset"),
      blob.getInt("size"));

  if (bytes == null) {
    promise.reject(ERROR_INVALID_BLOB, "The specified blob is invalid");
    return;
  }

  try {
    promise.resolve(new String(bytes, encoding));
  } catch (Exception e) {
    promise.reject(e);
  }
}
 
Example #10
Source File: AMapViewManager.java    From react-native-amap with MIT License 6 votes vote down vote up
@ReactProp(name = "region")
public void setRegion(MapView mapView, @Nullable ReadableMap region) {
    if (region == null) return;
    AMap map = mapView.getMap();
    Double lat = region.getDouble("latitude");
    Double lng = region.getDouble("longitude");
    Double lngDelta = region.getDouble("longitudeDelta");
    Double latDelta = region.getDouble("latitudeDelta");
    LatLngBounds bounds = new LatLngBounds(
        new LatLng(lat - latDelta / 2, lng - lngDelta / 2), // southwest
        new LatLng(lat + latDelta / 2, lng + lngDelta / 2)  // northeast
    );
    if (mapView.getHeight() <= 0 || mapView.getWidth() <= 0) {
        map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 10));
        boundsToMove = bounds;
    } else {
        map.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 0));
    }
}
 
Example #11
Source File: UIImplementation.java    From react-native-GPay with MIT License 6 votes vote down vote up
/**
 * Invoked by React to create a new node with a given tag, class name and properties.
 */
public void createView(int tag, String className, int rootViewTag, ReadableMap props) {
  ReactShadowNode cssNode = createShadowNode(className);
  ReactShadowNode rootNode = mShadowNodeRegistry.getNode(rootViewTag);
  Assertions.assertNotNull(rootNode, "Root node with tag " + rootViewTag + " doesn't exist");
  cssNode.setReactTag(tag);
  cssNode.setViewClassName(className);
  cssNode.setRootTag(rootNode.getReactTag());
  cssNode.setThemedContext(rootNode.getThemedContext());

  mShadowNodeRegistry.addNode(cssNode);

  ReactStylesDiffMap styles = null;
  if (props != null) {
    styles = new ReactStylesDiffMap(props);
    cssNode.updateProperties(styles);
  }

  handleCreateView(cssNode, rootViewTag, styles);
}
 
Example #12
Source File: TabLayoutView.java    From react-native-android-kit with MIT License 6 votes vote down vote up
/**
 * Ajout Tab contribuée sans Custom View:
 *
 * @param configMap
 * @return
 */
public boolean attachTab(ReadableMap configMap) {
	if (configMap != null) {
		Tab tab = this.newTab();
		if (configMap.hasKey("text")) {
			tab.setText(configMap.getString("text"));
		}
		if (configMap.hasKey("icon")) {
			tab.setIcon(ContextCompat.getDrawable(this.getContext(), Drawable.getID(this, configMap.getString("icon"))));
		}

		this.addTab(tab);

		return true;
	}
	return false;
}
 
Example #13
Source File: NSTStreetView.java    From react-native-streetview with MIT License 6 votes vote down vote up
public void setPov(ReadableMap pov) {

        if (pov == null ) return;
        tilt = (float) pov.getDouble("tilt");
        bearing = (float) pov.getDouble("bearing");
        zoom = pov.getInt("zoom");

        long duration = 1000;
         if (bearing > 0 && this.started) {
             StreetViewPanoramaCamera camera = new StreetViewPanoramaCamera.Builder()
             .zoom(zoom)
             .tilt(tilt)
             .bearing(bearing)
             .build();
             panorama.animateTo(camera,duration);
          }

    }
 
Example #14
Source File: TabLayoutView.java    From react-native-android-kit with MIT License 6 votes vote down vote up
/**
 * Ajout Tab contribuée sans Custom View:
 *
 * @param configMap
 * @return
 */
public boolean attachTab(ReadableMap configMap) {
	if (configMap != null) {
		Tab tab = this.newTab();
		if (configMap.hasKey("text")) {
			tab.setText(configMap.getString("text"));
		}
		if (configMap.hasKey("icon")) {
			tab.setIcon(ContextCompat.getDrawable(this.getContext(), Drawable.getID(this, configMap.getString("icon"))));
		}

		this.addTab(tab);

		return true;
	}
	return false;
}
 
Example #15
Source File: SQLitePlugin.java    From react-native-sqlite-storage with MIT License 6 votes vote down vote up
/**
 *
 * @param dbname - The name of the database file
 * @param options - options passed in from JS
 * @param cbc - JS callback context
 */
private void startDatabase(String dbname, ReadableMap options, CallbackContext cbc) {
    // TODO: is it an issue that we can orphan an existing thread?  What should we do here?
    // If we re-use the existing DBRunner it might be in the process of closing...
    DBRunner r = dbrmap.get(dbname);

    // Brody TODO: It may be better to terminate the existing db thread here & start a new one, instead.
    if (r != null) {
        // don't orphan the existing thread; just re-open the existing database.
        // In the worst case it might be in the process of closing, but even that's less serious
        // than orphaning the old DBRunner.
        cbc.success("database started");
    } else {
        r = new DBRunner(dbname, options, cbc);
        dbrmap.put(dbname, r);
        this.getThreadPool().execute(r);
    }
}
 
Example #16
Source File: Utils.java    From photo-viewer with Apache License 2.0 6 votes vote down vote up
/**
 * Converts Facebook's ReadableMap to a Java Map<>
 *
 * @param readableMap The Readable Map to parse
 * @return a Java Map<> to be used in memory
 */
public static Map<String, Object> toMap(@Nullable ReadableMap readableMap) {
    if (readableMap == null) {
        return null;
    }

    ReadableMapKeySetIterator iterator = readableMap.keySetIterator();
    if (!iterator.hasNextKey()) {
        return null;
    }

    Map<String, Object> result = new HashMap<>();
    while (iterator.hasNextKey()) {
        String key = iterator.nextKey();
        result.put(key, toObject(readableMap, key));
    }

    return result;
}
 
Example #17
Source File: NetworkRecordingModuleMock.java    From react-native-GPay with MIT License 6 votes vote down vote up
@ReactMethod
public final void sendRequest(
    String method,
    String url,
    int requestId,
    ReadableArray headers,
    ReadableMap data,
    final String responseType,
    boolean incrementalUpdates,
    int timeout,
    boolean withCredentials) {
  mLastRequestId = requestId;
  mRequestCount++;
  mRequestMethod = method;
  mRequestURL = url;
  mRequestHeaders = headers;
  mRequestData = data;
  if (mRequestListener != null) {
    mRequestListener.onRequest(method, url, headers, data);
  }
  if (mCompleteRequest) {
    onResponseReceived(requestId, mResponseCode, null);
    onDataReceived(requestId, mResponseBody);
    onRequestComplete(requestId, null);
  }
}
 
Example #18
Source File: GoogleFitModule.java    From react-native-google-fit with MIT License 5 votes vote down vote up
@ReactMethod
public void saveHeight(ReadableMap heightSample,
                       Callback errorCallback,
                       Callback successCallback) {

    try {
        BodyHistory bodyHistory = mGoogleFitManager.getBodyHistory();
        bodyHistory.setDataType(DataType.TYPE_HEIGHT);
        successCallback.invoke(bodyHistory.save(heightSample));
    } catch (IllegalViewOperationException e) {
        errorCallback.invoke(e.getMessage());
    }
}
 
Example #19
Source File: RNFitnessModule.java    From react-native-fitness with MIT License 5 votes vote down vote up
private ArrayList<Request> createRequestFromReactArray(ReadableArray permissions){
  ArrayList<Request> requestPermissions = new ArrayList<>();
  int size = permissions.size();
  for(int i = 0; i < size; i++) {
    try {
      ReadableMap singlePermission = permissions.getMap(i);
      final int permissionKind = singlePermission.getInt("kind");
      final int permissionAccess = singlePermission.hasKey("access") ? singlePermission.getInt("access") : FitnessOptions.ACCESS_READ;
      requestPermissions.add(new Request(permissionKind, permissionAccess));
    } catch (NullPointerException e) {
      Log.e(TAG, e.getMessage());
    }
  }
  return requestPermissions;
}
 
Example #20
Source File: ViewManagerPropertyUpdater.java    From react-native-GPay with MIT License 5 votes vote down vote up
public static <T extends ReactShadowNode> void updateProps(T node, ReactStylesDiffMap props) {
  ShadowNodeSetter<T> setter = findNodeSetter(node.getClass());
  ReadableMap propMap = props.mBackingMap;
  ReadableMapKeySetIterator iterator = propMap.keySetIterator();
  while (iterator.hasNextKey()) {
    String key = iterator.nextKey();
    setter.setProperty(node, key, props);
  }
}
 
Example #21
Source File: ReactNativeBiometrics.java    From react-native-biometrics with MIT License 5 votes vote down vote up
@ReactMethod
public void simplePrompt(final ReadableMap params, final Promise promise) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        UiThreadUtil.runOnUiThread(
                new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String cancelButtomText = params.getString("cancelButtonText");
                            String promptMessage = params.getString("promptMessage");

                            AuthenticationCallback authCallback = new SimplePromptCallback(promise);
                            FragmentActivity fragmentActivity = (FragmentActivity) getCurrentActivity();
                            Executor executor = Executors.newSingleThreadExecutor();
                            BiometricPrompt biometricPrompt = new BiometricPrompt(fragmentActivity, executor, authCallback);

                            PromptInfo promptInfo = new PromptInfo.Builder()
                                    .setDeviceCredentialAllowed(false)
                                    .setNegativeButtonText(cancelButtomText)
                                    .setTitle(promptMessage)
                                    .build();
                            biometricPrompt.authenticate(promptInfo);
                        } catch (Exception e) {
                            promise.reject("Error displaying local biometric prompt: " + e.getMessage(), "Error displaying local biometric prompt: " + e.getMessage());
                        }
                    }
                });
    } else {
        promise.reject("Cannot display biometric prompt on android versions below 6.0", "Cannot display biometric prompt on android versions below 6.0");
    }
}
 
Example #22
Source File: GPay.java    From react-native-GPay with MIT License 5 votes vote down vote up
/**
 * Display the Google Pay payment sheet
 */
@ReactMethod
public void show(int environment, ReadableMap requestData, final Promise promise) {

    Activity activity = getCurrentActivity();

    if (activity == null) {
        promise.reject(E_NO_ACTIVITY, "activity is null");
        return;
    }

    this.mRequestPaymentPromise = promise;

    JSONObject paymentDataRequestJson = GPay.getPaymentDataRequest(requestData);
    if (paymentDataRequestJson == null) {
        promise.reject(E_NO_PAYMENT_REQUEST_JSON, "payment data request json is null");
        return;
    }
    PaymentDataRequest request =
            PaymentDataRequest.fromJson(paymentDataRequestJson.toString());
    if (request != null) {
        AutoResolveHelper.resolveTask(
                getPaymentsClient(environment, activity).loadPaymentData(request), activity, LOAD_PAYMENT_DATA_REQUEST_CODE);
    } else {
        promise.reject(E_NO_PAYMENT_REQUEST, "payment data request is null");
    }
}
 
Example #23
Source File: RNKakaoLinkModule.java    From react-native-kakao-links with MIT License 5 votes vote down vote up
private SocialObject createSocialObject(ReadableMap social) {
  SocialObject.Builder socialObject = SocialObject.newBuilder();
  if (social.hasKey("likeCount")) socialObject.setLikeCount(social.getInt("likeCount"));
  if (social.hasKey("commentCount"))
    socialObject.setCommentCount(social.getInt("commentCount"));
  if (social.hasKey("sharedCount")) socialObject.setSharedCount(social.getInt("sharedCount"));
  if (social.hasKey("subscriberCount"))
    socialObject.setSubscriberCount(social.getInt("subscriberCount"));
  if (social.hasKey("viewCount")) socialObject.setViewCount(social.getInt("viewCount"));
  return socialObject.build();
}
 
Example #24
Source File: BlobModule.java    From react-native-GPay with MIT License 5 votes vote down vote up
@ReactMethod
public void sendOverSocket(ReadableMap blob, int id) {
  byte[] data = resolve(blob.getString("blobId"), blob.getInt("offset"), blob.getInt("size"));

  if (data != null) {
    getWebSocketModule().sendBinary(ByteString.of(data), id);
  } else {
    getWebSocketModule().sendBinary((ByteString) null, id);
  }
}
 
Example #25
Source File: AdditionAnimatedNode.java    From react-native-GPay with MIT License 5 votes vote down vote up
public AdditionAnimatedNode(
    ReadableMap config,
    NativeAnimatedNodesManager nativeAnimatedNodesManager) {
  mNativeAnimatedNodesManager = nativeAnimatedNodesManager;
  ReadableArray inputNodes = config.getArray("input");
  mInputNodes = new int[inputNodes.size()];
  for (int i = 0; i < mInputNodes.length; i++) {
    mInputNodes[i] = inputNodes.getInt(i);
  }
}
 
Example #26
Source File: MapUtil.java    From Instabug-React-Native with MIT License 5 votes vote down vote up
public static JSONObject toJSONObject(ReadableMap readableMap) throws JSONException {
    JSONObject jsonObject = new JSONObject();

    ReadableMapKeySetIterator iterator = readableMap.keySetIterator();

    while (iterator.hasNextKey()) {
        String key = iterator.nextKey();
        ReadableType type = readableMap.getType(key);

        switch (type) {
            case Null:
                jsonObject.put(key, null);
                break;
            case Boolean:
                jsonObject.put(key, readableMap.getBoolean(key));
                break;
            case Number:
                jsonObject.put(key, readableMap.getDouble(key));
                break;
            case String:
                jsonObject.put(key, readableMap.getString(key));
                break;
            case Map:
                jsonObject.put(key, MapUtil.toJSONObject(readableMap.getMap(key)));
                break;
            case Array:
                jsonObject.put(key, ArrayUtil.toJSONArray(readableMap.getArray(key)));
                break;
        }
    }

    return jsonObject;
}
 
Example #27
Source File: RCTSplashScreenModule.java    From react-native-smart-splash-screen with MIT License 5 votes vote down vote up
@ReactMethod
public void close(ReadableMap options) {

    int animationType = RCTSplashScreen.UIAnimationNone;
    int duration = 0;
    int delay = 0;

    if(options != null) {
        if(options.hasKey("animationType")) {
            animationType = options.getInt("animationType");
        }
        if(options.hasKey("duration")) {
            duration = options.getInt("duration");
        }
        if(options.hasKey("delay")) {
            delay = options.getInt("delay");
        }
    }

    if(animationType == RCTSplashScreen.UIAnimationNone) {
        delay = 0;
    }

    final int final_animationType = animationType;
    final int final_duration = duration;

    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        public void run() {
            RCTSplashScreen.removeSplashScreen(getCurrentActivity(), final_animationType, final_duration);
        }
    }, delay);
}
 
Example #28
Source File: MapAppModule.java    From react-native-baidu-map with MIT License 5 votes vote down vote up
private RouteParaOption createRouteParaOption(ReadableMap startPoint, ReadableMap endPoint) {
    RouteParaOption paraOption = new RouteParaOption()
            .startPoint(LatLngUtil.fromReadableMap(startPoint))
            .endPoint(LatLngUtil.fromReadableMap(endPoint))
            .busStrategyType(RouteParaOption.EBusStrategyType.bus_recommend_way);
    if (startPoint.hasKey(KEY_NAME)) {
        paraOption.startName(startPoint.getString(KEY_NAME));
    }
    if (endPoint.hasKey(KEY_NAME)) {
        paraOption.endName(endPoint.getString(KEY_NAME));
    }
    return paraOption;
}
 
Example #29
Source File: ActivityResultModule.java    From react-native-activity-result with MIT License 5 votes vote down vote up
@ReactMethod
public void startActivityForResult(int requestCode, String action, ReadableMap data, Promise promise) {
    Activity activity = getReactApplicationContext().getCurrentActivity();
    Intent intent = new Intent(action);
    intent.putExtras(Arguments.toBundle(data));
    activity.startActivityForResult(intent, requestCode);
    mPromises.put(requestCode, promise);
}
 
Example #30
Source File: SegmentAnalyticsModule.java    From react-native-segment-analytics with MIT License 5 votes vote down vote up
@ReactMethod
public void identify(String userId, ReadableMap traits) {
    try {
        Analytics.with(this.getReactApplicationContext()).identify(
            userId,
            toTraits(traits),
            null
        );
    } catch (Exception e) {
        Log.e("SegmentAnalyticsModule", "Failed to identify " + userId + ". " + e.getMessage());
    }
}