I am getting JSON data from a word press database to add them to a mobile app using android studio. However, am facing many problems.
First, I need to keep the post content correctly viewed, but what about the html tags ?
After searching I added JSON_HEX_TAG | JSON_PRETTY_PRINT | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE to my output, but that didn't solve my problem. =
PHP CODE
<?php
header('content-type: application/json; charset=utf-8');
/*
* Created by Belal Khan
* website: www.simplifiedcoding.net
* Retrieve Data From MySQL Database in Android
*/
//database constants
define('DB_HOST', 'localhost');
define('DB_USER', '');
define('DB_PASS', '');
define('DB_NAME', '');
//connecting to database and getting the connection object
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
//Checking if any error occured while connecting
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
die();
}
function getAttachment($post_title) {
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$stmt = $conn->prepare("SELECT guid,post_title FROM wp_posts WHERE `post_type`='attachment' AND `post_title` = ?");
$conn -> set_charset("utf8");
$stmt->bind_param("s",$post_title);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($guid, $post_title);
$products_attach = array();
if($stmt->num_rows == 1) {
while($stmt->fetch()){
$temp = array();
$temp['guid'] = $guid;
array_push($products_attach, $temp);
}
return $temp['guid'];
}
}
//creating a query
$stmt = $conn->prepare("SELECT ID, post_title, post_content FROM wp_posts WHERE `post_type`='lsvr_document'AND `post_status`= 'publish';");
$conn -> set_charset("utf8");
//executing the query
$stmt->execute();
//binding results to the query
$stmt->bind_result($id, $title, $content);
$products = array();
//traversing through all the result
while($stmt->fetch()){
$temp = array();
$temp['id'] = $id;
$temp['title'] = $title;
$temp['link'] = getAttachment($temp['title']);
$temp['content'] = $content;
array_push($products, $temp);
}
//displaying the result in json format
// echo json_encode($products, JSON_UNESCAPED_UNICODE | JSON_HEX_TAG );
$json = json_encode($products, JSON_HEX_TAG | JSON_PRETTY_PRINT | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE);
echo $json;
//print_r($products);
?>
Some of the Output
"id": 867,
"title": "إفادة إنجاز بناء مخالف",
"link": "http:\/\/syncsecser.com\/municipal\/wp-content\/uploads\/2020\/09\/إفادة-إنجاز-بناء-مخالف.pdf",
"content": "\u003C!-- wp:heading --\u003E\n\u003Ch2\u003Eالمستندات المرفقة و أماكن إنجازها\u003C\/h2\u003E\n\u003C!-- \/wp:heading --\u003E\n\n\u003C!-- wp:paragraph --\u003E\n\u003Cp\u003E1. طلب موقع من صاحب العلاقة أو من ينوب عنه قانوناً.\u003Cbr\u003E2. إفادة عقارية\u0026nbsp;شاملة.\u003Cbr\u003E3. أي مستند يثبت تاريخ إنجاز المخالفة.\u003C\/p\u003E\n\u003C!-- \/wp:paragraph --\u003E\n\n\u003C!-- wp:table {\u0022className\u0022:\u0022is-style-regular\u0022} --\u003E\n\u003Cfigure id=\u0022table1\u0022 class=\u0022wp-block-table is-style-regular\u0022\u003E\u003Ctable\u003E\u003Ctbody\u003E\u003Ctr\u003E\u003Ctd\u003E\u003Cbr\u003E\u003Cbr\u003E-\u003Cstrong\u003E\u003Cu\u003Eمدّة\u0026nbsp;الإنجاز :\u003C\/u\u003E\u003C\/strong\u003E\u003Cbr\u003E\u0026nbsp;ثلاثة أيام سنداً\u0026nbsp;لتعميم وزير الداخلية والشؤون البلدية والقروية رقم 8\/99.\u003Cbr\u003E\u003Cbr\u003E-\u003Cstrong\u003E\u0026nbsp;الرسوم\u0026nbsp;المتوجبة\u003Cbr\u003E\u003Cbr\u003E\u0026nbsp;\u003C\/strong\u003E\u003Cbr\u003E1.\u0026nbsp;\u0026nbsp;رسم الإفادة الفنية:\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp; 2000 ل.ل.\u003Cbr\u003E\u0026nbsp;\u003Cbr\u003E2.\u0026nbsp;\u0026nbsp;رسم طابع مالي:\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;1000 ل.ل.\u003Cbr\u003E\u003C\/td\u003E\u003C\/tr\u003E\u003C\/tbody\u003E\u003C\/table\u003E\u003C\/figure\u003E\n\u003C!-- \/wp:table --\u003E"
},
A simple solution is you can encode your content to base64 and then in your mobile app or any other page you want to parse the content, you can just simply decode this base64.
Related
So basically what I want: find and replace strings in a .jar file whatever length it is. It works for me fine except I need to have the same length of the replaced variable as the variable. I want that the length doesn't matter. Does anyone know how to help me?
PHP code:
<?php
$search1 = '%%__NONCE__%%';
$replace1 = 'ME_0000000001';
$search2 = '%%__USER__%%';
$replace2 = '000000000001';
$search3 = '%%__RESOURCE__%%';
$replace3 = '1';
function modifyzip($archive, $search, $replace) {
$zip = new ZipArchive();
$status = $zip->open($archive);
// echo $status;
if ($status == true) {
/* Get the count of files BEFORE the loop */
$filecount = $zip->numFiles;
// echo $filecount;
for ($i=0; $i < $filecount; $i++) {
$name = $zip->getNameIndex($i);
$content = $zip->getFromName($name);
$edited = str_replace($search, $replace, $content);
if ($edited != $content) {
// echo $edited;
// echo $edited . "\n\n";
}
$zip->deleteName($name);
$zip->addFromString($name, $edited);
}
}
$zip->close();
}
$templateFilename = 'zips/a.jar';
$inputFilename = 'zips/b.jar';
if (!copy($templateFilename, $inputFilename)) {
die("Could not copy '$templateFilename' to '$inputFilename'");
}
call_user_func('modifyzip', $inputFilename, $search1, $replace1);
call_user_func('modifyzip', $inputFilename, $search2, $replace2);
call_user_func('modifyzip', $inputFilename, $search3, $replace3);
//echo file_get_contents($templateFilename);
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$inputFilename");
header("Content-Type: application/java-archive");
header("Content-Transfer-Encoding: binary");
// read the file from disk
readfile($inputFilename);
unlink($inputFilename);
Java Luyten error:
java.lang.IllegalArgumentException: Argument 'value' must be in the range [1, 18], but value was: 0.
at com.strobel.core.VerifyArgument.inRange(VerifyArgument.java:346)
at com.strobel.assembler.ir.ConstantPool$Tag.fromValue(ConstantPool.java:532)
at com.strobel.assembler.ir.ConstantPool.read(ConstantPool.java:362)
at com.strobel.assembler.metadata.JarTypeLoader.getInternalNameFromClassFile(JarTypeLoader.java:105)
at com.strobel.assembler.metadata.JarTypeLoader.tryLoadType(JarTypeLoader.java:78)
at us.deathmarine.luyten.LuytenTypeLoader.tryLoadType(LuytenTypeLoader.java:25)
at com.strobel.assembler.metadata.MetadataSystem.resolveType(MetadataSystem.java:120)
at com.strobel.assembler.metadata.MetadataSystem.lookupTypeCore(MetadataSystem.java:81)
at com.strobel.assembler.metadata.MetadataResolver.lookupType(MetadataResolver.java:46)
at us.deathmarine.luyten.Model.openEntryByTreePath(Model.java:338)
at us.deathmarine.luyten.Model$TreeListener$1.run(Model.java:266)
I want to get the list of corpora.
curl -X GET --header "Authorization: Bearer xxxxxxxx(about 1200 characters IAM token)" "https://https://gateway-syd.watsonplatform.net/speech-to-text/api/v1/customizations/zzzzz(customization_id)/corpora"
result(This curl command succeeds.)
{"corpora": [
{
"out_of_vocabulary_words": 0,
"total_words": 10,
"name": "corpusname",
"status": "analyzed"
},
...
but...in Java,
HttpURLConnection urlConn = null;
try {
String urlStr ="https://https://gateway-syd.watsonplatform.net/speech-to-text/api/v1/customizations/zzzzz(customization_id)/corpora";
URL url = new URL(urlStr);
urlConn = (HttpURLConnection) url.openConnection();
String token = xxxxxxxx; // about 1200 characters IAM token
urlConn.setRequestProperty("Authorization", "Bearer " + token);
urlConn.setRequestMethod("GET");
urlConn.connect();
int status = urlConn.getResponseCode();
String resMessage = urlConn.getResponseMessage();
System.out.println("## HTTPStatus:" + status + " - " + resMessage); // "## HTTPStatus:400 - Bad Request"
} catch (xxx) {
// ...
}
result(failure)
## HTTPStatus:400 - Bad Request
I used same IAM token...
Why this error occurs?
(I'm sorry that I am not good at English.)
=============added 2020/03/03
I used watson SDK(ver.6.9.2). But another error(403) occurs...
IamOptions options = new IamOptions.Builder()
.accessToken(token)
.url(urlStr) // String urlStr = https://gateway-syd.watsonplatform.net/speech-to-text/api/v1/customizations/zzzzz(customization_id)/corpora
.build();
SpeechToText speechToText = new SpeechToText(options);
System.out.println();
ListCorporaOptions listCorporaOptions = new ListCorporaOptions.Builder()
.customizationId(customizations_id) // String curstomization_id = zzzzz
.build();
List<Corpus> corpus = speechToText.listCorpora(listCorporaOptions)
.execute()
.getCorpora(); // status: 403, error: Forbidden
System.out.println(corpus.get(0));
error:
play.api.http.HttpErrorHandlerExceptions$$anon$1: Execution exception[[ForbiddenException: Forbidden]]
at play.api.http.HttpErrorHandlerExceptions$.throwableToUsefulException(HttpErrorHandler.scala:251)
at play.api.http.DefaultHttpErrorHandler.onServerError(HttpErrorHandler.scala:178)
at play.core.server.AkkaHttpServer$$anonfun$1.applyOrElse(AkkaHttpServer.scala:363)
at play.core.server.AkkaHttpServer$$anonfun$1.applyOrElse(AkkaHttpServer.scala:361)
at scala.concurrent.Future.$anonfun$recoverWith$1(Future.scala:413)
at scala.concurrent.Future$$Lambda$6244/000000001ECBEAD0.apply(Unknown Source)
at scala.concurrent.impl.Promise.$anonfun$transformWith$1(Promise.scala:37)
at scala.concurrent.impl.Promise$$Lambda$3716/00000000172D40F0.apply(Unknown Source)
at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:60)
at akka.dispatch.BatchingExecutor$AbstractBatch.processBatch(BatchingExecutor.scala:55)
Caused by: com.ibm.watson.developer_cloud.service.exception.ForbiddenException: Forbidden
at com.ibm.watson.developer_cloud.service.WatsonService.processServiceCall(WatsonService.java:474)
at com.ibm.watson.developer_cloud.service.WatsonService$WatsonServiceCall.execute(WatsonService.java:532)
at controllers.Controller.getCorpora(Controller.java:147)
at router.Routes$$anonfun$routes$1.$anonfun$applyOrElse$52(Routes.scala:1412)
at router.Routes$$anonfun$routes$1$$Lambda$6727/000000001FB17820.apply(Unknown Source)
at play.core.routing.HandlerInvokerFactory$$anon$3.resultCall(HandlerInvoker.scala:134)
at play.core.routing.HandlerInvokerFactory$$anon$3.resultCall(HandlerInvoker.scala:133)
at play.core.routing.HandlerInvokerFactory$JavaActionInvokerFactory$$anon$8$$anon$2$$anon$1.invocation(HandlerInvoker.scala:108)
at play.core.j.JavaAction$$anon$1.call(JavaAction.scala:88)
at play.http.DefaultActionCreator$1.call(DefaultActionCreator.java:31)
Just use the Watson Java SDK!
https://cloud.ibm.com/apidocs/speech-to-text/speech-to-text?code=java#get-a-corpus
The example that Mike pointed to won't work with version 6, which is 2 major versions back. Can you update to version 8 of the SDK? See the migration guide.
Then your authentication code would be different and the example in the API reference should work:
IamAuthenticator authenticator = new IamAuthenticator("{apikey}");
SpeechToText speechToText = new SpeechToText(authenticator);
speechToText.setServiceUrl("{url}");
replace {url} with https://api.au-syd.speech-to-text.watson.cloud.ibm.com or https://gateway-syd.watsonplatform.net/speech-to-text/api
and replace {apikey} with your key.
I am pretty new to Neo4j. I have written this piece of code below:
List<Value> collect_appnames = new ArrayList<Value>();
Driver dr = GraphDatabase.driver("bolt://inmbzp5137.in.dst.ibm.com:7687", AuthTokens.basic("neo4j", " "));
Session session = dr.session();
StatementResult rs = session.run("Match(n:Application) with n.name as a return distinct collect(a)");
Assert.assertTrue(rs.hasNext());
while(rs.hasNext()) {
Record record = rs.next();
collect_appnames= record.values();
}
collect_appnames returns this->
[
[
"sample-tomcat",
"sampleticketing",
"sampleoms",
"samplescheduler",
"sampleinventory",
"samplerating",
"sampleloyalty",
"samplertcm",
"sampleproducts",
"sampleinvoicegenerator",
"samplejbosswildfly",
"samplewebsphereapplication",
"samplereports",
"sampleapplication",
"samplebanking",
"samplemoneytransfer",
"sampleautomobile",
"samplemanufacturing",
"sampleinvestment",
"samplesavings",
"sampledesign",
"samplepatterns",
"samplepatents",
"sampleonlinetransfer",
"samplerecharge",
"samplecreditcheck",
"samplecreditcheck",
"sampleautomobileserver",
"sample-tomcat",
"sampleticketing",
"sampleoms",
"samplescheduler",
"sampleinventory",
"samplerating",
"sampleloyalty",
"samplertcm",
"sampleproducts",
"sampleinvoicegenerator",
"samplejbosswildfly",
"samplewebsphereapplication",
"samplereports",
"sampleapplication",
"samplebanking",
"samplemoneytransfer",
"sampleautomobile",
"samplemanufacturing",
"sampleinvestment",
"samplesavings",
"sampledesign",
"samplepatterns",
"samplepatents",
"sampleonlinetransfer",
"samplerecharge",
"sampleticketing",
"sampleoms",
"samplescheduler",
"sampleinventory",
"samplerating",
"sampleloyalty",
"sample-tomcat",
"samplertcm",
"sampleproducts",
"sampleinvoicegenerator",
"samplejbosswildfly",
"samplewebsphereapplication",
"samplereports",
"sampleapplication",
"samplebanking",
"samplemoneytransfer",
"sampleautomobile",
"samplemanufacturing",
"sampleinvestment",
"samplesavings",
"sampledesign",
"samplepatterns",
"samplepatents",
"sampleonlinetransfer",
"samplerecharge",
"samplecreditcheck",
"sampleautomobileserver"
]
]
However collect_appnames.size() returns 1. So when i do collect_appnames.get(0) it is returning me the entire set. I want to extract only sample-tomcat from this list. Please tell me how to do this. Thanks in advance!
I'm doing a project with Matlab.
This project is about Thai license plate recognition.
I have a problem with encoding-utf8 (I guess).
The program can recognize and show data in Thai but inserting data in table can't show Thai character. (ex. กข1234 --> ??1234 )
I set collation in utf8_unicode_ci. Did i do anything wrong?
Thank you
Here is some of my code
%# Database
javaaddpath('mysql-connector-java-5.1.6-bin.jar');
host = 'localhost:3306';
user = 'root';
password = '';
dbName = 'smart parking';
%# JDBC parameters
jdbcString = sprintf('jdbc:mysql://%s/%s', host, dbName);
jdbcDriver = 'com.mysql.jdbc.Driver';
%# Create the database connection object
conn = database(dbName, user , password, jdbcDriver, jdbcString);
exec(conn, 'SET character_set_results=UTF-8');
exec(conn, 'SET character_set_client=UTF-8');
exec(conn, 'SET character_set_connection=UTF-8');
exec(conn, 'SET character_set_server=UTF-8');
exec(conn, 'SET NAMES utf8');
% check to make sure that we successfully connected
if isconnection(conn)
SQL_x = ['SELECT * FROM tbl_information WHERE sPlate = ''' R_str ''' AND sOut = 0'];
curs_x = exec(conn, SQL_x);
curs_x = fetch(curs_x);
QUERY_x = curs_x.Data;
if strcmp(QUERY_x, 'No Data') == 1
Plate = R_str;
Sql = ['INSERT INTO tbl_information(sPlate, sTimeIn, sTimeOut, sUse, sPrice, sOut) VALUES(''' Plate ''', ''' datestr(now) ''', '''' , 0, 0, 0)'];
curs = exec(conn, Sql);
end
end
set(handles.text8, 'String', R_str);
drawnow;
I want to integrate the Aadhaar Card Authentication API for Aadhaar number Verification in PHP. I tried this and wrote code for API access.
How can I generate the XML encryption field data below in PHP? This sample code is written in Java.
<Auth uid="" tid="" ac="" sa="" ver="" txn="" lk="">
<Uses pi="" pa="" pfa="" bio="" bt="" pin="" otp=""/>
<Tkn type="" value=""/>
<Meta udc="" fdc="" idc="" pip="" lot=”G|P” lov=""/>
<Skey ci="" ki="">encrypted and encoded session key</Skey>
<Data type=”X|P”>encrypted PID block</Data>
<Hmac>SHA-256 Hash of Pid block, encrypted and then encoded</Hmac>
<Signature>Digital signature of AUA</Signature>
</Auth>
// Below is the running code to integrate Aadhaar Card Authentication Api for Aadhaar number Verification in PHP?
$path=$_SERVER['DOCUMENT_ROOT'];
$certpath=$path."/your .pfx file";
$publickeypath=$path."/your .cer file";
$certpassword="your cert password";
require_once('xmlsecurity.php'); // for creating this file use link : https://github.com/robrichards/xmlseclibs
$trn_id = "AuthDemoClient:public:". date('YmdHisU');
if (!$cert_store = file_get_contents($certpath)) {
echo "Error: Unable to read the cert file\n";
exit;
}
if (openssl_pkcs12_read($cert_store, $cert_info, $certpassword)) {
//print_r($cert_info["cert"]);
//print_r($cert_info["pkey"]);
} else {
echo "Error: Unable to read the cert store.\n";
exit;
}
define("UIDAI_PUBLIC_CERTIFICATE" , $publickeypath);
define("AUA_PRIVATE_CERTIFICATE" , $cert_info["pkey"]);
date_default_timezone_set("Asia/Calcutta");
$date2= gmdate("Y-m-d\TH:i:s");
$date1 = date('Y-m-d\TH:i:s', time());
$ts='"'.$date1.'"';//date('Y-m-d\TH:i:s');
$pid_1='<Pid ts='.$ts.' ver="1.0"><Pv otp="'.$otp.'"/></Pid>';
$randkey = generateRandomString();
$SESSION_ID = $randkey;
$skey1=encryptMcrypt($SESSION_ID);
$skey=base64_encode($skey1);
// generate ci code start
$ci=getExpiryDate(UIDAI_PUBLIC_CERTIFICATE);
// generate pid block code start
$pid=encryptPID($pid_1,$randkey);
//hmac creation code start
$hash=hash("SHA256",$pid_1,true);
$hmac=encryptPID($hash,$randkey);
$load_xml="<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><Auth xmlns=\"http://www.uidai.gov.in/authentication/uid-auth-request/1.0\" sa=\"public\" lk=\"your license key\" txn=\"$trn_id\" ver=\"1.6\" tid=\"public\" ac=\"your code from aadhaar\" uid=\"$aadhaarno\"><Uses pi=\"n\" pa=\"n\" pfa=\"n\" bio=\"n\" bt=\"\" pin=\"n\" otp=\"y\"/><Meta udc=\"UDC:001\" fdc=\"NC\" idc=\"NA\" pip=\"NA\" lot=\"P\" lov=\"$pincode\"/><Skey ci=\"$ci\">$skey</Skey><Data type=\"X\">$pid</Data><Hmac>$hmac</Hmac></Auth>";
$dom = new DOMDocument();
$dom->loadXML($load_xml); // the XML you specified above.
$objDSig = new XMLSecurityDSig();
$objDSig->setCanonicalMethod(XMLSecurityDSig::C14N_COMMENTS);
$objDSig->addReference($dom, XMLSecurityDSig::SHA1, array('http://www.w3.org/2000/09/xmldsig#enveloped-signature'),array('force_uri'
=>'true'));
$objKey = new XMLSecurityKey(XMLSecurityKey::RSA_SHA1, array('type'=>'private'));
$objKey->loadKey($cert_info["pkey"], False);
$objKey->passphrase = 'your certificate password';
$objDSig->sign($objKey, $dom->documentElement);
$objDSig->add509Cert($cert_info["cert"]);
$objDSig->appendSignature($dom->documentElement);
$xml_string = $dom->saveXML();
$xml_string1 = urlencode($xml_string);
$curl = curl_init();
$url=""; //aadhar service url
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_POSTFIELDS,"eXml=A28".$xml_string1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
/* complete within 20 seconds */
curl_setopt($curl, CURLOPT_TIMEOUT, 20);
$result = curl_exec($curl);
curl_close($curl);
$xml = #simplexml_load_string($result);
$return_status=$xml['ret'];
if($return_status=="y"){
$res=1;
}
if($return_status!="y"){
$res=0;
}
}else
{
$res='Aadhaarno not exist';
}
return array('Message'=>$res);
}
function encryptMcrypt($data) {
$fp=fopen(UIDAI_PUBLIC_CERTIFICATE,"r");
$pub_key_string=fread($fp,8192);
openssl_public_encrypt($data, $encrypted_data, $pub_key_string, OPENSSL_PKCS1_PADDING);
return $encrypted_data;
}
function generateRandomString($length = 32) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
function encryptPID($data,$skey) {
$result=openssl_encrypt ( $data , 'AES-256-ECB' , $skey );
return ($result);
}
function getExpiryDate($_CERTIFICATE){
$_CERT_DATA = openssl_x509_parse(file_get_contents($_CERTIFICATE));
return date('Ymd', $_CERT_DATA['validTo_time_t']);
}
To generate the XML, you could use this library to generate it quite easily:
https://github.com/iwyg/xmlbuilder
For the encryption; I could be wrong but it looks like (from this page) you can generate the encoded results in java one time and just paste in the results to your PHP variables.