Sample OSLC code with a "where" clause - java

Could anyone please provide sample OSLC code with a where clause for the service class?
I have just started using OSLC recently.
Here is the code that I have tried (does't work):
#GET
#Produces({OslcMediaType.APPLICATION_RDF_XML, OslcMediaType.APPLICATION_XML, OslcMediaType.APPLICATION_JSON})
public Project[] getChangeRequests(#QueryParam("oslc.where") final String where,
#QueryParam("oslc.prefix") final String prefix)
{
final List< Project> results = new ArrayList<Project>();
Map<String, String> prefixMap;
try
{
QueryUtils.parseSearchTerms(where);
prefixMap = QueryUtils.parsePrefixes(prefix);
WhereClause whereClause = QueryUtils.parseWhere(where, prefixMap);
}
catch (ParseException e)
{
e.printStackTrace();
}
final Project[] changeRequests = Persistence.getChangeRequestsForProject();
for (final Project changeRequest : changeRequests)
{
changeRequest.setServiceProvider(ServiceProviderSingleton.getServiceProviderURI());
results.add(changeRequest);
}
return results.toArray(new Project[results.size()]);
}

I just thought I will post a working piece of code. Here it is:
prefixMap = QueryUtils.parsePrefixes(prefix);
WhereClause whereClause = QueryUtils.parseWhere(where, prefixMap);
PName property = null;
String value ="";
for (SimpleTerm term : whereClause.children())
{
ComparisonTerm comparison = (ComparisonTerm)term;
String operator;
switch (comparison.operator())
{
case EQUALS:
operator = "equals";
break;
case NOT_EQUALS:
operator = "notequals";
break;
case LESS_THAN:
operator = "lessthan";
break;
case LESS_EQUALS:
operator = "lessthaneq";
break;
case GREATER_THAN:
operator = "greaterthan";
break;
default:
case GREATER_EQUALS:
operator = "greaterhaneq";
break;
}
property = comparison.property();
Value operand = comparison.operand();
value = operand.toString();
switch (operand.type())
{
case STRING:
case URI_REF:
value = value.substring(1, value.length() - 1);
break;
case BOOLEAN:
case DECIMAL:
break;
default:
throw new WebApplicationException
(new UnsupportedOperationException("Unsupported oslc.where comparison operand: " + value),Status.BAD_REQUEST);
}
}
String compareString=property.toString().substring(property.toString().indexOf(":")+1);
String val="get" + compareString.substring(0,1).toUpperCase() +compareString.substring(1);
final Project[] changeRequests = Persistence.getChangeRequestsForProject();
for (final Project changeRequest : changeRequests)
{
changeRequest.setServiceProvider(ServiceProviderSingleton.getServiceProviderURI());
Method m=changeRequest.getClass().getMethod(val, null);
if((m.invoke(changeRequest).toString().equalsIgnoreCase(value)))
{
results.add(changeRequest);
}
}

Related

Drools Unterminated Collection Element Error

I have when statement that goes from an if statement to the else statement:
rule "rule"
ruleflow-group "ruleFlow"
when
$block : Block()
$inst : BlockInstitution(blockInstitutionCategory!=null) from $block.getInstitution()
$categorycode : InstitutionCategory(Constants.INSTITUTION_CATEGORY_CODE.equals(institutionCategoryCode)) from $inst.getInstitutionCategory()
$list : BlockInstitution(Constants.validNonList not contains dealCode) from $block.getInstitution()
then
Service $service = new Service();
try {
JsonObject enquiry =
$service.execute($block.getTransaction().getNumber()).get();
if (enquiry.isEmpty()) {
$block.getBusinessValidationResult().add(ValidationResult.NOT_FOUND);
$block.getMsg().setStatusText(Constants.NOT_FOUND);
}
else {
String numberFromService = statusEnquiry.getString(Constants.NUMBER);
String cardExpiryFromService =
enquiry.getString(Constants.EXPIRY_DATE);
String paymentRequestorIdentifier =
enquiry.getString(Constants.IDENTIFIER);
String paymentExpiryDate = enquiry.getString(Constants.EXPIRY_DATE);
String statusText = enquiry.getString(Constants.STATUS_TEXT);
String providerIdentifier =
enquiry.getString(Constants.PROVIDER_IDENTIFIER);
if (Objects.nonNull(paymentExpiryDate)) {
paymentExpiryDate =
EncryptionUtilFactory.getInstance().decryptData(paymentExpiryDate);
if (paymentExpiryDate.length() == 4) {
paymentExpiryDate =
paymentExpiryDate.substring(2, 4) + paymentExpiryDate.substring(0, 2);
}
paymentExpiryDate =
EncryptionUtilFactory.getInstance().encryptData(paymentExpiryDate);
}
if (Objects.nonNull(cardExpiryFromService)) {
cardExpiryFromService =
EncryptionUtilFactory.getInstance().decryptData(cardExpiryFromService);
if (cardExpiryFromService.length() == 4) {
cardExpiryFromService =
cardExpiryFromService.substring(2, 4) + cardExpiryFromService.substring(0, 2);
}
cardExpiryFromService =
EncryptionUtilFactory.getInstance().encryptData(cardExpiryFromService);
}
$block.getTransaction().setServiceNumber(numberFromService);
$block.getTransaction().setServiceAccountExpirationDate(cardExpiryFromService);
$block.getTransaction().setPaymentExpiryDate(paymentExpiryDate);
$block
.getTransaction()
.setFlag(Constants.ID_SET.contains(providerIdentifier));
$block.getTransaction().setProviderIdentifier(providerIdentifier);
String text = $block.getTransaction().getPrimaryAccountNumber();
$block.getTransaction().setText(text);
$block.getTransaction().setStatusText(statusText);
$block
.getTransaction()
.setPaymentRequestorIdentifier(paymentRequestorIdentifier);
if (!Constants.STATUS.equals(statusText)) {
switch (statusText) {
case Constants.INACTIVE_STATUS:
$block.getBusinessValidationResult().add(ValidationResult.INACTIVE);
break;
case Constants.CANCELLED_STATUS:
$block.getBusinessValidationResult().add(ValidationResult.CANCELLED);
break;
case Constants.SUSPENDED_STATUS:
$block.getBusinessValidationResult().add(ValidationResult.SUSPENDED);
break;
default:
break;
}
}
}
} catch (Exception ex) {
$block.getBusinessValidationResult().add(ValidationResult.CALL_FAILED);
$block.getTransaction().setStatusText(Constants.NOT_FOUND);
}
end
ERROR:
[Error: unterminated collection element]
[Near : {... _FOUND); } else { String numberFr ....}]
As the code goes from the if block to the else block it gives me an error: "Unterminated Collection Element".
Is there anything you see that indicates what's wrong. I can't find anything on the Internet that discusses this error. I've found "Unterminated String Element", but nothing on collection elements.

stax parsing using java if element value blank then assign parsing element to upper element

I am parsing big xml input data using stax parser.
My input xml part will be like below
<User>
<LoginName>abcd</LoginName>
<FirstName>abcd</FirstName>
<LastName>kkk</LastName>
<CompanyName>infosys</CompanyName>
<EmailAddress>mmm#gmail.com</EmailAddress>
<CorporateEmailAddress></CorporateEmailAddress>
</User>
My stax code is as below
private static Message parseMessage(XMLStreamReader xr)
throws XMLStreamException {
String userName = null;
String content = null;
String email = null;
String comp = null;
while (xr.hasNext()) {
int event = xr.next();
switch (event) {
case XMLStreamConstants.START_ELEMENT: {
String elName = xr.getLocalName();
if (LOGIN_NAME.equals(elName)) {
userName = xr.getElementText();
} else if (CONTENT.equals(elName)) {
content = StringUtils.trimToEmpty(xr.getElementText());
content = content.replace("\n"," ");
} else if (CORP_EMAIL_ADDRESS.equals(elName)) {
email = xr.getElementText();
/*if(email.equals(""))
email ="unknown";*/
conv.emails.add(email);
}
else if (COMPANY_NAME.equals(elName)) {
comp = xr.getElementText();
conv.comps.add(comp);
//System.out.println(comp);
}
break;
}
case XMLStreamConstants.END_ELEMENT: {
String elName = xr.getLocalName();
if (MESSAGE.equals(elName)) {
return new Message(userName, content,email);
}
break;
}
case XMLStreamConstants.END_DOCUMENT:
throw new XMLStreamException("xml not well-formed: <"
+ MESSAGE + "> tag not closed");
}
}
here in code if xr.getElementText(email) is null as doesnot have any value. SO in this case I want to use tag value
So how to assign again xr.elementText to loginvalue? only when cor-email is null
Please help

String statement returning null from switch statement

I am currently working on an Android application that allows you to watch streaming video in a VideoView. I have a method for allowing you to select one of four streams via a switch statement. That is working correctly and the code for that is as follows:
public void playStream(int position) {
switch (position) {
case 0:
streamOn = true;
streamPos = 0;
logString = "M";
posSelected = "0";
break;
case 1:
streamOn = true;
streamPos = 1;
logString = "J";
posSelected = "1";
break;
case 2:
streamOn = true;
streamPos = 2;
logString = "B";
posSelected = "2";
break;
case 3:
streamOn = true;
streamPos = 3;
logString = "N";
posSelected = "3";
break;
default:
break;
}
checkStreamLink(position);
Log.wtf(logString, posSelected);
Log.wtf(logString, streamURL);
}
What is not working correctly is that in this method for selecting the stream, I have a call to another method ( checkStreamLink(); ) that runs a thread. Depending on which stream you have selected, the thread will call another method that opens up a webpage, reads a line of text, and then sets that text to a String streamURL. The code for those two methods is as follows:
public void checkStreamLink(final int position) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
switch (position) {
case 0:
streamURL = getStreamLink("LINK 0 GOES HERE");
break;
case 1:
streamURL = getStreamLink("LINK 1 GOES HERE");
break;
case 2:
streamURL = getStreamLink("LINK 2 GOES HERE");
break;
case 3:
streamURL = getStreamLink("LINK 3 GOES HERE");
break;
default:
break;
}
}
catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
public String getStreamLink (String textSource) {
URL streamURL;
String errorParsingURL = "ERROR PARSING URL";
try {
streamURL = new URL(textSource);
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(streamURL.openStream()));
String StringBuffer;
String stringText = "";
while ((StringBuffer = bufferReader.readLine()) != null) {
stringText += StringBuffer;
}
bufferReader.close();
return stringText;
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return errorParsingURL;
}
The issue I'm having is that the String streamURL is returning null on its first use as evidenced by the Log statements I have included. Each time you select a stream after that, the String streamURL returns the text that you should have received the previous time you select a stream. I cannot seem to figure out why this is happening and I would appreciate any assistance.
You are getting a null because getStreamLink is returning its value after you have already printed the result. Print the result log messages at the end of the getStreamLink method to see the actual value which is being returned, and call any additional functionality at that point as well.

Having trouble with reading a txt file with one line and multiple variables

(Fixed) I am new to Java (Which you probably will be able to tell by the inefficiency of code) and I am having a problem reading data from a text file.
Here is an example of how I create the file and write my data to the file.
final String GString = "c:/GradeCalc/java/files";
Path Gpath = Paths.get(GString);
if (Files.notExists( Gpath )){
try {
Files.createDirectories(Gpath);
} catch (IOException e2) {
System.out.println(e2);
}
}
final String Gfile = "Grades.txt";
Path filePath = Paths.get(GString, Gfile);
if (Files.notExists (filePath)) {
try {
Files.createFile (filePath);
} catch (IOException e1) {
System.out.println(e1);
}
}
File gradeFile = filePath.toFile();
try (PrintWriter out = new PrintWriter(
new BufferedWriter(
new FileWriter (gradeFile))))
{
if (BQ1Num != null){
out.print(BQ1Num + "\t" );
}else{
out.print("0.0"+"\t");}
if (BQ2Num != null){
out.print(BQ2Num + "\t" );
}else{
out.print("0.0"+"\t");}
if (BQ3Num != null){
out.print(BQ3Num + "\t" );
}else{
out.print("0.0"+"\t");}
if (BQ4Num != null){
out.println(BQ4Num + "\t" );
}else{
out.println("0.0"+"\t");}
out.close ();
}
catch (IOException a)
{
System.out.println (a);
}
Writting the data to the file seems to work perfectly. My problem arrises when I try to read that data and set it to a variable.
Here is an example of how I attempt to read the data from said file and assign the data to variables, then use those variables.
try (BufferedReader in = new BufferedReader(new FileReader(Gfile))){
String line = in.readLine();
while(line != null){
String[] columns = line.split("\t");
BQ1RetrievedNum = columns [0];
BQ2RetrievedNum = columns [1];
BQ3RetrievedNum = columns [2];
BQ4RetrievedNum = columns [3];
line = in.readLine();
}
}
catch(IOException b){
System.out.println(b);
}
if (BQ1RetrievedNum != null ){
BQ1.setText(" Quarter 1 " +BQ1RetrievedNum+ "%");
}
if (BQ2RetrievedNum != null){
BQ2.setText(" Quarter 2 " +BQ2RetrievedNum+ "%");
}
if (BQ3RetrievedNum != null){
BQ3.setText(" Quarter 3 " +BQ1RetrievedNum+ "%");
}
if (BQ4RetrievedNum != null){
BQ4.setText(" Quarter 4 " +BQ1RetrievedNum+ "%");
}
Whenever I run my program, I get an ArrayIndexOutOfBoundsException.
I've been searching for hours on how to fix this exception, but with no success.
Here is what the contents of the Grades.txt look like.
43.0 0.0 0.0 0.0
Here is the code for the fileReader that I now have after some editing.
try (BufferedReader in = new BufferedReader(new FileReader(Gfile))){
String line = in.readLine();
line = in.readLine();
String[]columns = line.split("\t");
for(int i=0;i<4;i++) {
if(i<columns.length) {
switch(i) {
case 1: BQ1RetrievedNum = columns[0];
break;
case 2: BQ2RetrievedNum = columns[1];
break;
case 3: BQ3RetrievedNum = columns[2];
break;
case 4: BQ4RetrievedNum = columns [3];
break;
}
}
}
}
catch(IOException b){
System.out.println(b);
}
I keep getting a NullPointerException on this line:
String[]columns = line.split("\t");
This is the code for my repaired reader.
try (BufferedReader reader = Files.newBufferedReader(filePath, ENCODING )){
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
String[]columns = line.split("/");
BQ1RetrievedNum = "";
BQ2RetrievedNum = "";
BQ3RetrievedNum = "";
BQ4RetrievedNum = "";
System.out.println(columns.length);
for(int i=0;i<4;i++) {
if(i<columns.length) {
switch(i) {
case 0: BQ1RetrievedNum = columns[0];
break;
case 1: BQ2RetrievedNum = columns[1];
break;
case 2: BQ3RetrievedNum = columns[2];
break;
case 3: BQ4RetrievedNum = columns[3];
break;
}
}
}
System.out.println("1: "+BQ1RetrievedNum);
System.out.println("2: "+BQ2RetrievedNum);
System.out.println("3: "+BQ3RetrievedNum);
System.out.println("4: "+BQ4RetrievedNum);
}
}
catch(IOException b){
System.out.println(b);
}
When you split according to \t:
String[] columns = line.split("\t");
You don't check the length of the returned array. You're getting the exception in one of these lines:
BQ1RetrievedNum = columns [0];
BQ2RetrievedNum = columns [1];
BQ3RetrievedNum = columns [2];
BQ4RetrievedNum = columns [3];
Before doing that, make sure the array has 4 elements.
You can do something like this:
for(int i=0;i<4;i++) {
if(i<columns.length) {
switch(i) {
case 1: BQ1RetrievedNum = columns[0];
break;
case 2: BQ2RetrievedNum = columns[1];
break;
//...
}
}
}
See what is the length of the array
System.out.println(columns.length);
It may not contains expected number of values
EDIT: Following code work for me. Case values are edited.
String line = "43.0 0.0 0.0 0.0";
String[]columns = line.split("\t");
String output1 = "";
String output2 = "";
String output3 = "";
String output4 = "";
System.out.println(columns.length);
for(int i=0;i<4;i++) {
if(i<columns.length) {
switch(i) {
case 0: output1 = columns[0];
break;
case 1: output2 = columns[1];
break;
case 2: output3 = columns[2];
break;
case 3: output4 = columns[3];
break;
}
}
}
System.out.println("1: "+output1);
System.out.println("2: "+output2);
System.out.println("3: "+output3);
System.out.println("4: "+output4);
String.split("") doesn't throw NullPointerException

Android: How to parse HTML Table into ListView?

Hello i want to parse a HTML Table into a Android ListView but i don't know where to start. The Table has a lot of information. Could someone help me to start with this?
Thanks in advance!
The HTML Table: http://intranet.staring.nl/toepassingen/rooster/lochem/2W2/2012090320120909/2W01533.htm (Just click view source).
You will first need to parse the HTML table into a data structure, and then use ListView to display that information. Try using the JSoup library to do the HTML parsing: http://jsoup.org/cookbook/introduction/parsing-a-document
I don't know if you already got your answer here but I did the same with the link you suggest, I will post my code here but it is still very messy and don't apply for the newest timetable(9th hour)
Im using HTML Cleaner library for parsing the html:
try {
HtmlCleaner hc = new HtmlCleaner();
CleanerProperties cp = hc.getProperties();
cp.setAllowHtmlInsideAttributes(true);
cp.setAllowMultiWordAttributes(true);
cp.setRecognizeUnicodeChars(true);
cp.setOmitComments(true);
String loc = sp.getString( Constants.pref_locatie , "" );
String per = sp.getString( Constants.pref_persoon , "" );
String oob = sp.getString( Constants.pref_onderofboven , "" );
int counteruurmax;
int[] pauze;
if (oob.contains("onder")){
pauze = Constants.pauzeo;
} else if (oob.contains("boven")) {
pauze = Constants.pauzeb;
} else {
return false;
}
String url = "";
if (loc.contains("lochem")) {
url += Constants.RoosterLochem;
url += t.getDatum();
url += "/";
url += per;
counteruurmax = 11;
} else if (loc.contains("herenlaan")) {
url += Constants.RoosterHerenlaan;
url += per;
counteruurmax = 13;
} else if (loc.contains("beukenlaan")) {
url += Constants.RoosterBeukenlaan;
url += per;
counteruurmax = 11;
} else {
return false;
}
String htmlcode = t.getHtml(url);
TagNode html = hc.clean(htmlcode);
Document doc = new DomSerializer(cp, true).createDOM(html);
XPath xp = XPathFactory.newInstance().newXPath();
NodeList nl = (NodeList) xp.evaluate(Constants.XPathRooster, doc, XPathConstants.NODESET);
int counteruur = 1;
int counterdag = 1;
int decreaser = 0;
Boolean isPauze = false;
RoosterItems RItems = new RoosterItems();
RoosterItem RItem = null;
for (int i = 0; i < nl.getLength(); i++){
if ((counteruur == pauze[0]) || (counteruur == pauze[1]) || (counteruur == pauze[2])) {
isPauze = true;
decreaser++;
}
if (!isPauze) {
RItem = new RoosterItem();
switch (counterdag){
case 1:
RItem.setDag("ma");
break;
case 2:
RItem.setDag("di");
break;
case 3:
RItem.setDag("wo");
break;
case 4:
RItem.setDag("do");
break;
case 5:
RItem.setDag("vr");
break;
}
Node n = nl.item(i);
String content = n.getTextContent();
if (content.length() > 1) {
RItem.setUur(""+(counteruur-decreaser));
NodeList t1 = n.getChildNodes();
NodeList t2 = t1.item(0).getChildNodes();
NodeList t3 = t2.item(0).getChildNodes();
for (int j = 0; j < t3.getLength(); j++) {
Node temp = t3.item(j);
if (t3.getLength() == 3) {
switch (j) {
case 0:
RItem.setLes(""+temp.getTextContent());
break;
case 1:
RItem.setLokaal(""+temp.getTextContent());
break;
case 2:
RItem.setDocent(""+temp.getTextContent());
break;
default:
return false;
}
} else if (t3.getLength() == 4) {
switch (j) {
case 0:
break;
case 1:
RItem.setLes("tts. " + temp.getTextContent());
break;
case 2:
RItem.setLokaal(""+temp.getTextContent());
break;
case 3:
RItem.setDocent(""+temp.getTextContent());
break;
default:
return false;
}
} else if (t3.getLength() == 1) {
RItem.setLes(""+temp.getTextContent());
} else {
return false;
}
}
} else {
RItem.setUur("" + (counteruur-decreaser));
RItem.setLokaal("Vrij");
}
RItems.add(RItem);
}
if (counteruur == counteruurmax) { counteruur = 0; counterdag++; decreaser = 0;}
counteruur++;
isPauze = false;
}
if (RItems.size() > 0) {
mSQL = new RoosterSQLAdapter(mContext);
mSQL.openToWrite();
mSQL.deleteAll();
for (int j = 0; j < RItems.size(); j++) {
RoosterItem insert = RItems.get(j);
mSQL.insert(insert.getDag(), insert.getUur(), insert.getLes(), insert.getLokaal(), insert.getDocent());
}
if (mSQL != null) mSQL.close();
}
return true;
} catch (ParserConfigurationException e) {
e.printStackTrace();
return false;
} catch (XPathExpressionException e) {
e.printStackTrace();
return false;
}
There are a few constants but I think you can guess them yourself;) and otherwise you know how to ask me for them:)
The RoosterItem class will hold all variables of an hour, and the RoosterItems will hold more than one RoosterItem
Good Luck!
So far i think JSoup is one of the best way to extract or manipulate the HTML.....
See this link :
http://jsoup.org/
But somehow.... this did't worked in my case, so i converted the entire HTML code into String, then parsed it.....

Categories