Java Code Examples for com.facebook.react.bridge.ReadableMap

The following examples show how to use com.facebook.react.bridge.ReadableMap. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: react-native-GPay   Source File: UIImplementation.java    License: 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 2
Source Project: magnet-client   Source File: ApiMagnetReact.java    License: 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 3
Source Project: react-native-oauth   Source File: OAuthManagerProviders.java    License: 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 4
Source Project: react-native-sockets   Source File: SocketClient.java    License: 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 5
Source Project: react-native-arcgis-mapview   Source File: RNAGSGraphicsOverlay.java    License: 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 6
Source Project: react-native-pili   Source File: PiliStreamingViewManager.java    License: 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 7
Source Project: react-native-tesseract-ocr   Source File: RNTesseractOcrModule.java    License: 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 8
Source Project: react-native-GPay   Source File: FileReaderModule.java    License: 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 9
Source Project: react-native-amap   Source File: AMapViewManager.java    License: 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 10
Source Project: react-native-GPay   Source File: UIImplementation.java    License: 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 11
Source Project: react-native-android-kit   Source File: TabLayoutView.java    License: 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 12
Source Project: react-native-streetview   Source File: NSTStreetView.java    License: 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 13
Source Project: react-native-android-kit   Source File: TabLayoutView.java    License: 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 14
Source Project: react-native-sqlite-storage   Source File: SQLitePlugin.java    License: 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 15
Source Project: photo-viewer   Source File: Utils.java    License: 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 16
Source Project: react-native-GPay   Source File: NetworkRecordingModuleMock.java    License: 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 17
Source Project: imsdk-android   Source File: QtalkPlugin.java    License: 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 18
Source Project: react-native-GPay   Source File: BlobModule.java    License: 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 19
Source Project: react-native-kakao-links   Source File: RNKakaoLinkModule.java    License: 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 20
@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());
    }
}
 
Example 21
Source Project: react-native-baidu-map   Source File: MapAppModule.java    License: 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 22
Source Project: imsdk-android   Source File: QimRNBModule.java    License: MIT License 5 votes vote down vote up
/**
 * 删除好友
 *
 * @param params
 */
@ReactMethod
public void deleteUserFriend(ReadableMap params) {
    String jid = params.getString("UserId");
    //这个好友可能是跨域的 所以domain不能取内存的 要从jid截取
    ConnectionUtil.getInstance().deleteFriend(QtalkStringUtils.parseId(jid), QtalkStringUtils.parseDomain(jid));
    saveRNActLog("delete friend", "删除好友", "好友名片页");
}
 
Example 23
Source Project: react-native-sqlite-storage   Source File: SQLitePlugin.java    License: MIT License 5 votes vote down vote up
@ReactMethod
public void echoStringValue(ReadableMap args, Callback success, Callback error) {
    String actionAsString = "echoStringValue";
    try {
        this.execute(actionAsString, args, new CallbackContext(success, error));
    } catch (Exception ex){
        error.invoke("Unexpected error");
    }
}
 
Example 24
@ReactMethod
public void getUserData (ReadableMap accountObject, String key, Promise promise) {
	Account account = accounts.get(accountObject.getInt("_index"));
	if(account == null) {
		promise.reject("Invalid account");
		return;
	}

	WritableNativeMap result = new WritableNativeMap();
	result.putString("value", manager.getUserData(account, key));
	promise.resolve(result);
	return;
}
 
Example 25
public void testInvalidIteratorExceptionThrown() {
  mCatalystInstance.getJSModule(TestJSToJavaParametersModule.class).returnMapWithBasicTypes();
  waitForBridgeAndUIIdle();

  List<ReadableMap> calls = mRecordingTestModule.getMapCalls();
  assertEquals(1, calls.size());
  ReadableNativeMap map = (ReadableNativeMap) calls.get(0);
  assertNotNull(map);

  ReadableMapKeySetIterator mapIterator = map.keySetIterator();
  while (mapIterator.hasNextKey()) {
    mapIterator.nextKey();
  }
  assertInvalidIteratorExceptionThrown(mapIterator);
}
 
Example 26
Source Project: imsdk-android   Source File: QimRNBModule.java    License: MIT License 5 votes vote down vote up
/**
 * 群角色管理
 * @param params
 * @param callback
 */
@ReactMethod
public void setGroupAdmin(ReadableMap params, Callback callback){
    Logger.i("setGroupAdmin:" + params.toString());
    String groupId = params.getString("groupId");
    String xmppid = params.getString("xmppid");
    String name = params.getString("name");
    boolean isAdmin = params.getBoolean("isAdmin");
    ConnectionUtil.getInstance().setGroupAdmin(groupId,xmppid,name,isAdmin);
}
 
Example 27
Source Project: react-native-GPay   Source File: UIManagerModule.java    License: MIT License 5 votes vote down vote up
@ReactMethod
public void updateView(int tag, String className, ReadableMap props) {
  if (DEBUG) {
    String message =
        "(UIManager.updateView) tag: " + tag + ", class: " + className + ", props: " + props;
    FLog.d(ReactConstants.TAG, message);
    PrinterHolder.getPrinter().logMessage(ReactDebugOverlayTags.UI_MANAGER, message);
  }
  mUIImplementation.updateView(tag, className, props);
}
 
Example 28
Source Project: react-native-barcode   Source File: RNLBarCodeModule.java    License: MIT License 5 votes vote down vote up
@ReactMethod
public void decode(ReadableMap option, final Promise promise) {
    int decoderID = option.getInt("decoder");
    Decoder decoder = RNLBarCodeUtils.getDecoderByID(decoderID);
    if (decoder == null) {
        promise.reject(RNLBarCodeError.InvokeFailed.toString(),
                "Device doesn't support this decoder");
        return;
    }
    decoder.setFormats(option.getArray("formats"));
    Bitmap image = null;
    if (option.getBoolean("screenshot")) {
        image = RNLBarCodeUtils.takeScreenshot(getCurrentActivity());
        if (image == null) {
            promise.reject(RNLBarCodeError.InvokeFailed.toString(),
                    "Can't take screenshot");
        }
    } else {
        try {
            image = RNLBarCodeUtils.parseImageStr(option.getString("data"));
        } catch (Exception e) {
            promise.reject(RNLBarCodeError.InvokeFailed.toString(),
                    "Parse image failed, reason: " + e.getMessage());
        }
    }
    if (image != null) {
        promise.resolve(decoder.decodeRGBBitmap(image));
    }
    decoder.release();
}
 
Example 29
Source Project: react-native-datetime-picker   Source File: DatePicker.java    License: MIT License 5 votes vote down vote up
public DatePicker(ReadableMap options, Callback callback) {
    final Calendar c = Calendar.getInstance();
    this.callback = callback;
    year = options.hasKey("year") ? options.getInt("year") : c.get(Calendar.YEAR);
    month = options.hasKey("month") ? options.getInt("month") : c.get(Calendar.MONTH);
    day = options.hasKey("day") ? options.getInt("day") : c.get(Calendar.DAY_OF_MONTH);
}
 
Example 30
Source Project: react-native-turbolinks   Source File: NavBarStyle.java    License: MIT License 5 votes vote down vote up
private NavBarStyle(ReadableMap rp) {
    ReadableMap menuIcon = rp.hasKey(MENU_ICON) ? rp.getMap(MENU_ICON) : null;
    this.titleTextColor = rp.hasKey(TITLE_TEXT_COLOR) && !rp.isNull(TITLE_TEXT_COLOR) ? rp.getInt(TITLE_TEXT_COLOR) : null;
    this.subtitleTextColor = rp.hasKey(SUBTITLE_TEXT_COLOR) && !rp.isNull(SUBTITLE_TEXT_COLOR) ? rp.getInt(SUBTITLE_TEXT_COLOR) : null;
    this.barTintColor = rp.hasKey(BAR_TINT_COLOR) && !rp.isNull(BAR_TINT_COLOR) ? rp.getInt(BAR_TINT_COLOR) : null;
    this.menuIcon = menuIcon != null ? Arguments.toBundle(menuIcon) : null;
}