Post data in wordpress from java using xmlrpc - java

I am trying to post data in wordpress using this code but I am getting token null
In place of sXmlRpcURL I have used http://wordpress.com/ and http://sUsername.wordpress.com/ also but both the cases its generating token null.
String sXmlRpcURL= arg[0];
String sUsername = arg[1];
String sPassword = arg[2];
// Hard-coded blog_ID
int blog_ID = 1;
// XML-RPC method
String sXmlRpcMethod = "blogger.newPost";
// XML-RPC method ver 2
// sXmlRpcMethod = "metaWeblog.newPost"; // I have used this also
// We'll hard-code our blog content for now as well
String sTitle = "HI........";
String sContent = "Hello XML-RPC World!";
// Create our content struct
HashMap hmContent = new HashMap();
hmContent.put("title", sTitle);
hmContent.put("description", sContent);
// You can specify whether or not you want the blog published immediately
boolean bPublish = true;
// Try block
try {
// Create the XML-RPC client
XmlRpcClient client = new XmlRpcClient(sXmlRpcURL,true);
// Make our method call
Object token = client.invoke( sXmlRpcMethod, new Object[] { new Integer( blog_ID ), sUsername, sPassword, hmContent, new Boolean( bPublish ) } );
// The return is a String containing the postID
System.out.println("Posted : " + (String) token);
} // Catch exceptions
catch (Exception e) {
}
please help me.

I have got the solution you want to use -
http://sUsername.wordpress.com/xmlrpc.php?
for sXmlRpcURL.
Now it working well-

Related

how to insert an array to JSONArray with rest assured

I want to insert the array with Rest Assured.
tokenUUIDs - is an array ( A variable that I defined in a previous step).
When I run the code - tokenUUIDs received a correct value But ArraytokenUUIDs have not received something good. He received : [[Ljava.lang.String;#6fc0bbc6]
This is my Method:
public static void releaseTokens(String[] tokenUUIDs )
{
try{
RequestSpecification request = RestAssured.given();
request.header("Content-Type", "application/json");
JSONObject releaseTokens = new JSONObject();
releaseTokens.put("partnerCode", commonOps.partnerCode);
releaseTokens.put("apiAccessToken",commonOps.openAccessToken);
releaseTokens.put("sessionUUID",SessionUUID);
releaseTokens.put("taskUUID","TaskUUID");
JSONArray ArraytokenUUIDs = new JSONArray();
ArraytokenUUIDs.add(tokenUUIDs);
releaseTokens.put("tokenUUIDs", ArraytokenUUIDs);
request.body(releaseTokens.toJSONString());
Response response = request.post((getData("APIenv") + "/api/sessions/releaseTokens.php"));
int code = response.getStatusCode();
Assert.assertEquals(code, 200);
System.out.println("Status code for releaseTokens.php is" +code );
ResponseBody bodyreleaseTokens = response.getBody();
System.out.println("Body bodyreleaseTokens.php " + bodyreleaseTokens.asString() );
String statusbodyreleaseTokens = bodyreleaseTokens.asString();
String status = response.getBody().jsonPath().getString("status");
Assert.assertEquals(status, "OK");
test.log(LogStatus.PASS, "bodyreleaseTokens is done" );
}
catch (Exception e)
{
test.log(LogStatus.FAIL, "bodyreleaseTokens is not done");
test.log(LogStatus.FAIL, e.getMessage());
fail ("bodyreleaseTokens is not done");
}
Try to add every token individually
for (String s : tokenUUIDs){
ArraytokenUUIDs.add(s);
}
Change
ArraytokenUUIDs.add(tokenUUIDs);
to
for (String tokenUUID : tokenUUIDs) {
ArraytokenUUIDs.add(tokenUUID);
}
Also consider that variables in java are named with lowercase first letter as a standard to avoid confusion with classes.

NotesException: A required argument has not been provided

My XPage gathers information which I use to populate a document in a different Domino database. I use a link button (so I can open another XPage after submission). The onClick code is as follows:
var rtn = true
var util = new utilities()
var hostURL = configBean.getValue("HostURL");
var userAttachment;
//set up info needed for checking duplicates
var attachName=getComponent("attachmentIdentifier").getValue();
var serialNbr = getComponent("serialNumber").getValue();
userAttachment = user+"~"+attachName;
var userSerial = user+"~"+serialNbr;
//Done setting info needed
//check for duplicates
rtn = utilBean.checkAttachmentName(userAttachment, userSerial)
//done
if(rtn==true){
var doc:Document = document1;
dBar.info("ALL IS GOOD");
var noteID:String=document1.getNoteID();
dBar.info("Calling saveNewAttachment using NoteID " + noteID )
rtn=utilBean.saveNewAttachment(session,noteID ); //<<< I get error here
dBar.info("rtn = " + rtn)
return "xsp-success";
view.postScript("window.open('"+sessionScope.nextURL+"')")
}else if (rtn==false){
errMsgArray = utilBean.getErrorMessages();
for(err in errMsgArray){
//for (i=0; i < errMsgArray.size(); i++){
dBar.info("err: "+ err.toString());
if (err== "nameUsed"){
//send message to XPXage
facesContext.addMessage(attachmentIdentifier.getClientId(facesContext) , msg(langBean.getValue("duplicateName")));
}
if(err=="serialUsed"){
//send message to XPXage
facesContext.addMessage(serialNumber.getClientId(facesContext) , msg(langBean.getValue("duplicateSerial")));
}
}
return "xsp-failure";
}
And the java code that delivers the error is this
public boolean saveNewAttachment(Session ses, String noteID)
throws NotesException {
debugMsg("Entering saveNewAttachment and NOTEID = "+noteID);
// this is used when the user saves an attachment to to the
// user profiles db
boolean rtn = false;
Document doc;
ConfigBean configBean = (ConfigBean)
ExtLibUtil.resolveVariable(FacesContext.getCurrentInstance(),
"configBean");
String dbName = (String) configBean.getValue("WebsiteDbPath");
debugMsg("A");
Database thisDB = ses.getDatabase(ses.getServerName(), dbName, false);
String value;
try {
debugMsg("noteID: "+noteID);
The next line throws the NotesException error
doc = thisDB.getDocumentByID("noteID");
debugMsg("C");
} catch (Exception e) {
debugMsg("utilitiesBean.saveAttachment: " + e.toString());
e.printStackTrace();
System.out.println("utilitiesBean.saveAttachment: " + e.toString());
throw new RuntimeException("utilitiesBean.saveAttachment: "
+ e.toString());
}
return rtn;
}
I might be going about this wrong. I want to save the document which the data is bound to the User Profile database but if I submit it I need to redirect it to a different page. That is why I am using a link, however, I am having a hard time trying to get the document saved.
Has document1 been saved before this code is called? If not, it's not in the backend database to retrieve via getDocumentByID().
I'm assuming this line has been copied into here incorrectly, because "noteID" is not a NoteID or a variable holding a NoteID, it's a string.
doc = thisDB.getDocumentByID("noteID");

How do I get multiple optional values of JSON data?

There is a JSON data that contains several optional fields:
My code to get these values is:
String name = null;
String family_name = null;
String given_name = null;
String suffix_name = null;
try {
JSONObject contact = new JSONObject("{\"givenName\":[\"John\"],\"familyName\":[\"Doe\"]}");
name = contact.getJSONArray("name").getString(0);
family_name = contact.getJSONArray("familyName").getString(0);
given_name = contact.getJSONArray("givenName").getString(0);
suffix_name = contact.getJSONArray("honorificPrefix").getString(0);
} catch (JSONException e) {
Log.e("ContactsManager", "Failed to parse json data: "+e);
}
The problem here is, if "name" is null(as the example above), all other fields will failed to be retrieved, which is not I expected.
why not add a check before reading
if (contact.has("name")) {
name = contact.getJSONArray("name").getString(0);
}

How to retrieve more than 25 youtube comments using Java

YouTubeService service = new YouTubeService("MyApp");
String videoEntryUrl = "http://gdata.youtube.com/feeds/api/videos/nU9dinwMyHo";
VideoEntry videoEntry = service.getEntry(new URL(videoEntryUrl), VideoEntry.class);
String commentUrl = videoEntry.getComments().getFeedLink().getHref();
CommentFeed commentFeed = service.getFeed(new URL(commentUrl), CommentFeed.class);
for(CommentEntry comment : commentFeed.getEntries()) {
System.out.println(comment.getPlainTextContent());
Here are my codes to retrieve the youtube comments of a specific video.
I'm able to retrieve about 25 comments using this code, but how do I retrieve ALL the comments from the video?
I think it is something like:
// Get a video entry
String str = "http://gdata.youtube.com/feeds/api/videos/" + videoId;
YouTubeQuery youtubeQuery = new YouTubeQuery(new URL(str));
String videoEntryUrl = youtubeQuery.getUrl().toString();
VideoEntry videoEntry = service.getEntry(new URL(videoEntryUrl),VideoEntry.class);
// Get the comments url for this video
if (videoEntry.getComments() != null) {
String commentUrl = videoEntry.getComments().getFeedLink().getHref();
System.out.println(commentUrl);
// Get the comment feed; use a new query
YouTubeQuery youtubeQuery = new YouTubeQuery(new URL(commentUrl);
youtubeQuery.setMaxResults(50);
youtubeQuery.setStartIndex(1);
String commentUrlFeed = youtubeQuery.getUrl().toString();
CommentFeed commentFeed = service.getFeed(new URL(commentUrlFeed),CommentFeed.class);
// The response should contain an url for the next feed, if any, already with an updated start-index.
for (int i = 0; i < commentFeed.getEntries().size()
&& commentFeed.getEntries().get(i) != null; i++) {
String author=commentFeed.getEntries().get(i).getAuthors().get(0).getUri().substring(41)
String commentId=commentFeed.getEntries().get(i).getId().substring(47);
String comment=commentFeed.getEntries().get(i).getPlainTextContent();
}
}
// Loop thru next comment feed call, if more can be expected.
// Use updated url from the response or set start-index = start-index + max-results.
}

how to convert java object to plain string in j2me Bluetooth application?

I'm making a j2me Bluetooth application. I'm also new in java world. Where I have to display a Bluetooth service name to the user. So far it seems all is working correctly except service name. I verified my Bluetooth server is advertising service name correctly by other client (done by qt). I tried as follows:-
public void commandAction(Command command, Item item) {
if (item == deviceChoiceGroup) {
if (command == servicesDiscoverCommand) {
if(deviceList.size()==0) {
return;
}
UUID[] searchList = new UUID[1];
searchList[0] = new UUID("11111111111111111111111111111111",false);
int[] attrSet = new int[1];
attrSet[0] = 0x100;
RemoteDevice currentDevice =
(RemoteDevice) deviceList.elementAt(
getDeviceChoiceGroup().getSelectedIndex());
if(currentDevice == null) {
return;
}
try {
transactionID = bluetoothDiscoveryAgent.searchServices(
new int[] {0x100}, searchList, currentDevice, this);
printToForm("Start services under L2CAP searching...");
form.addCommand(cancelServicesDiscoverCommand);
} catch (BluetoothStateException e) {
//TODO: write handler code
}
}
}
}
public void servicesDiscovered(int transID, ServiceRecord[] serviceRecords){
if (serviceRecords.length>0 && serviceRecords!=null)
{
connectionURL=serviceRecords[0].getConnectionURL(0, false);
int[] ids=serviceRecords[0].getAttributeIDs();
DataElement ServiceName=serviceRecords[0].getAttributeValue(ids[1]);
// tried to convert objedct to string.
String str = (ServiceName.getValue()).toString();
// out is put is like java.util.vector$1#3c60cd14c
printToForm("#Service name: "+str);
printToForm("The Service name is: "+ServiceName.getValue());
}
}
"DataElement.getValue()" which returns object. Thus I can see service name as "java.util.vector$1#3c60cd14c". I tried to convert object to string as "String str = (ServiceName.getValue()).toString();" It doesn't convert correctly.
So how to convert object to string. So that I could see the service name in plain text. Thanks!
By seeing the result : java.util.vector$1#3c60cd14c i guess the returned object's type is Vector.
So try to cast to the Vector and iterate through it to get the values.
Iterator itr = serviceName.getValue().iterator();//do something here
System.out.println("Iterating through Vector elements...");
while(itr.hasNext())
System.out.println(itr.next());

Categories