Java Code Examples for org.json.JSONObject

The following examples show how to use org.json.JSONObject. 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: RipplePower   Author: cping   File: MarketsRespone.java    License: Apache License 2.0 7 votes vote down vote up
public void from(Object obj) {
	if (obj != null) {
		if (obj instanceof JSONObject) {
			JSONObject result = (JSONObject) obj;
			this.rowkey = result.optString("rowkey");
			this.count = result.optLong("count");
			this.startTime = result.optString("startTime");
			this.endTime = result.optString("endTime");
			this.exchange.copyFrom(result.opt("exchange"));
			this.exchangeRate = result.optDouble("exchangeRate");
			this.total = result.optDouble("total");
			JSONArray arrays = result.optJSONArray("components");
			if (arrays != null) {
				int size = arrays.length();
				for (int i = 0; i < size; i++) {
					MarketComponent marketComponent = new MarketComponent();
					marketComponent.from(arrays.getJSONObject(i));
					components.add(marketComponent);
				}
			}
		}
	}
}
 
Example #2
Source Project: snapdroid   Author: badaix   File: JsonRPC.java    License: GNU General Public License v3.0 6 votes vote down vote up
JSONObject toJson() {
    JSONObject response = new JSONObject();
    try {
        response.put("jsonrpc", "2.0");
        if (error != null)
            response.put("error", error);
        else if (result != null)
            response.put("result", result);
        else
            throw new JSONException("error and result are null");

        response.put("id", id);
        return response;
    } catch (JSONException e) {
        e.printStackTrace();
        return null;
    }
}
 
Example #3
Source Project: alfresco-remote-api   Author: Alfresco   File: WebScriptUtil.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
public static Date getDate(JSONObject json) throws ParseException
{
    if(json == null)
    {
        return null;
    }
    String dateTime = json.optString(DATE_TIME);
    if(dateTime == null)
    {
        return null;
    }
    String format = json.optString(FORMAT);
    if(format!= null && ISO8601.equals(format) == false)
    {
        SimpleDateFormat dateFormat = new SimpleDateFormat(format);
        return dateFormat.parse(dateTime);
    }
    return ISO8601DateFormat.parse(dateTime);
}
 
Example #4
Source Project: jelectrum   Author: fireduck64   File: ElectrumNotifier.java    License: MIT License 6 votes vote down vote up
public void sendAddressHistory(StratumConnection conn, Object request_id, ByteString scripthash, boolean include_confirmed, boolean include_mempool)
{
    Subscriber sub = new Subscriber(conn, request_id);
    try
    {
        JSONObject reply = sub.startReply();

        reply.put("result", getScriptHashHistory(scripthash,include_confirmed,include_mempool));

        sub.sendReply(reply);


    }
    catch(org.json.JSONException e)
    {   
        throw new RuntimeException(e);
    }
}
 
Example #5
Source Project: android-skeleton-project   Author: AAverin   File: GraphObjectAdapter.java    License: MIT License 6 votes vote down vote up
protected URI getPictureUriOfGraphObject(T graphObject) {
    String uri = null;
    Object o = graphObject.getProperty(PICTURE);
    if (o instanceof String) {
        uri = (String) o;
    } else if (o instanceof JSONObject) {
        ItemPicture itemPicture = GraphObject.Factory.create((JSONObject) o).cast(ItemPicture.class);
        ItemPictureData data = itemPicture.getData();
        if (data != null) {
            uri = data.getUrl();
        }
    }

    if (uri != null) {
        try {
            return new URI(uri);
        } catch (URISyntaxException e) {
        }
    }
    return null;
}
 
Example #6
Source Project: TGPassportAndroidSDK   Author: TelegramMessenger   File: PassportScopeElementOne.java    License: MIT License 6 votes vote down vote up
@Override
Object toJSON(){
	if(!selfie && !translation && !nativeNames)
		return type;
	try{
		JSONObject o=new JSONObject();
		o.put("type", type);
		if(selfie)
			o.put("selfie", true);
		if(translation)
			o.put("translation", true);
		if(nativeNames)
			o.put("native_names", true);
		return o;
	}catch(JSONException ignore){}
	return null;
}
 
Example #7
Source Project: XmlToJson   Author: smart-fun   File: ExampleInstrumentedTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void attributeReplacementTest() throws Exception {

    Context context = InstrumentationRegistry.getTargetContext();
    AssetManager assetManager = context.getAssets();
    InputStream inputStream = assetManager.open("common.xml");

    XmlToJson xmlToJson = new XmlToJson.Builder(inputStream, null)
            .setAttributeName("/library/book/id", "attributeReplacement")
            .build();

    inputStream.close();

    JSONObject result = xmlToJson.toJson();
    JSONObject library = result.getJSONObject("library");
    JSONArray books = library.getJSONArray("book");
    assertEquals(books.length(), 2);
    for (int i = 0; i < books.length(); ++i) {
        JSONObject book = books.getJSONObject(i);
        book.getInt("attributeReplacement");
    }
}
 
Example #8
Source Project: ki4a   Author: staf621   File: ForwardList.java    License: Apache License 2.0 6 votes vote down vote up
protected static List<ForwardInfo> loadForwardInfo(Context context) {
    List<ForwardInfo> arrayList = new ArrayList<>();
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
    String jsonString = settings.getString("port_forward_json", "");
    if(jsonString.isEmpty()) return arrayList;
    try {
        JSONArray jsonArray = new JSONArray(jsonString);
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject obj = jsonArray.getJSONObject(i);
            arrayList.add(ForwardInfo.getForwardInfo(obj));
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return arrayList;
}
 
Example #9
Source Project: keemob   Author: alex-shpak   File: FileUtils.java    License: MIT License 6 votes vote down vote up
private boolean needPermission(String nativeURL, int permissionType) throws JSONException {
    JSONObject j = requestAllPaths();
    ArrayList<String> allowedStorageDirectories = new ArrayList<String>();
    allowedStorageDirectories.add(j.getString("applicationDirectory"));
    allowedStorageDirectories.add(j.getString("applicationStorageDirectory"));
    if(j.has("externalApplicationStorageDirectory")) {
        allowedStorageDirectories.add(j.getString("externalApplicationStorageDirectory"));
    }

    if(permissionType == READ && hasReadPermission()) {
        return false;
    }
    else if(permissionType == WRITE && hasWritePermission()) {
        return false;
    }

    // Permission required if the native url lies outside the allowed storage directories
    for(String directory : allowedStorageDirectories) {
        if(nativeURL.startsWith(directory)) {
            return false;
        }
    }
    return true;
}
 
Example #10
Source Project: cordova-plugin-admob-free   Author: ratson   File: InterstitialExecutor.java    License: MIT License 6 votes vote down vote up
public PluginResult requestAd(JSONObject options, CallbackContext callbackContext) {
    CordovaInterface cordova = plugin.cordova;

    plugin.config.setInterstitialOptions(options);

    if (interstitialAd == null) {
        callbackContext.error("interstitialAd is null, call createInterstitialView first");
        return null;
    }

    final CallbackContext delayCallback = callbackContext;
    cordova.getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {
            if (interstitialAd == null) {
                return;
            }
            interstitialAd.loadAd(plugin.buildAdRequest());

            delayCallback.success();
        }
    });

    return null;
}
 
Example #11
Source Project: java-sdk   Author: Baidu-AIP   File: AipImageClassify.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * logo商标识别—添加接口   
 * 使用入库接口请先在[控制台](https://console.bce.baidu.com/ai/#/ai/imagerecognition/overview/index)创建应用并申请建库,建库成功后方可正常使用。
 *
 * @param image - 二进制图像数据
 * @param brief - brief,检索时带回。此处要传对应的name与code字段,name长度小于100B,code长度小于150B
 * @param options - 可选参数对象,key: value都为string类型
 * options - options列表:
 * @return JSONObject
 */
public JSONObject logoAdd(byte[] image, String brief, HashMap<String, String> options) {
    AipRequest request = new AipRequest();
    preOperation(request);
    
    String base64Content = Base64Util.encode(image);
    request.addBody("image", base64Content);
    
    request.addBody("brief", brief);
    if (options != null) {
        request.addBody(options);
    }
    request.setUri(ImageClassifyConsts.LOGO_ADD);
    postOperation(request);
    return requestServer(request);
}
 
Example #12
Source Project: android-discourse   Author: goodev   File: Forum.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void load(JSONObject object) throws JSONException {
    super.load(object);
    name = getString(object, "name");
    JSONObject topic = object.getJSONArray("topics").getJSONObject(0);
    numberOfOpenSuggestions = topic.getInt("open_suggestions_count");
    numberOfVotesAllowed = topic.getInt("votes_allowed");
    categories = deserializeList(topic, "categories", Category.class);
    if (categories == null)
        categories = new ArrayList<Category>();
}
 
Example #13
Source Project: bjoern   Author: octopus-platform   File: Radare.java    License: GNU General Public License v3.0 5 votes vote down vote up
private JSONObject parseReferenceLine(String line) {
	// The JSON object does not contain type information. We have to parse
	// by hand.
	// line format "type0.type1.type2.source=destination0,destination1,
	// ...,destinationN
	JSONObject answer = new JSONObject();
	String[] split = line.split("\\.");
	answer.put("type", split[0] + "." + split[1] + "." + split[2]);
	String[] addresses = split[3].split("=");
	answer.put("address", Long.decode(addresses[0]));
	answer.put("locations", new JSONArray(
			Arrays.stream(addresses[1].split(",")).map(Long::decode)
			      .toArray()));
	return answer;
}
 
Example #14
Source Project: orion.server   Author: eclipse   File: GitPushTest.java    License: Eclipse Public License 1.0 5 votes vote down vote up
static WebRequest getPostGitRemoteRequest(String location, String srcRef, boolean tags, boolean force) throws JSONException, UnsupportedEncodingException {
	String requestURI = toAbsoluteURI(location);
	JSONObject body = new JSONObject();
	if (srcRef != null)
		body.put(GitConstants.KEY_PUSH_SRC_REF, srcRef);
	body.put(GitConstants.KEY_PUSH_TAGS, tags);
	body.put(GitConstants.KEY_FORCE, force);
	WebRequest request = new PostMethodWebRequest(requestURI, IOUtilities.toInputStream(body.toString()), "UTF-8");
	request.setHeaderField(ProtocolConstants.HEADER_ORION_VERSION, "1");
	setAuthentication(request);
	return request;
}
 
Example #15
Source Project: Popeens-DSub   Author: popeen   File: SQLiteHandler.java    License: GNU General Public License v3.0 5 votes vote down vote up
public void importData(JSONArray array){
    SQLiteDatabase db = this.getWritableDatabase();
    try {
        for (int i = 0; i < array.length(); i++) {
            JSONObject row = array.getJSONObject(i);
            ContentValues values = new ContentValues();
            values.put(BOOK_NAME, row.getString("BOOK_NAME"));
            values.put(BOOK_HEARD, row.getString("BOOK_HEARD"));
            values.put(BOOK_DATE, row.getString("BOOK_DATE"));
            db.insertWithOnConflict(TABLE_HEARD_BOOKS, null, values, SQLiteDatabase.CONFLICT_REPLACE);
        }
    }catch(Exception e){ }
}
 
Example #16
Source Project: sdl_java_suite   Author: smartdevicelink   File: DeleteWindowTests.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
protected JSONObject getExpectedParameters(int sdlVersion) {
    JSONObject result = new JSONObject();

    try {
        result.put(DeleteWindow.KEY_WINDOW_ID, Test.GENERAL_INT);
    } catch (JSONException e) {
        fail(Test.JSON_FAIL);
    }

    return result;
}
 
Example #17
Source Project: financisto   Author: dsolonenko   File: FreeCurrencyRateDownloader.java    License: GNU General Public License v2.0 5 votes vote down vote up
private String getResponse(Currency fromCurrency, Currency toCurrency) throws Exception {
    String url = buildUrl(fromCurrency, toCurrency);
    Log.i(TAG, url);
    JSONObject jsonObject = client.getAsJson(url);
    Log.i(TAG, jsonObject.getString(toCurrency.name));
    return jsonObject.getString(toCurrency.name);
}
 
Example #18
Source Project: memetastic   Author: gsantner   File: AssetUpdater.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void run() {
    if (PermissionChecker.hasExtStoragePerm(_context)) {
        if (MainActivity.LOCAL_ONLY_MODE || MainActivity.DISABLE_ONLINE_ASSETS) {
            return;
        }
        AppCast.ASSET_DOWNLOAD_REQUEST.send(_context, ASSET_DOWNLOAD_REQUEST__CHECKING);
        String apiJsonS = NetworkUtils.performCall(URL_API, NetworkUtils.GET);
        try {
            JSONObject apiJson = new JSONObject(apiJsonS);
            String lastUpdate = apiJson.getString("pushed_at");
            int datesubstrindex = lastUpdate.indexOf(":", lastUpdate.indexOf(":") + 1);
            Date date = FORMAT_MINUTE.parse(lastUpdate.substring(0, datesubstrindex));
            if (date.after(_appSettings.getLastAssetArchiveDate())) {
                _appSettings.setLastArchiveCheckDate(new Date(System.currentTimeMillis()));
                if (!_doDownload) {
                    AppCast.ASSET_DOWNLOAD_REQUEST.send(_context, ASSET_DOWNLOAD_REQUEST__DO_DOWNLOAD_ASK);
                } else {
                    doDownload(date);
                    new LoadAssetsThread(_context).start();
                }
            }
            return;
        } catch (JSONException | ParseException e) {
            e.printStackTrace();
        }
    }
    AppCast.ASSET_DOWNLOAD_REQUEST.send(_context, ASSET_DOWNLOAD_REQUEST__FAILED);
}
 
Example #19
Source Project: SocialSdkLibrary   Author: chendongMarch   File: OpenApiShareHelper.java    License: Apache License 2.0 5 votes vote down vote up
void post(Activity activity, final ShareObj obj) {
    mWbLoginHelper.justAuth(activity, new WbAuthListenerImpl() {
        @Override
        public void onSuccess(final Oauth2AccessToken token) {
            Task.callInBackground(() -> {
                Map<String, String> params = new HashMap<>();
                params.put("access_token", token.getToken());
                params.put("status", obj.getSummary());
                return _SocialSdk.getInst().getRequestAdapter().postData("https://api.weibo.com/2/statuses/share.json", params, "pic", obj.getThumbImagePath());
            }).continueWith(task -> {
                if (task.isFaulted() || TextUtils.isEmpty(task.getResult())) {
                    throw SocialError.make(SocialError.CODE_PARSE_ERROR, "open api 分享失败 " + task.getResult(), task.getError());
                } else {
                    JSONObject jsonObject = new JSONObject(task.getResult());
                    if (jsonObject.has("id") && jsonObject.get("id") != null) {
                        mPlatform.onShareSuccess();
                        return true;
                    } else {
                        throw SocialError.make(SocialError.CODE_PARSE_ERROR, "open api 分享失败 " + task.getResult());
                    }
                }
            }, Task.UI_THREAD_EXECUTOR).continueWith(task -> {
                if (task != null && task.isFaulted()) {
                    Exception error = task.getError();
                    if (error instanceof SocialError) {
                        mPlatform.onShareFail((SocialError) error);
                    } else {
                        mPlatform.onShareFail(SocialError.make(SocialError.CODE_REQUEST_ERROR, "open api 分享失败", error));
                    }

                }
                return true;
            }, Task.UI_THREAD_EXECUTOR);
        }
    });
}
 
Example #20
Source Project: letv   Author: JackChan1999   File: JavaScriptinterface.java    License: Apache License 2.0 5 votes vote down vote up
public void handleResult(Activity activity, ParseResultEntity resultEntity) {
    LogInfo.log("lxx", "text: " + resultEntity.getText());
    HashMap<String, String> qrCodeResult = new HashMap();
    qrCodeResult.put("string", resultEntity.getText());
    try {
        jsCallBack(jsInBean, new JSONObject(qrCodeResult).toString());
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        activity.finish();
    }
}
 
Example #21
Source Project: Onosendai   Author: haku   File: Account.java    License: Apache License 2.0 5 votes vote down vote up
public static Account parseJson (final JSONObject json) throws JSONException {
	if (json == null) return null;
	final String id = json.getString(KEY_ID);
	final AccountProvider provider = AccountProvider.parse(json.getString(KEY_PROVIDER));
	Account account;
	switch (provider) {
		case TWITTER:
			account = parseTwitterAccount(json, id);
			break;
		case MASTODON:
			account = parseMastodonAccount(json, id);
			break;
		case SUCCESSWHALE:
			account = parseUsernamePasswordLikeAccount(json, id, AccountProvider.SUCCESSWHALE);
			break;
		case INSTAPAPER:
			account = parseUsernamePasswordLikeAccount(json, id, AccountProvider.INSTAPAPER);
			break;
		case HOSAKA:
			account = parseUsernamePasswordLikeAccount(json, id, AccountProvider.HOSAKA);
			break;
		case BUFFER:
			account = parseBufferAccount(json, id);
			break;
		default:
			throw new IllegalArgumentException("Unknown provider: " + provider);
	}
	return account;
}
 
Example #22
Source Project: alfresco-remote-api   Author: Alfresco   File: CalendarRestApiTest.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
private JSONObject getEntry(String name, int expectedStatus) throws Exception
{
   Response response = sendRequest(new GetRequest(URL_EVENT_BASE + name), expectedStatus);
   if (expectedStatus == Status.STATUS_OK)
   {
      JSONObject result = validateAndParseJSON(response.getContentAsString());
      return result;
   }
   else
   {
      return null;
   }
}
 
Example #23
Source Project: sdl_java_suite   Author: smartdevicelink   File: ReadDidTests.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
   * Tests a valid JSON construction of this RPC message.
   */
  public void testJsonConstructor () {
  	JSONObject commandJson = JsonFileReader.readId(this.mContext, getCommandType(), getMessageType());
  	assertNotNull(Test.NOT_NULL, commandJson);
  	
try {
	Hashtable<String, Object> hash = JsonRPCMarshaller.deserializeJSONObject(commandJson);
	ReadDID cmd = new ReadDID(hash);
	
	JSONObject body = JsonUtils.readJsonObjectFromJsonObject(commandJson, getMessageType());
	assertNotNull(Test.NOT_NULL, body);
	
	// Test everything in the json body.
	assertEquals(Test.MATCH, JsonUtils.readStringFromJsonObject(body, RPCMessage.KEY_FUNCTION_NAME), cmd.getFunctionName());
	assertEquals(Test.MATCH, JsonUtils.readIntegerFromJsonObject(body, RPCMessage.KEY_CORRELATION_ID), cmd.getCorrelationID());

	JSONObject parameters = JsonUtils.readJsonObjectFromJsonObject(body, RPCMessage.KEY_PARAMETERS);
	assertEquals(Test.MATCH, JsonUtils.readIntegerFromJsonObject(parameters, ReadDID.KEY_ECU_NAME), cmd.getEcuName());

	List<Integer> didLocationList = JsonUtils.readIntegerListFromJsonObject(parameters, ReadDID.KEY_DID_LOCATION);
	List<Integer> testLocationList = cmd.getDidLocation();
	assertEquals(Test.MATCH, didLocationList.size(), testLocationList.size());
	assertTrue(Test.TRUE, Validator.validateIntegerList(didLocationList, testLocationList));
} catch (JSONException e) {
	fail(Test.JSON_FAIL);
}    	
  }
 
Example #24
Source Project: spring-integration-aws   Author: 3pillarlabs   File: HttpEndpoint.java    License: MIT License 5 votes vote down vote up
private void handleSubscriptionConfirmation(HttpServletRequest request,
		HttpServletResponse response) throws IOException {
	try {
		String source = readBody(request);
		log.debug("Subscription confirmation:\n" + source);
		JSONObject confirmation = new JSONObject(source);

		if (validSignature(source, confirmation)) {
			URL subscribeUrl = new URL(
					confirmation.getString("SubscribeURL"));
			HttpURLConnection http = (HttpURLConnection) subscribeUrl
					.openConnection();
			http.setDoOutput(false);
			http.setDoInput(true);
			StringBuilder buffer = new StringBuilder();
			byte[] buf = new byte[4096];
			while ((http.getInputStream().read(buf)) >= 0) {
				buffer.append(new String(buf));
			}
			log.debug("SubscribeURL response:\n" + buffer.toString());
		}
		response.setStatus(HttpServletResponse.SC_OK);

	} catch (JSONException e) {
		throw new IOException(e.getMessage(), e);
	}
}
 
Example #25
Source Project: ambry   Author: linkedin   File: FrontendRestRequestServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Sets account name and container name in headers.
 * @param headers the {@link JSONObject} where the headers should be set.
 * @param targetAccountName sets the {@link RestUtils.Headers#TARGET_ACCOUNT_NAME} header. Can be {@code null}.
 * @param targetContainerName sets the {@link RestUtils.Headers#TARGET_CONTAINER_NAME} header. Can be {@code null}.
 * @throws IllegalArgumentException if {@code headers} is null.
 * @throws JSONException
 */
private void setAccountAndContainerHeaders(JSONObject headers, String targetAccountName, String targetContainerName)
    throws JSONException {
  if (headers != null) {
    if (targetAccountName != null) {
      headers.put(RestUtils.Headers.TARGET_ACCOUNT_NAME, targetAccountName);
    }
    if (targetContainerName != null) {
      headers.put(RestUtils.Headers.TARGET_CONTAINER_NAME, targetContainerName);
    }
  } else {
    throw new IllegalArgumentException("Some required arguments are null. Cannot set ambry headers");
  }
}
 
Example #26
Source Project: healthcare-dicom-dicomweb-adapter   Author: GoogleCloudPlatform   File: AttributesUtilTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testJsonToAttributes_empty() throws Exception {
  JSONObject jsonObj = new JSONObject();

  Attributes attrs = AttributesUtil.jsonToAttributes(jsonObj);

  assertThat(attrs).isEqualTo(new Attributes());
}
 
Example #27
Source Project: react-native-navigation   Author: wix   File: OptionsTest.java    License: MIT License 5 votes vote down vote up
@NonNull
private JSONObject createOtherBottomTabs() throws JSONException {
    return new JSONObject()
            .put("currentTabId", BOTTOM_TABS_CURRENT_TAB_ID)
            .put("currentTabIndex", BOTTOM_TABS_CURRENT_TAB_INDEX)
            .put("visible", BOTTOM_TABS_VISIBLE)
            .put("animate", BOTTOM_TABS_ANIMATE.get())
            .put("tabBadge", BOTTOM_TABS_BADGE);
}
 
Example #28
Source Project: olat   Author: huihoo   File: CommandFactory.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * - resets the js flag which is set when the user changes form data and is checked when an other link is clicked.(to prevent form data loss).<br>
 * 
 * @return the command
 */
public static Command createPrepareClientCommand(String businessControlPath) {
    JSONObject root = new JSONObject();
    try {
        root.put("bc", businessControlPath == null ? "" : businessControlPath);
    } catch (JSONException e) {
        throw new AssertException("wrong data put into json object", e);
    }
    Command c = new Command(6);
    c.setSubJSON(root);
    return c;
}
 
Example #29
Source Project: java-sdk   Author: Baidu-AIP   File: AipOcr.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 通用文字识别(高精度版)接口   
 * 用户向服务请求识别某张图中的所有文字,相对于通用文字识别该产品精度更高,但是识别耗时会稍长。
 *
 * @param image - 二进制图像数据
 * @param options - 可选参数对象,key: value都为string类型
 * options - options列表:
 *   detect_direction 是否检测图像朝向,默认不检测,即:false。朝向是指输入图像是正常方向、逆时针旋转90/180/270度。可选值包括:<br>- true:检测朝向;<br>- false:不检测朝向。
 *   probability 是否返回识别结果中每一行的置信度
 * @return JSONObject
 */
public JSONObject basicAccurateGeneral(byte[] image, HashMap<String, String> options) {
    AipRequest request = new AipRequest();
    preOperation(request);
    
    String base64Content = Base64Util.encode(image);
    request.addBody("image", base64Content);
    if (options != null) {
        request.addBody(options);
    }
    request.setUri(OcrConsts.ACCURATE_BASIC);
    postOperation(request);
    return requestServer(request);
}
 
Example #30
Source Project: epcis   Author: JaewookByun   File: VocabularyCapture.java    License: Apache License 2.0 5 votes vote down vote up
@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> post(@RequestBody String inputString, @RequestParam(required = false) Integer gcpLength) {
	Configuration.logger.info(" EPCIS Masterdata Document Capture Started.... ");

	JSONObject retMsg = new JSONObject();
	if (Configuration.isCaptureVerfificationOn == true) {
		InputStream validateStream = CaptureUtil.getXMLDocumentInputStream(inputString);
		// Parsing and Validating data
		boolean isValidated = CaptureUtil.validate(validateStream,
				Configuration.wsdlPath + "/EPCglobal-epcis-masterdata-1_2.xsd");
		if (isValidated == false) {
			return new ResponseEntity<>(new String("Error: EPCIS Masterdata Document is not validated"),
					HttpStatus.BAD_REQUEST);
		}
	}

	InputStream epcisStream = CaptureUtil.getXMLDocumentInputStream(inputString);
	EPCISMasterDataDocumentType epcisMasterDataDocument = JAXB.unmarshal(epcisStream,
			EPCISMasterDataDocumentType.class);
	CaptureService cs = new CaptureService();
	retMsg = cs.capture(epcisMasterDataDocument, gcpLength);
	Configuration.logger.info(" EPCIS Masterdata Document : Captured ");

	if (retMsg.isNull("error") == true)
		return new ResponseEntity<>(retMsg.toString(), HttpStatus.OK);
	else
		return new ResponseEntity<>(retMsg.toString(), HttpStatus.BAD_REQUEST);
}