my request is going to update query in the else if condition but the records are not updating in the database
help me out of this situation
I didn't get any errors after clicking on update button the database record is not inserted in the database
// imports ...
public class RequestData extends HttpServlet {
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/html");
out.print("<html>");
out.print("<title>DataRetreving</title>");
out.print("<body>");
out.print("<table border=5 width=50% height=50% bgcolor=magenta align=center>");
out.print("<tr>");
out.print("<th><b>id</b></th>");
out.print("<th><b>name</b></th>");
out.print("<th><b>address</b></th>");
out.print("<th><b>action</b></th>");
out.print("<th><b>actionupdate</b></th>");
out.print("</tr>");
Driver driver = new OracleDriver();
try {
DriverManager.registerDriver(driver);
Connection connection = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521/XE", "system",
"india124");
Statement pst = connection.createStatement();
if(request.getParameter("action")!=null && "delete".equals(request.getParameter("action")))
{
int id=Integer.parseInt(request.getParameter("id"));
pst.executeUpdate("delete from employee where id="+id);
}
else if(request.getParameter("id") != null
&& request.getParameter("name") != null
&& request.getParameter("address") != null
&& request.getParameter("update") != null
&& !"update".equals(request.getParameter("actionupdate")))
{
int id = Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("name");
String address = request.getParameter("address");
pst.executeQuery("insert into employee(id,name,address)"+"values("+id+",'"+name+"','"+address+"')");
}
else if(request.getParameter("actionupdate")!=null
&& "update".equals(request.getParameter("actionupdate"))) {
int id = Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("name");
String address =request.getParameter("address");
pst.executeUpdate("update employee set address='"+address+"',name='"+name+"'where id="+id+"");
}
ResultSet rst=pst.executeQuery("select *from employee");
while (rst.next())
{
out.print("<tr>");
out.print("<td align=center bgcolor=yellow><b> " + rst.getInt("id") + "</b></td>");
out.print("<td align=center><b>" + rst.getString("name") + "</b></td>");
out.print("<td align=center><b>" + rst.getString("address") + "</b></td>");
out.print("<form align=center action=\"./requestdata\">");
out.print("<td align=center bgcolor=yellow><a href=\"http://localhost:8082/RequestDataDemo/requestdata?id="
+rst.getInt("id")+"&action=delete\">DELETE</a></td>");
out.print("<td align=center bgcolor=yellow><a href=\"http://localhost:8082/RequestDataDemo/requestdata?id="
+rst.getInt("id")+"&name="+rst.getString("name")+"&address="+rst.getString("address")+"&actionupdate=update\">UPDATE</a></td>");
out.print("</tr>");
}
out.print("</table>");
out.print("<br><br>");
if(request.getParameter("actionupdate")!=null && "update".equals(request.getParameter("actionupdate"))) {
out.print("<form align=center action=\"./requestdata\">");
out.print("enter id :<input type=\" text\" name = \" id \" value="+request.getParameter("id")+"><br><br>");
out.print("enter name: <input type=\"text\" name = \"name\" value="+request.getParameter("name")+"><br><br>");
out.print("enter address:<input type=\"text\" name = \"address \" value="+request.getParameter("address")+"><br><br>");
out.print(" <input type=\"submit\" value =\"update\"><br><br>");
out.print("</form>");
}
else
{
out.print("<form align=center action=\"./requestdata\">");
out.print("eneter id :<input type=" + "text" + " name = " + "id><br><br>");
out.print("eneter name: <input type=" + "text" + " name = " + "name><br><br>");
out.print("eneter address:<input type=" + "text" + " name = " + "address><br><br>");
out.print(" <input type=" + "submit" + " value = " + "submit><br><br>");
out.print(" <input type=" + "reset><br><br>");
/* out.print("<input type='submit' value='delete'>"); */
out.print("</form>");
}
out.print("</body>");
out.print("</html>");
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
out.close();
}
}
my request is going to update but the records are not updating in the database
help me out of this situation
I didn't get any errors after clicking on update button the database record is not inserted in the database
I agree to all the comments that you should refactor this code. But for a first try I guess it is important to see it working.
I think you have a bit of a logical problem here: What exactly do you send when you insert a new record? I couldn't find that part.
I am guessing you want the insert block to run, so this condition:
else if(request.getParameter("id") != null&&request.getParameter("name")!=null&&request.getParameter("address")!=null &&request.getParameter("update")!=null &&!"update".equals(request.getParameter("actionupdate") ))
to be true. But if you look at the end of the line you want the "update" parameter to be present and "actionupdate" to be different than "update". But you are not setting these in your code. So this condition will always be false, hence the insert is never called.
When you press a submit button a parameter submit="" is sent to the server. This way you can tell which button was clicked. So maybe add a submit button with value="insert" and test if that is present to enter in the INSERT block.
Again, try to make this work by revisiting all your conditions and parameters and see when/if they are set and when they are true or not. And after that absolutely spend some time refactoring and practicing better techniques.
I am trying to create nodes and relations in neo4j demo.db folder using this code .Its just creating the blank demo.db folder .When i open this db folder in neo4j it showing zero nodes an relations. I am providing the relations.xls file.
public class TestAut {
private static final File DB_PATH = new File("databases/demo.db");
private static GraphDatabaseService graphDb;
private static String [] r1={"PARTNERS_JV_WITH","EXEC_JOINS","EXEC_QUITS","INVESTS_IN_TECH_IP","ACQUIRES","LAUNCHES_NEW_PRODUCT_SERVICE","LAUNCHES",
"ACQUIRE_TALENT","DOWNSIZES_TALENT","ENTER_NEW_MARKET","DELIVERS_VALUE","OPENS_NEW_CENTER"};
private static String [] r2={"PARTNERS_JV_WITH","EXEC_JOINS","EXEC_QUITS","INVESTS_IN_TECH_IP","ACQUIRES","LAUNCHES_NEW_PRODUCT_SERVICE","LAUNCHES",
"ACQUIRE_TALENT","DOWNSIZES_TALENT","ENTER_NEW_MARKET","DELIVERS_VALUE","OPENS_NEW_CENTER"};
private static Relations relations;
public static void main(String args[]) {//throws FileNotFoundException {
String fileName = "relations.xls";
Workbook workbook;
startDb();
relations=new Relations(r1,r2);
System.out.println (fileName);
BufferedReader br;
try {
br = new BufferedReader( new InputStreamReader( new FileInputStream(fileName)));
br.close();
workbook = Workbook.getWorkbook(new File(fileName));
for(int i=0;i<workbook.getNumberOfSheets();i++) {
Sheet sheet=workbook.getSheet(i);
for(int j=0;j<sheet.getRows();j++) {
Cell cell[]=sheet.getRow(j);
for(int k=0;k<cell.length;k++)
System.out.print(cell[k].getContents()+" ");
System.out.print("\n");
createNodesAndRelationship(cell[0].getContents(),cell[1].getContents(),
cell[2].getContents(),cell[3].getContents(),
cell[4].getContents(),cell[5].getContents(),cell[6].getContents(),cell[7].getContents());
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BiffException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
stopDb();
System.out.println("Done!!");
successfully.... ");
}
public static void startDb() {
graphDb = new GraphDatabaseFactory().newEmbeddedDatabase(DB_PATH);
}
public static void stopDb() {
graphDb.shutdown();
}
public static void createNodesAndRelationship(String subject,String subjecttype,String object,
String objecttype,String relationship,String headline,String newslink,String date) {
Transaction tx = graphDb.beginTx();
try
{
Result result;
result=graphDb.execute("match ("+subjecttype+"{name:\""+subject+"\"}) return "+subjecttype+".name;");
if(result.toString().equals("empty iterator")) {
//Query="create (a:"+subjecttype+"{name:\""+subject+"\"}) return a;";
result=graphDb.execute("create (a:"+subjecttype+"{name:\""+subject+"\"}) return a;");
System.out.println(result.toString());
}
//Query="match ("+objecttype+"{name:\""+object+"\"}) return "+objecttype+".name;";
result=graphDb.execute("match ("+objecttype+"{name:\""+object+"\"}) return "+objecttype+".name;");
if(result.toString().equals("empty iterator")) {
result=graphDb.execute("create (a:"+objecttype+"{name:\""+object+"\"}) return a;");
System.out.println(result.toString());
}
result=graphDb.execute("match (a:"+subjecttype+"{name:\""+subject+"\"}) "
+ "match(b:"+objecttype+"{name:\""+object+"\"}) "
+ "match (a)-[:"+relationship+"]->"
+ "(b) return a.name,b.name;");
if(result.toString().equals("empty iterator")&&relations.contains(relationship)) {
result=graphDb.execute("match (a:"+subjecttype+"{name:\""+subject+"\"}) "
+ "match(b:"+objecttype+"{name:\""+object+"\"}) "
+ "create (a)-[r:"+relationship+"{headlines:\""+
headline+"\",newslink:\""+newslink+ "\",date:\""+date+"\""+ "}]->(b) return r;");
System.out.println(result.toString());
}
tx.success();
}
finally {
tx.close();
}
}
}
This is the console output after executing this code ....
relations.xls
Southwestern Bell Corporation Company Warner Communications Company ACQUIRES TIMELINE: AT&T's Merger With Time Warner Follows Decades Of Industry Deals http://www.npr.org/sections/thetwo-way/2016/10/22/498996253/timeline-at-ts-merger-with-time-warner-follows-decades-of-industry-deals?utm_medium=RSS&utm_campaign=technology 24/10/16
Verizon Company Yahoo Company ACQUIRES TIMELINE: AT&T's Merger With Time Warner Follows Decades Of Industry Deals http://www.npr.org/sections/thetwo-way/2016/10/22/498996253/timeline-at-ts-merger-with-time-warner-follows-decades-of-industry-deals?utm_medium=RSS&utm_campaign=technology 24/10/16
AOL Company Time Warner Inc. Company ACQUIRES TIMELINE: AT&T's Merger With Time Warner Follows Decades Of Industry Deals http://www.npr.org/sections/thetwo-way/2016/10/22/498996253/timeline-at-ts-merger-with-time-warner-follows-decades-of-industry-deals?utm_medium=RSS&utm_campaign=technology 24/10/16
Comcast Company The Walt Disney Company Company ACQUIRES TIMELINE: AT&T's Merger With Time Warner Follows Decades Of Industry Deals http://www.npr.org/sections/thetwo-way/2016/10/22/498996253/timeline-at-ts-merger-with-time-warner-follows-decades-of-industry-deals?utm_medium=RSS&utm_campaign=technology 24/10/16
SBC Corporation Company Southwestern Bell Corporation Company ACQUIRES TIMELINE: AT&T's Merger With Time Warner Follows Decades Of Industry Deals http://www.npr.org/sections/thetwo-way/2016/10/22/498996253/timeline-at-ts-merger-with-time-warner-follows-decades-of-industry-deals?utm_medium=RSS&utm_campaign=technology 24/10/16
Comcast Company NBC Universal Company ACQUIRES TIMELINE: AT&T's Merger With Time Warner Follows Decades Of Industry Deals http://www.npr.org/sections/thetwo-way/2016/10/22/498996253/timeline-at-ts-merger-with-time-warner-follows-decades-of-industry-deals?utm_medium=RSS&utm_campaign=technology 24/10/16
sss Company sdadasfd Company ACQUIRES bndfhfdhedr http://www.npr.org/sections/thetwo-way/2016/10/22/498996253/timeline-at-ts-merger-with-time-warner-follows-decades-of-industry-deals?utm_medium=RSS&utm_campaign=technology 24/10/16
Done!!
Actually the if condition is returning false all the time thats why its not creating any node and relations.I just changed my if condition and now its working fine.
try
{
Result result;
result = graphDb.execute("merge (a:" + subjecttype + "{name:\"" + subject + "\"}) return a;");
result = graphDb.execute("merge (a:" + objecttype + "{name:\"" + object + "\"}) return a;");
result = graphDb.execute("merge (a:" + subjecttype + "{name:\"" + subject + "\"}) " + "merge(b:"
+ objecttype + "{name:\"" + object + "\"}) " + "merge (a)-[r:" + relationship + "{headlines:\""
+ headline + "\",newslink:\"" + newslink + "\",date:\"" + date + "\"" + "}]->(b) return r;");
tx.success();
}
finally {
tx.close();
}
Sorry to say this, but this code is really messy! Besides, we can't reproduce your results, since we don't have the data and the code is far from being a minimal example. We can't really debug for you: isolate each step, see if does anything, etc.
Here' a few tips and remarks, though.
Testing absent results
if (result.toString().equals("empty iterator"))
Really? Please, use the API instead of a string conversion, which is never a stable interface (it's not part of any contract):
if (!result.hasNext())
Variable or label?
Do the values of subjecttype and objecttype represent a variable name or the node of a label? The former doesn't really make sense (why should the query change when it's functionally the same), but the latter isn't properly used:
result=graphDb.execute("match ("+subjecttype+"{name:\""+subject+"\"}) return "+subjecttype+".name;");
subjecttype is used as a variable in the return clause, but looks like a label in the match clause, except it's missing a leading colon:
result=graphDb.execute("match (n:"+subjecttype+"{name:\""+subject+"\"}) return n.name");
(The final semi-colon is unnecessary)
You're actually using it correctly for the matching create:
result=graphDb.execute("create (a:"+subjecttype+"{name:\""+subject+"\"}) return a;");
Query parameters
Also, your query is vulnerable to "Cypher injection" (a relative of SQL injection), if subject contains quotes. Use query parameters instead:
result = graphDb.execute("match (n:" + subjecttype + " {name:{name}}) return n.name",
Collections.<String, Object>singletonMap("name", subject));
It has the added benefit of making the query generic, which means it's not parsed and its execution plan is not computed for each line (only once per label).
Use MERGE
You could replace your logic by simply using MERGE instead of MATCH + CREATE:
result = graphDb.execute("merge (n:" + subjecttype + " {name:{name}}) return n",
Collections.<String, Object>singletonMap("name", subject));
Power to Cypher
Your multiple queries could actually be reduced to a single one, except for the filter on relationship being contained in relations:
Map<String, Object> params = new HashMap<>();
params.put("subject", subject);
params.put("object", object);
params.put("headline", headline);
params.put("newslink", newslink);
params.put("date", date);
graphDb.execute(
"MERGE (a:" + subjecttype + " {name: {subject}}) " +
"MERGE (b:" + objecttype + " {name: {object}}) " +
"MERGE (a)-[r:" + relationship + "]->(b) " +
"ON CREATE SET r.headlines = {headline}, " +
" r.newslink = {newslink}, " +
" r.date = {date}",
params);
With the filter, it's actually 3 queries:
Map<String, Object> params = new HashMap<>();
params.put("subject", subject);
params.put("object", object);
params.put("headline", headline);
params.put("newslink", newslink);
params.put("date", date);
graphDb.execute("MERGE (a:" + subjecttype + " {name: {subject}})", params);
graphDb.execute("MERGE (b:" + objecttype + " {name: {object}})", params);
if (relations.contains(relationship)) {
graphDb.execute(
"MATCH (a:" + subjecttype + " {name: {subject}}) " +
"MATCH (b:" + objecttype + " {name: {object}}) " +
"MERGE (a)-[r:" + relationship + "]->(b) " +
"ON CREATE SET r.headlines = {headline}, " +
" r.newslink = {newslink}, " +
" r.date = {date}",
params);
}
Try-with-resources
Transaction is AutoCloseable, which means you should use a try-with-resources instead of managing it manually. Instead of
Transaction tx = graphDb.beginTx();
try {
// ...
} finally {
tx.close();
}
just do
try (Transaction tx = graphDb.beginTx()) {
// ...
}
I'm not sure how the start and end date work with the whole find appointments. I am getting all the rooms for a public group, then getting the rooms for the group, then getting the appointments within a date range.
But the ranges act weird, I know there are appointments on 12-19 to 12-16, but if I set the start date range to 2013-10-10 and the end date to 2013-12-28, I get nothing.
If I set the end date to 2014-01-28, I get tons of stuff that is in the range previously mentioned. Why is that?
ExchangeService service = new ExchangeService();
ExchangeCredentials credentials = new WebCredentials( "username", "pw");
service.setCredentials( credentials );
service.setUrl( new URI("my mail url") );
Folder inbox = Folder.bind(service, WellKnownFolderName.Inbox);
System.out.println("messages: " + inbox.getTotalCount());
CalendarFolder cf = CalendarFolder.bind(service, WellKnownFolderName.Calendar);
//Get all new appts?
java.text.SimpleDateFormat formatter= new java.text.SimpleDateFormat("YYYY-mm-dd");
Date startDate1 = formatter.parse("2013-11-25");
Date endDate1 = formatter.parse("2014-01-28 ");
EmailAddressCollection myRoomLists = service.getRoomLists();
for (EmailAddress item : myRoomLists)
{
System.out.println("Room Email========"+ item.toString());
NameResolutionCollection nameResolutions = service.resolveName(
item.getName(),
ResolveNameSearchLocation.DirectoryOnly,
true);
for (NameResolution nameResolution : nameResolutions)
{
ExpandGroupResults groupResults;
//System.out.println(nameResolution.getMailbox().getAddress());
try {
groupResults = service.expandGroup(nameResolution.getMailbox().getAddress());
} catch (microsoft.exchange.webservices.data.ServiceResponseException e){
groupResults=null;
System.out.println("NO INFO FOR "+nameResolution.getMailbox().getAddress());
}
if (groupResults!=null){
for (EmailAddress member : groupResults.getMembers())
{
if (member.getAddress().indexOf("rm.Cary")>-1){
System.out.println(member.getName() + " <" + member.getAddress() + ">");
FolderId folderid = new FolderId(WellKnownFolderName.Calendar, new Mailbox(member.getAddress()));
try {
FindItemsResults<Appointment> aps = service.findAppointments(folderid, new CalendarView(startDate1,endDate1));
for (Item items : aps.getItems())
{
Appointment appt = (Appointment)items;
System.out.println("SUBJECT===== " + appt.getSubject());
System.out.println("Location======== " + appt.getLocation());
System.out.println("Start Time========" + appt.getStart());
System.out.println("End Time========"+appt.getEnd());
System.out.println("Email Address========"+ appt.getOrganizer().getAddress());
System.out.println("Last Modified Time========"+appt.getLastModifiedTime());
System.out.println("Start time========"+appt.getStart());
System.out.println("End Time========"+appt.getEnd());
System.out.println("Is recurring========"+appt.getIsRecurring());
System.out.println("Duration========"+appt.getDuration().toString());
System.out.println("Organizer========"+appt.getOrganizer());
System.out.println("Required Attendees========"+appt.getRequiredAttendees().getCount());
System.out.println("Optional Attendees========"+appt.getOptionalAttendees().getCount());
System.out.println("");
}
} catch (microsoft.exchange.webservices.data.ServiceResponseException e){
System.out.println(e.getMessage());
}
}
}
}
}
}
System.out.println("End");
Change it to:
java.text.SimpleDateFormat formatter= new java.text.SimpleDateFormat("yyyy-MM-dd");
How do I fetch child user stories with Java client using Rally API?
Using Chrome's Postman client with URL https://us1.rallydev.com/slm/webservice/v2.0/HierarchicalRequirement/ObjectId/Children, I am able to fetch the children user stories.
But when I try with a Java client, like this:
QueryRequest request = new QueryRequest("/HierarchicalRequirement/ObjectId/Children");
it doesn't work.
Any pointer would be helpful.
It will take fetching "Children" collection on user stories and then hydrating it in a separate request. Here is an example based on latest version of Rally toolkit for Java:
public class GetChildStories {
public static void main(String[] args) throws Exception {
String host = "https://rally1.rallydev.com";
String apiKey = "_abc123";
String applicationName = "Find Child Stories of Epics filtered by Tag";
String workspaceRef = "/workspace/12352608129";
RallyRestApi restApi = null;
try {
restApi = new RallyRestApi(new URI(host),apiKey);
QueryRequest storyRequest = new QueryRequest("HierarchicalRequirement");
storyRequest.setWorkspace(workspaceRef);
restApi.setApplicationName(applicationName);
storyRequest.setFetch(new Fetch(new String[] {"Name", "FormattedID", "Tags", "Children"}));
storyRequest.setLimit(1000);
storyRequest.setScopedDown(false);
storyRequest.setScopedUp(false);
storyRequest.setQueryFilter((new QueryFilter("Tags.Name", "contains", "\"tag1\"")).and(new QueryFilter("DirectChildrenCount", ">", "0")));
QueryResponse storyQueryResponse = restApi.query(storyRequest);
System.out.println("Successful: " + storyQueryResponse.wasSuccessful());
System.out.println("Size: " + storyQueryResponse.getTotalResultCount());
for (int i=0; i<storyQueryResponse.getTotalResultCount();i++){
JsonObject storyJsonObject = storyQueryResponse.getResults().get(i).getAsJsonObject();
System.out.println("Name: " + storyJsonObject.get("Name") + " FormattedID: " + storyJsonObject.get("FormattedID"));
QueryRequest childrenRequest = new QueryRequest(storyJsonObject.getAsJsonObject("Children"));
childrenRequest.setFetch(new Fetch("Name","FormattedID"));
int numberOfChildren = storyJsonObject.get("DirectChildrenCount").getAsInt();
System.out.println(numberOfChildren);
//load the collection
JsonArray children = restApi.query(childrenRequest).getResults();
for (int j=0;j<numberOfChildren;j++){
System.out.println("Name: " + children.get(j).getAsJsonObject().get("Name") + children.get(j).getAsJsonObject().get("FormattedID").getAsString());
System.out.println("Name: " + children.get(0).getAsJsonObject().get("Name") + children.get(0).getAsJsonObject().get("FormattedID").getAsString());
}
}
} finally {
if (restApi != null) {
restApi.close();
}
}
}
}
I am trying to update nickname of a contact but not able to do so.
Below is the code which I have written
ArrayList<android.content.ContentProviderOperation> ops = new ArrayList<android.content.ContentProviderOperation>();
String selectArgs1 = Data.CONTACT_ID + " = ? AND " + Data.MIMETYPE + " = ? ";
String[] selectArgs2 = new String[]{ContactId, "vnd.android.cursor.item/nickname"};
ops.add(ContentProviderOperation.newUpdate(Data.CONTENT_URI)
.withSelection(selectArgs1, selectArgs2)
.withValue(ContactsContract.CommonDataKinds.Nickname.NAME, nickname)
.build());
ContentProviderResult [] cpResArr = getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
int j=cpResArr.length;
System.out.println(j);
Toast.makeText(getApplicationContext(), "value is updated", Toast.LENGTH_LONG).show();**
I got it worked, below is the piece of code which worked for me.
ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
.withValue(Data.RAW_CONTACT_ID, ContactId)
.withValue(Data.MIMETYPE, Nickname.CONTENT_ITEM_TYPE)
.withValue(Nickname.NAME, "Sister")
.withValue(Nickname.TYPE, Nickname.TYPE_CUSTOM)
.withValue(Nickname.LABEL, "Sister")
.build());
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
We need to obtain builder object and than add it to arraylist before calling applybatch.
Refer the following link for further info: http://developer.android.com/reference/android/provider/ContactsContract.CommonDataKinds.Nickname.html