NullPointerException using DOMParser and selectSingleNode - xpath

String url = "http://www.amazon.com/Classic-Starts-Great-Expectations/dp/1402766459/ref=sr_1_1?s=books&ie=UTF8&qid=1294405505&sr=1-1";
DOMParser parser = new DOMParser();
parser.parse(url);
Document document = parser.getDocument();
DOMReader reader = new DOMReader();
org.dom4j.Document nhddoc = reader.read(document);
//book price
Node price = nhddoc.selectSingleNode("/HTML/BODY/DIV[2]/FORM/TABLE[3]/TBODY/TR/TD/DIV/TABLE/TBODY/TR/TD[2]/B");
System.out.println(price.getText().toString().trim());
the error i get is :
Exception in thread "main" java.lang.NullPointerException
at nekodom4j.Main.main(Main.java:44)
does the null pointer exception means no node was selected ?

I have no particular idea what the cause of the problem might be, but the first thing I would do to debug it would be to walk the path one level at a time and see where it fails to return what you expect.
Node html = nhddoc.selectSingleNode("/HTML");
/* maybe print out some information about the Node just acquired */
Node body = html.selectSingleNode("/BODY");
etc...

Related

is it possible to create a message which has a field with its own type with protocol buffer

Is it possible to define a message which has a field of its own type as in linked lists with protocol buffers? For example the value of next field could be null at the end of the list.
message Node {
string name = 1;
Node next = 2;
}
I know you asked how to make a custom type. The documentation mentions to try to avoid that. I find that you can model almost anything with the parts / types that are built in. To make a list of nodes with the built in types do this:
message ResponseOfNodes {
repeated Node nodes = 1;
}
message Node {
string name = 1;
string someOtherData = 2;
}
Here's code that uses the generated code / list.
// make a node so it can be added to the list.
Node node1 = Node.newBuilder().setName("a name").setSomeOtherData("etc").build();
// Build a response (ResponseOfNodes) that will get nodes added to its list. Add two Nodes.
ResponseOfNodes.Builder responseBuilder = ResponseOfNodes.newBuilder().addNodes(node1);
responseBuilder.addNodes(node1.toBuilder().setName("name 2").build());
// build the ResponseOfNodes and print it out.
ResponseOfNodes responseOfNodes = responseBuilder.build();
log.info("the list: {}", responseOfNodes.getNodesList());
Console Output;
[INFO ] [main] - Hello I am a client.
[INFO ] [main] - the list: [name: "a name"
someOtherData: "etc"
, name: "name 2"
someOtherData: "etc"

Linq to entities giving error when generic repository is used with List<T> object

In my ASP.NET Web API project, I am trying to use the generic repositories with the List objects under one of the methods. But it is throwing exception
Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll
System.Data.Entity.Core.EntityCommandExecutionException: Calling 'Read' when the data reader is closed is not a valid operation. --->
System.Data.SqlClient.SqlException: Execution Timeout Expired. The
timeout period elapsed prior to completion of the operation or the
server is not responding. ---> System.ComponentModel.Win32Exception:
The wait operation timed out
lstFinalResult object contains few rows. partnerRepo is a generic repo and will have data at the later stage, i suppose.
Please advise, where am i making the mistake. Can we mix the List with generic repository objects in the linq query ?
Here is the linq code :-
List<UserDocumentResult> lstFinalResult = new List<UserDocumentResult>();
foreach (DocumentMapping dm in lstMappings)
{
lstFinalResult.Add(new UserDocumentResult { PID = dm.PartnerID,
DocMappingID = dm.DocumentMappingID,
EntityType = "",
Name = ""
});
}
var partnerRepo = _docRepository.PtGenericRepo.Get();
var entityCodesRepo = _docRepository.EntityCodeGenericRepo.Get();
---While debugging, I am getting error in the below code only.
var qualifiedPartnerSet = (from tmp in lstFinalResult
join px in partnerRepo on tmp.PID equals px.PartnerID
join ecx in entityCodesRepo on px.EntityCodeID equals ecx.EntityCodeID
select new UserDocumentResult
{
PID = px.PartnerID,
MappingID = tmp.MappingID,
EntityType = ecx.DisLabel.Trim(),
Name = px.NameLine1.Trim() + px.NameLine2.Trim(),
}).ToList();

MANAGED_CLASS_MAPPING_ERROR given javaClass 'class java.util.ArrayList' is mapped to ListType, expected ManagedType

We are starting to experiment with JaVers in our application. We want to track changes to orders after they are placed by users. So it's your typical order object with the main order object, items, item options, etc. About half the time we go to run the test program we are receiving this exception:
130 [main] INFO org.javers.core.JaversBuilder - JaVers instance is up
& ready Exception in thread "main" JaversException:
MANAGED_CLASS_MAPPING_ERROR given javaClass 'class
java.util.ArrayList' is mapped to ListType, expected ManagedType at
org.javers.core.metamodel.type.TypeMapper.getJaversManagedType(TypeMapper.java:149)
at
org.javers.core.metamodel.type.TypeMapper.getJaversManagedType(TypeMapper.java:132)
at
org.javers.core.metamodel.object.GlobalIdFactory.createId(GlobalIdFactory.java:39)
at
org.javers.core.graph.LiveCdoFactory.create(LiveCdoFactory.java:24)
at org.javers.core.graph.EdgeBuilder.asCdo(EdgeBuilder.java:39) at
org.javers.core.graph.EdgeBuilder.buildSingleEdge(EdgeBuilder.java:32)
at
org.javers.core.graph.ObjectGraphBuilder.buildSingleEdges(ObjectGraphBuilder.java:81)
at
org.javers.core.graph.ObjectGraphBuilder.buildEdges(ObjectGraphBuilder.java:71)
at
org.javers.core.graph.ObjectGraphBuilder.buildGraphFromCdo(ObjectGraphBuilder.java:59)
at
org.javers.core.graph.ObjectGraphBuilder.buildGraph(ObjectGraphBuilder.java:48)
at
org.javers.core.graph.LiveGraphFactory.createLiveGraph(LiveGraphFactory.java:39)
at org.javers.core.diff.DiffFactory.buildGraph(DiffFactory.java:109)
at org.javers.core.diff.DiffFactory.compare(DiffFactory.java:64) at
org.javers.core.JaversCore.compare(JaversCore.java:104)
We just rerun the program and eventually it works. The code basically looks like this.
// Original database object
OrderVO oldOrder = // load from database.
// Changed database object
OrderVO newOrder = // load from database.
// Change the email
newOrder.setEmail("test#test.com");
// Simulate changing quantity and item id on items
for (OrderItemVO OrderItemVO : newOrder.getItems()) {
OrderItemVO.setMerchantItemId(OrderItemVO.getMerchantItemId() + "A");
OrderItemVO.setQuantity(OrderItemVO.getQuantity().add(1));
}
// Remove the first item
OrderItemVO[] items = new OrderItemVO[newOrder.getItems().length - 1];
System.arraycopy(newOrder.getItems(), 1, items, 0, items.length);
newOrder.setItems(items);
// Run comparison
Javers javers = JaversBuilder.javers().withListCompareAlgorithm(ListCompareAlgorithm.LEVENSHTEIN_DISTANCE).build();
Diff diff = javers.compare(oldOrder, newOrder);

SearchPhaseExecutionException with Basic Embedded Elasticsearch

I am trying out Elasticsearch with a basic Scala program, using the Java API:
object TestES {
var node:Node = NodeBuilder.nodeBuilder.node
var client:Client = node.client
def insertDoc(id:String, doc:String) = {
client.prepareIndex("myindex", "test", id).
setSource(doc).execute.actionGet
}
def countHits(qry:String) = {
client.prepareSearch("myindex").setTypes("test").
setQuery(queryString(qry)).execute.actionGet.
getHits.getTotalHits
}
def waitForGreen = client.admin.cluster.prepareHealth().
setWaitForGreenStatus.execute.actionGet
def main(args: Array[String]): Unit = {
insertDoc("1", """{"foo":"bar"}""")
//waitForGreen
println(countHits("bar"))
node.close
}
}
This works, and the insert + query run in under one second. If I comment out the insert, I get the following exception:
Exception in thread "main" org.elasticsearch.action.search.SearchPhaseExecutionException:
Failed to execute phase [query], total failure;
shardFailures {[_na_][myindex][0]: No active shards}
If I enable the waitForGreen line, it works again, but takes over half a minute to run both lines.
This seems quite odd. Is inserting a document a must before running a query, or is there a better way?
Inserting a document is not needed to run a query, but having the index created is required.
When you insert a document and the index doesn't exist, it will be automatically created.
If you want to avoid document creation, you can create only the index using the API :
client.admin.indices.prepareCreate("myindex").execute.actionGet

SharePoint, List.Items and List.GetItems(Query) and Linq

Following on from suggestions, I am trying to use List.GetItems(Query) to retrieve my initial data subset rather than the entire list contents via List.Items. However, whereas List.Items.Cast() results in a usable IEnumerable for Linq, List.GetItems(Query).Cast() does not.
Working Code:
IEnumerable<SPListItem> results = SPContext.Current.Web.Lists[ListName].Items.Cast<SPListItem>().Where(item => item["Date"] != null).Where(item => DateTime.Parse(item["Date"].ToString()) >= StartDate).Where(item => DateTime.Parse(item["Date"].ToString()) <= EndDate);
MessageLine = results.Count().ToString();
Non-working Code:
string SPStartDate = SPUtility.CreateISO8601DateTimeFromSystemDateTime(this.StartDate);
string SPEndDate = SPUtility.CreateISO8601DateTimeFromSystemDateTime(this.EndDate);
SPQuery MyQuery = new SPQuery();
MyQuery.Query = "<Where><And><And><Geq><FieldRef Name='Date'/><Value Type='DateTime'>" + SPStartDate + "</Value></Geq><Leq><FieldRef Name='Date'/><Value Type='DateTime'>" + SPEndDate + "</Value></Leq></And></Where>";
IEnumerable<SPListItem> results = SPContext.Current.Web.Lists[ListName].GetItems(MyQuery).Cast<SPListItem>();
MessageLine = results.Count().ToString();
The List.GetItems(Query).Cast() method produces the following Exception on the .Count() line:
Microsoft.SharePoint.SPException:
Cannot complete this action. Please
try again. --->
System.Runtime.InteropServices.COMException
(0x80004005): Cannot complete this
action. Please try again. at
Microsoft.SharePoint.Library.SPRequestInternalClass.GetListItemDataWithCallback(String
bstrUrl, String bstrListName, String
bstrViewName, String bstrViewXml,
SAFEARRAYFLAGS fSafeArrayFlags,
ISP2DSafeArrayWriter pSACallback,
ISPDataCallback pPagingCallback,
ISPDataCallback pSchemaCallback) at
Microsoft.SharePoint.Library.SPRequest.GetListItemDataWithCallback(String
bstrUrl, String bstrListName, String
bstrViewName, String bstrViewXml,
SAFEARRAYFLAGS fSafeArrayFlags,
ISP2DSafeArrayWriter pSACallback,
ISPDataCallback pPagingCallback,
ISPDataCallback pSchemaCallback) ---
End of inner exception stack trace ---
at
Microsoft.SharePoint.Library.SPRequest.GetListItemDataWithCallback(String
bstrUrl, String bstrListName, String
bstrViewName, String bstrViewXml,
SAFEARRAYFLAGS fSafeArrayFlags,
ISP2DSafeArrayWriter pSACallback,
ISPDataCallback pPagingCallback,
ISPDataCallback pSchemaCallback) at
Microsoft.SharePoint.SPListItemCollection.EnsureListItemsData()
at
Microsoft.SharePoint.SPListItemCollection.Undirty()
at
Microsoft.SharePoint.SPBaseCollection.System.Collections.IEnumerable.GetEnumerator()
at
System.Linq.Enumerable.d__aa1.MoveNext()
at
System.Linq.Enumerable.Count[TSource](IEnumerable1
source) at
Test.GetTransactionsInPeriod() at
Test.CreateChildControls()
Can anyone suggest anything?
From the error message it looks like the CAML Query is wrong. You may want to run it through something like U2U's CAML Query Builder to double check. The error message is thrown by SharePoint before the requested casts. Glancing over it, I think you have an extra <And> at the beginning (<Where><And><And>)
By the way: Don't use SPWeb.Lists[Name]. This will load every list in the SPWeb (including Metadata), which is rather resource intensive. One of the SPWeb.GetList or SPWeb.Lists.GetList methods is better.

Resources