How to add more data in java bson document with looping - java

i want to looping the code, every loop the data saved to document variable, how to add more data to document, i have problem when the loop more than 1 loop. can you give me an idea how to do it? thank you anyway
private Document getProcessInstances(String status, int page, int size, String sort){
StringBuilder url = new StringBuilder();
Document processinstancelist = null;
Integer totalItems = this.getTotalItems(status, page, size, sort);
Integer totalPages = totalItems/size;
try{
while (page<=totalPages){
url.append(activitiqueryhost).append("/v1/process-instances?status=").append(status).append("&page=").append(page).append("&size=").append(size).append("&sort=").append(sort);
// System.out.println(" >>>>>>>>>> URL="+url.toString());
ResponseEntity<String> processinstancestring = this.get(url.toString());
// System.out.println("processinstancestring="+processinstancestring.getBody());
Document processinstance = Document.parse(processinstancestring.getBody());
// System.out.println(">>>>> processinstance=" + processinstance.toJson());
// Document
processinstancelist = (Document) processinstance.get("list");
// System.out.println(">>>>> list=" + processinstancelist.toJson());
System.out.println("==== datanya "+totalItems);
System.out.println("==== total page "+totalPages);
System.out.println("==== datanya "+page);
page++;
}
return processinstancelist;
}
catch(Exception e){
return null;
}
}

Related

MongoDB get data from object in document using java

I have the following document in my database:
_id: ObjectId('63a73aec1afb1e4de760d9de')
uuid: "71e5db4e-ab05-4de2-9238-5660474c5156"
coins: 0
level: 1
currentXp: 1
upgrades: Object
durability: 0
luck: 1
Now I want to get the data from the object. I tried to get the int from durability by doing this:
public static int getDurabilityLevel(UUID uuid) {
Document filter = new Document("uuid", uuid.toString());
int durabilityLevel = Main.getInstance().getDataConnection().getCollection().find(filter).first().getInteger("upgrades.durability");
return durabilityLevel;
}
I also want to chance the value of the luck integer. But if I try to chance it, the durability integer disappears. I used this to chance the value:
public static void setLuckLevel(UUID uuid, int level) {
Document filter = new Document("uuid", uuid.toString());
Document foundDocument = Main.getInstance().getDataConnection().getCollection().find(filter).first();
if(foundDocument != null) {
Document updateValue = new Document("Upgrades", new Document("luck", level));
Document updateOperation = new Document("$set", updateValue);
Main.getInstance().getDataConnection().getCollection().updateOne(foundDocument, updateOperation);
}
}
I hope anyone can help me with this simple problem. Thanks!
Now I could fix the problems. Here are my solutions:
This is my way to get data from the object:
public static int getDurabilityLevel(UUID uuid) {
Document filter = new Document("uuid", uuid.toString());
Document document = Main.getInstance().getDataConnection().getCollection().find(filter).first();
Document object = (Document) document.get("upgrades");
int durabilityLevel = object.getInteger("durability");
return durabilityLevel;
}
And this is my way to chance data in the object without deleting the other values:
public static void setDurabilityLevel(UUID uuid, int level) {
Document filter = new Document("uuid", uuid.toString());
Document foundDocument = Main.getInstance().getDataConnection().getCollection().find(filter).first();
if (foundDocument != null) {
Document updateValue = new Document("upgrades.durability", level);
Document updateOperation = new Document("$set", updateValue);
Main.getInstance().getDataConnection().getCollection().updateOne(foundDocument, updateOperation);
}
}

how to get arraylist values one by one and put it in stringbuilder java?

all,
I have an arraylist and I want to take the values one by one and put them in the string builder.
I have tried several steps, such as looping for and foreach
this is my code :
try{
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/"+jComboBox1.getSelectedItem()+"","root","");
Statement stmt=con.createStatement();
for(int i =0; i < box.size();i++){
if(box.get(i).isSelected()){
//System.out.print(box.get(i).getText().trim());
ResultSet rs=stmt.executeQuery("select "+box.get(i).getText().trim()+" from "+jComboBox3.getSelectedItem()+";");
while(rs.next()){
isikolom = rs.getString(1);
isi.add(isikolom);
String getkey = jTextField1.getText().toString();
byte[] key = getkey.getBytes();
RC4 rc = new RC4(new String(key));
byte[] desText = rc.decrypt(enText);
descrypted = new String(desText);
StringBuilder sb2 = new StringBuilder(128);
sb2.append("UPDATE ").append(jComboBox3.getSelectedItem().toString()).append(" SET ");
sb2.append(box.get(i).getText().toString()+" = ").append("REPLACE ").append("("+box.get(i).getText().toString()+",");
sb2.append("'"+isikolom+"'").append(",");
isideskripsi.stream().forEach(isideskripsi -> {
sb2.append("'"+isideskripsi+"'");
});
sb2.append(")");
String query2 = sb2.toString();
System.out.println(query2);
PreparedStatement presatet2 = con.prepareStatement(query2);
// presatet2.executeUpdate();
}
System.out.println("After Encryption : "+isiencrypsi);
System.out.println("After Descryption : "+isideskripsi);
}
}
end = System.currentTimeMillis();
long time = end - start;
JOptionPane.showMessageDialog(null, "Berhasil Deskripsi Dalam Waktu "+time+" Detik");
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Gagal Deskripsi, Error Pada : "+e);
System.out.print(e);
}
arraylist items is [admin, pegawai, penyidik]
this is result of that code :
UPDATE user SET username = REPLACE (username,'X"mBR','admin''pegawai''penyidik')
UPDATE user SET username = REPLACE (username,'I#gJK�','admin''pegawai''penyidik')
UPDATE user SET username = REPLACE (username,' I#nRU� �','admin''pegawai''penyidik')
the results i expected :
UPDATE user SET username = REPLACE (username,'X"mBR','admin')
UPDATE user SET username = REPLACE (username,'I#gJK�','pegawai')
UPDATE user SET username = REPLACE (username,' I#nRU� �','penyidik')
Because your description is not clear, I am not sure what you want to do is as follows:
int idx = 0;
while(rs.next()) {
...
sb2.append("'"+isikolom+"'").append(",");
/* remove this block
isideskripsi.stream().forEach(isideskripsi -> {
sb2.append("'"+isideskripsi+"'");
});
*/
sb2.append("'").append(isideskripsi.get(idx)).append("'");
sb2.append(")");
idx++;
...
}
isideskripsi.stream().forEach(isideskripsi -> {
sb2.append("'"+isideskripsi+"'");
});
The above code problems, because every time you build your SQL, you output all the items inside the arraylist, instead you should:
sb2.append("'"+isideskripsi.get(i-1)+"'");
As you only want every one arraylist item one time

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");

Scraping multiple pages with jsoup

I am trying to scrap links in pagination of GitHub repositories
I have scraped them separately but what Now I want is to optimize it using some loop. Any idea how can i do it? here is code
ComitUrl= "http://github.com/apple/turicreate/commits/master";
Document document2 = Jsoup.connect(ComitUrl ).get();
Element pagination = document2.select("div.pagination a").get(0);
String Url1 = pagination.attr("href");
System.out.println("pagination-link1 = " + Url1);
Document document3 = Jsoup.connect(Url1).get();
Element pagination2 = document3.select("div.pagination a").get(1);
String Url2 = pagination2.attr("href");
System.out.println("pagination-link2 = " + Url2);
Document document4 = Jsoup.connect(Url2).get();
Element check = document4.select("span.disabled").first();
if (check.text().equals("Older")) {
System.out.println("No pagination link more");
}
else { Element pagination3 = document4.select("div.pagination a").get(1);
String Url3 = pagination3.attr("href");
System.out.println("pagination-link3 = " + Url3);
}
Try something like given below:
public static void main(String[] args) throws IOException{
String url = "http://github.com/apple/turicreate/commits/master";
//get first link
String link = Jsoup.connect(url).get().select("div.pagination a").get(0).attr("href");
//an int just to count up links
int i = 1;
System.out.println("pagination-link_"+ i + "\t" + link);
//parse next page using link
//check if the div on next page has more than one link in it
while(Jsoup.connect(link).get().select("div.pagination a").size() >1){
link = Jsoup.connect(link).get().select("div.pagination a").get(1).attr("href");
System.out.println("pagination-link_"+ (++i) +"\t" + link);
}
}

How to implement a Sign in function by using Gigya API in JAVA?

I am trying to delete the accounts from Gigya DB, so we can reuse them to test our login function through Gigya. It seems the UID required for deletion come from login, so how am I suppose to do it in Java?
As mentioned by Ilan, firstly you'll need to include the Gigya Java SDK.
You can then look up the UID using either the Identity Access or Identity Query Tool within Gigya console and use the follow code to delete the account:
// delete user record
GSRequest deleteAccountRequest = new GSRequest(apiKey, secretKey, "accounts.deleteAccount");
//deleteAccountRequest.setAPIDomain("eu1.gigya.com"); // enable this if you're using the EU data centre
deleteAccountRequest.setUseHTTPS(true);
deleteAccountRequest.setParam("UID", uid);
GSResponse deleteAccountResponse = deleteAccountRequest.send();
if(deleteAccountResponse.getErrorCode()==0)
{
}
else
{
System.out.println("deleteAccountResponse failure: " + deleteAccountResponse.getLog());
}
Alternatively, if you want to delete users in batch, you can run a search using accounts.search and delete all the users within the results set:
int limit = 100;
String query = "select UID from accounts where ... " + limit; // add your query here i.e. email = 'someone#example.com'
String cursorId = "";
int objectsCount = limit;
GSRequest searchRequest;
ArrayList<String> uidList = new ArrayList<String>();
// send request
do
{
// check if we have an open cursor
if(cursorId.length() > 0)
{
// run next request in cursor
// set up request
searchRequest = new GSRequest(apiKey, secretKey, "accounts.search");
//searchRequest.setAPIDomain("eu1.gigya.com");
//searchRequest.setUseHTTPS(true);
// set timeout
searchRequest.setParam("timeout", 60000);
// set cursor id
searchRequest.setParam("cursorId", cursorId);
} else {
// run new request and open cursor
// set up request
searchRequest = new GSRequest(apiKey, secretKey, "accounts.search");
//searchRequest.setAPIDomain("eu1.gigya.com");
//searchRequest.setUseHTTPS(true);
// set timeout
searchRequest.setParam("timeout", 60000);
// set query
searchRequest.setParam("query", query);
// open cursor
searchRequest.setParam("openCursor", true);
}
GSResponse searchResponse = searchRequest.send();
if(searchResponse.getErrorCode()==0)
{
GSArray uids = new GSArray();
uids = searchResponse.getArray("results", uids);
for(int i=0; i<uids.length(); i++)
{
String uid;
try {
// retrieve uid and add to list of uids
uid = uids.getObject(i).getString("UID");
uidList.add(uid);
} catch (GSKeyNotFoundException e) {
}
}
cursorId = searchResponse.getString("nextCursorId", "");
objectsCount = searchResponse.getInt("objectsCount", 0);
}
else
{
System.out.println("searchRequest failure: " + searchResponse.getLog());
}
}
while (objectsCount >= limit);
for(int i=0; i<uidList.size(); i++)
{
String uid;
try {
uid = uidList.get(i);
// delete user record
GSRequest deleteAccountRequest = new GSRequest(apiKey, secretKey, "accounts.deleteAccount");
//deleteAccountRequest.setAPIDomain("eu1.gigya.com");
deleteAccountRequest.setUseHTTPS(true);
deleteAccountRequest.setParam("UID", uid);
GSResponse deleteAccountResponse = deleteAccountRequest.send();
if(deleteAccountResponse.getErrorCode()==0)
{
}
else
{
System.out.println("deleteAccountResponse failure: " + deleteAccountResponse.getLog());
}
} catch (Exception e) {
}
}

Categories