Converting String to java.net.URI - java

First apologies, I'm mainly a Perl person doing some Java. I've read some literature but can't get this to give me the signature that I need:
logger.debug("Entered addRelationships");
boolean rval = true;
for(int i=0;i<relationships.length;i++)
{
URI converted_uri ;
try {
converted_uri = new URI("relationships[i].datatype") ;
} catch (URISyntaxException e) {
logger.error("Error converting datatype", e);
return rval = false ;
}
boolean r = addRelationship(context, relationships[i].subject,
relationships[i].predicate, relationships[i].object,
relationships[i].isLiteral, converted_uri);
if(r==false)
{
rval = false;
}
}
return rval;
}
The resulting error is:
addRelationship(org.fcrepo.server.Context,java.lang.String,java.lang.String,java.lang.String,boolean,java.lang.String) in org.fcrepo.server.management.DefaultManagement cannot be applied to (org.fcrepo.server.Context,java.lang.String,java.lang.String,java.lang.String,boolean,java.net.URI)
It seems to me that converted_uri is a URI at the end of this? datatype was a String in the previous release, so no gymnastics were required!

Just remove the qoutes:
converted_uri = new URI(relationships[i].datatype) ;
When you are using quotes, exactly as in perl you are dealing with string literal. If you want to refer to variable you have to mention it in code directly.

While #AlexR pointed out another problem in your code, it's not the cause of the problem you identified in your question.
You had a compile error, and an error in the syntax of the URI will only show up at runtime like the one that #AlexR identified.
The problem you have is that you are trying to pass a URI as the last argument, but the method addRelationship expects a String as the last argument. That's what the error says.
(The first part of the error says what the signature of the method is in reality, as you see it ends in java.lang.String, while the second part of the error says what type of data you are trying to give to the method, and as you see that one ends in java.net.URI)
So it seems that the URI was not changed as you expected; it still needs a String.
Solution is to change your code to:
boolean rval = true;
for(int i = 0; i < relationships.length; i++)
{
boolean r = addRelationship(context, relationships[i].subject,
relationships[i].predicate, relationships[i].object,
relationships[i].isLiteral, relationships[i].datatype);
if (!r)
{
rval = false;
}
}
return rval;

Related

Learning Java by book sierra k "head first java". Example isnt running

im starting my adventure with learning to code in Java. Im stuck on an example from book. It does compile but there is no effect when I run it. The output is just blank. Im using Visual studio code. The example says that all 3 separate files (ProstyPortal, ProstyPortalGra & PomocnikGry) should be in 1 folder. When i try to start a file with main also nothing happens. I decided to join them all into one file but still i do get no result. The code is basically one line battleship game example.
ftp://ftp.helion.pl/przyklady/javrg2.zip - in folder r05 there are files (ProstyPortal, ProstyPortalGra & PomocnikGry) from the example that should work when in the same folder but they dont.
Damn, its really hard to find whats wrong when you just start learning :P
Its an example from chapter nr 5.
I did follow all the rules and sugestions as in the book but even a straight copying the code does not help. the previous examples i did run without bigger issues.
import java.io.*;
class ProstyPortalGra {
public static void main(String[] args) {
int iloscRuchow = 0;
PomocnikGry pomocnik = new PomocnikGry();
ProstyPortal portal = new ProstyPortal();
int liczbaLosowa = (int) (Math.random() * 5);
int[] polozenie = {liczbaLosowa, liczbaLosowa+1, liczbaLosowa+2};
portal.setPolaPolozenia(polozenie);
boolean czyIstnieje = true;
while (czyIstnieje == true) {
String pole = pomocnik.pobierzDaneWejsciowe("Podaj liczbę");
String wynik = portal.sprawdz(pole);
iloscRuchow++;
if (wynik.equals("zatopiony")) {
czyIstnieje = false;
System.out.println(iloscRuchow + " ruchów");
} // koniec if
} // koniec while
} // koniec main
}
class ProstyPortal {
int [] polaPolozenia;
int iloscTrafien;
public void setPolaPolozenia(int[] ppol) {
polaPolozenia = ppol;
}
public String sprawdz(String stringPole) {
int strzal = Integer.parseInt(stringPole);
String wynik = "pudło";
for (int pole : polaPolozenia) {
if (strzal == pole) {
wynik = "trafiony";
iloscTrafien++;
break;
}
} // koniec pętli
if (iloscTrafien == polaPolozenia.length) {
wynik = "zatopiony";
}
System.out.println(wynik);
return wynik;
} // koniec metody
} // koniec klasy
class PomocnikGry {
public String pobierzDaneWejsciowe(String komunikat) {
String wierszWej = null;
System.out.print(komunikat + " ");
try {
BufferedReader sw = new BufferedReader(
new InputStreamReader(System.in));
wierszWej = sw.readLine();
if (wierszWej.length() == 0) return null;
} catch (IOException e) {
System.out.println("IOException: " + e);
}
return wierszWej;
}
}
So you want it to print something? If that's the problem, then you must make sure that the if-statement that tests whether the wynik is equal to "zatopiony" actually happens to be true. You program will only give an output, if this if-statement is true.
I separated the classes into separate files with proper names located in the same folder. Still doesnt workin and i do get this error : error: cannot find symbol.
this error occurs for every separated class. I checked all common errors from this thread:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
Files are saved with UTF-8 encoding if that means anyting. When i saves with BOM encoding i got a lot more errors

A Very Strange StringIndexOutOfBoundsException

Before asking this question , i spent around half an hour on google , but since i didn't find a solution i thought i maybe should ask here.
So basically i'm using Java Reader to read a text file and converting each line of information into an Object that i called Nation ( With a constructor of course ) and making an array out of all those objects.
The problem is that a single line on my text file goes to 75 characters. But i get an error telling me that the length is only 68 ! So Here's the part of the code where i read informations from the file :
static int lireRemplir (String nomFichier, Nation[] nations)
throws IOException
{
boolean existeFichier = true;
int n =0;
FileReader fr = null;
try {
fr = new FileReader(nomFichier);
}
catch (java.io.FileNotFoundException erreur) {
System.out.println("Probléme avec l'ouverture du fichier " + nomFichier);
existeFichier = false;
}
if (existeFichier) {
BufferedReader entree = new BufferedReader(fr);
boolean finFichier = false;
while (!finFichier) {
String uneLigne = entree.readLine();
if (uneLigne == null) {
finFichier=true;
}
else {
nations[n] = new Nation(uneLigne.charAt(0),uneLigne.substring(55,63),
uneLigne.substring(64,74),uneLigne.substring(1,15),uneLigne.substring(36,54));
n++;
}
}
entree.close();
}
return n;
}
The Error i get is :
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
begin 64, end 74, length 68
Since i'm new here i tried to post an image of my text but i couldn't, so i'll just try to hand write an exemple:
2ETATS-UNIS WASHINGTON 9629047 291289535
4CHINE PEKIN 9596960 1273111290
3JAPON KYOTO 377835 12761000
There is alot of space between the words it's like an array!
If i change the 74 to 68 i get a result when i try to print my array , but the information is missing.
Here's my constructor:
public Nation(char codeContinent, String superficie, String population, String nom, String capitale) {
this.codeContinent = codeContinent;
this.superficie = superficie;
this.population = population;
this.nom = nom;
this.capitale = capitale;
}
I hope you could help me with this! If you need to know more about my code let me know ! Thank you very much.
To avoid Runtime Exceptions, you need to be careful with your code. In cases where you are dealing with indexes of a String or an array, please check for length of the String to be greater or equal to the maximum index you are using. Enclose you code that is throwing the exception within:
if(uneLigne.length() > 74) {
nations[n] = new Nation(uneLigne.charAt(0),uneLigne.substring(55,63),
uneLigne.substring(64,74),uneLigne.substring(1,15),uneLigne.substring(36,54));
} else {
//your logic to handle the line with less than 74 characters
}
This will ensure your code does not break even if any line is smaller than expected characters.
______________________________________________________________________________
Another approach
Adding the comment as an answer:
The other way would be to use split() method of String class or StringTokenizer class to get the array/tokens if the line is delimited with space or some other character. With this, you need not break the string using substring() method where you need to worry about the lengths and possible Runtime.
Check the below code snippet using split() method, for each line you read from file, you probably have to do this way:
Nation nation = null;
String uneLigne = "2ETATS-UNIS WASHINGTON 9629047 291289535";
String[] strArray = uneLigne.split(" ");
if(strArray.length > 3) {
nation = new Nation(getContinentCodeFromFirstElement(strArray[0]), strArray[1],
strArray[2], strArray[3], strArray[4]);
}
//getContinentCodeFromFirstElement(strArray[0]) is your private method to pick the code from your first token/element.
The simpliest way to solve your problem is to change the 74 by uneLigne.length.
Here's the new code.
nations[n] = new Nation(uneLigne.charAt(0),uneLigne.substring(55,63),
uneLigne.substring(64,uneLigne.length),uneLigne.substring(1,15),uneLigne.substring(36,54));

Using Jackcess to retrieve numeric values stored in a text field gives ClassCastException

I am working with Jackcess to read and categorize an access database. It's simply meant to open the database, loop through each line, and print out individual row data to the console which meet certain conditions. It works fine, except for when I try to read numeric values. My code is below. (This code is built into a Swing GUI and gets executed when a jbutton is pressed.)
if (inv == null) { // Check to see if inventory file has been set. If not, then set it to the default reference path.
inv = rPath;
}
if (inventoryFile.exists()) { // Check to see if the reference path exists.
List<String> testTypes = jList1.getSelectedValuesList();
List<String> evalTypes = jList3.getSelectedValuesList();
List<String> grainTypes = jList2.getSelectedValuesList();
StringBuilder sb = new StringBuilder();
for (int i=0; i<=evalTypes.size()-1; i++) {
if (i<evalTypes.size()-1) {
sb.append(evalTypes.get(i)).append(" ");
}
else {
sb.append(evalTypes.get(i));
}
}
String evalType = sb.toString();
try (Database db = DatabaseBuilder.open(new File(inv));) {
Table sampleList = db.getTable("NTEP SAMPLES LIST");
Cursor cursor = CursorBuilder.createCursor(sampleList);
for (int i=0; i<=testTypes.size()-1; i++) {
if ("Sample Volume".equals(testTypes.get(i))) {
if (grainTypes.size() == 1 && "HRW".equals(grainTypes.get(0))) {
switch (evalType) {
case "GMM":
for (Row row : sampleList){
if (null != row.getString("CURRENTGAC")) {}
if ("HRW".equals(row.get("GRAIN")) && row.getDouble("CURRENTGAC")>=12.00) {
System.out.print(row.get("GRAIN") + "\t");
System.out.println(row.get("CURRENTGAC"));
}
}
break;
case "NIRT":
// some conditional code
break;
case "TW":
// some more code
break;
}
}
else {
JOptionPane.showMessageDialog(null, "Only HRW samples can be used for the selected test(s).", "Error", JOptionPane.ERROR_MESSAGE);
}
break;
}
}
}
catch (IOException ex) {
Logger.getLogger(SampleFilterGUI.class.getName()).log(Level.SEVERE, null, ex);
}
When the code is run I get the following error:
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Double
The following condition looks to be what is throwing the error.
row.getDouble("CURRENTGAC")>=12.00
It appears that when the data is read from the database, the program is reading everything as a string, even though some fields are numeric. I was attempting to cast this field as a double, but java doesn't seem to like that. I have tried using the Double.parseDouble() and Double.valueOf() commands to try converting the value (as mentioned here) but without success.
My question is, how can I convert these fields to numeric values? Is trying to type cast the way to go, or is there a different method I'm not aware of? You will also notice in the code that I created a cursor, but am not using it. The original plan was to use it for navigating through the database, but I found some example code from the jackcess webpage and decided to use that instead. Not sure if that was the right move or not, but it seemed like a simpler solution. Any help is much appreciated. Thanks.
EDIT:
To ensure the program was reading a string value from my database, I input the following code
row.get("CURRENTGAC").getClass().getName()
The output was java.lang.String, so this confirms that it is a string. As was suggested, I changed the following code
case "GMM":
for (Row row : sampleList){
if (null != row.get("CURRENTGAC"))
//System.out.println(row.get("CURRENTGAC").getClass().getName());
System.out.println(String.format("|%s|", row.getString("CURRENTGAC")));
/*if ("HRW".equals(row.get("GRAIN")) && row.getDouble("CURRENTGAC")>=12.00 && row.getDouble("CURRENTGAC")<=14.00) {
System.out.print(row.get("GRAIN") + "\t");
System.out.println(row.get("CURRENTGAC"));
}*/
}
break;
The ouput to the console from these changes is below
|9.85|
|11.76|
|9.57|
|12.98|
|10.43|
|13.08|
|10.53|
|11.46|
...
This output, although looks numeric, is still of the string type. So when I tried to run it with my conditional statement (which is commented out in the updated sample code) I still get the same java.lang.ClassCastException error that I was getting before.
Jackcess does not return all values as strings. It will retrieve the fields (columns) of a table as the appropriate Java type for that Access field type. For example, with a test table named "Table1" ...
ID DoubleField TextField
-- ----------- ---------
1 1.23 4.56
... the following Java code ...
Table t = db.getTable("Table1");
for (Row r : t) {
Object o;
Double d;
String fieldName;
fieldName = "DoubleField";
o = r.get(fieldName);
System.out.println(String.format(
"%s comes back as: %s",
fieldName,
o.getClass().getName()));
System.out.println(String.format(
"Value: %f",
o));
System.out.println();
fieldName = "TextField";
o = r.get(fieldName);
System.out.println(String.format(
"%s comes back as: %s",
fieldName,
o.getClass().getName()));
System.out.println(String.format(
"Value: %s",
o));
try {
d = r.getDouble(fieldName);
} catch (Exception x) {
System.out.println(String.format(
"r.getDouble(\"%s\") failed - %s: %s",
fieldName,
x.getClass().getName(),
x.getMessage()));
}
try {
d = Double.parseDouble(r.getString(fieldName));
System.out.println(String.format(
"Double.parseDouble(r.getString(\"%s\")) succeeded. Value: %f",
fieldName,
d));
} catch (Exception x) {
System.out.println(String.format(
"Double.parseDouble(r.getString(\"%s\")) failed: %s",
fieldName,
x.getClass().getName()));
}
System.out.println();
}
... produces:
DoubleField comes back as: java.lang.Double
Value: 1.230000
TextField comes back as: java.lang.String
Value: 4.56
r.getDouble("TextField") failed - java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Double
Double.parseDouble(r.getString("TextField")) succeeded. Value: 4.560000
If you are unable to get Double.parseDouble() to parse the string values from your database then either
they contain "funny characters" that are not apparent from the samples you posted, or
you're doing it wrong.
Additional information re: your sample file
Jackcess is returning CURRENTGAC as String because it is a Text field in the table:
The following Java code ...
Table t = db.getTable("NTEP SAMPLES LIST");
int countNotNull = 0;
int countAtLeast12 = 0;
for (Row r : t) {
String s = r.getString("CURRENTGAC");
if (s != null) {
countNotNull++;
Double d = Double.parseDouble(s);
if (d >= 12.00) {
countAtLeast12++;
}
}
}
System.out.println(String.format(
"Scan complete. Found %d non-null CURRENTGAC values, %d of which were >= 12.00.",
countNotNull,
countAtLeast12));
... produces ...
Scan complete. Found 100 non-null CURRENTGAC values, 62 of which were >= 12.00.

Iterating over tokens in HIDDEN channel

I am currently working on creating an IDE for the custom, very lua-like scripting language MobTalkerScript (MTS), which provides me with an ANTLR4 lexer. Since the specifications from the language file for MTS puts comments into the HIDDEN_CHANNEL channel, I need to tell the lexer to actually read from the HIDDEN_CHANNEL channel. This is how I tried to do that.
Mts3Lexer lexer = new Mts3Lexer(new ANTLRInputStream("<replace this with the input>"));
lexer.setTokenFactory(new CommonTokenFactory(false));
lexer.setChannel(Token.HIDDEN_CHANNEL);
Token token = lexer.emit();
int type = token.getType();
do {
switch(type) {
case Mts3Lexer.LINE_COMMENT:
case Mts3Lexer.COMMENT:
System.out.println("token "+token.getText()+" is a comment");
default:
System.out.println("token "+token.getText()+" is not a comment");
}
} while((token = lexer.nextToken()) != null && (type = token.getType()) != Token.EOF);
Now, if I use this code on the following input, nothing but token ... is not a comment gets printed to the console.
function foo()
-- this should be a single-line comment
something = "blah"
--[[ this should
be a multi-line
comment ]]--
end
The tokens containing the comments never show up, though. So I searched for the source of this problem and found the following method in the ANTLR4 Lexer class:
/** Return a token from this source; i.e., match a token on the char
* stream.
*/
#Override
public Token nextToken() {
if (_input == null) {
throw new IllegalStateException("nextToken requires a non-null input stream.");
}
// Mark start location in char stream so unbuffered streams are
// guaranteed at least have text of current token
int tokenStartMarker = _input.mark();
try{
outer:
while (true) {
if (_hitEOF) {
emitEOF();
return _token;
}
_token = null;
_channel = Token.DEFAULT_CHANNEL;
_tokenStartCharIndex = _input.index();
_tokenStartCharPositionInLine = getInterpreter().getCharPositionInLine();
_tokenStartLine = getInterpreter().getLine();
_text = null;
do {
_type = Token.INVALID_TYPE;
// System.out.println("nextToken line "+tokenStartLine+" at "+((char)input.LA(1))+
// " in mode "+mode+
// " at index "+input.index());
int ttype;
try {
ttype = getInterpreter().match(_input, _mode);
}
catch (LexerNoViableAltException e) {
notifyListeners(e); // report error
recover(e);
ttype = SKIP;
}
if ( _input.LA(1)==IntStream.EOF ) {
_hitEOF = true;
}
if ( _type == Token.INVALID_TYPE ) _type = ttype;
if ( _type ==SKIP ) {
continue outer;
}
} while ( _type ==MORE );
if ( _token == null ) emit();
return _token;
}
}
finally {
// make sure we release marker after match or
// unbuffered char stream will keep buffering
_input.release(tokenStartMarker);
}
}
The line that caught my eye was the following.
_channel = Token.DEFAULT_CHANNEL;
I don't know much about ANTLR, but apparently this line keeps the lexer in the DEFAULT_CHANNEL channel.
Is the way I tried to read from the HIDDEN_CHANNEL channel right or can't I use nextToken() with the hidden channel?
I found out why the lexer didn't give me any tokens containing the comments - I seem to have missed that the grammar file skips comments instead of putting them into the hidden channel. Contacted the author, changed the grammar file and now it works.
Note to myself: pay more attention to what you read.
For Go (golang) this snippet works for me:
import (
"github.com/antlr/antlr4/runtime/Go/antlr"
)
type antlrparser interface {
GetParser() antlr.Parser
}
func fullText(prc antlr.ParserRuleContext) string {
p := prc.(antlrparser).GetParser()
ts := p.GetTokenStream()
tx := ts.GetTextFromTokens(prc.GetStart(), prc.GetStop())
return tx
}
just pass your ctx.GetSomething() into fullText. Of course, as shown above, whitespace has to go to the hidden channel in the *.g4 file:
WS: [ \t\r\n] -> channel(HIDDEN);

enum cannot be resolved in Java

I 'm havin a problem with resolving enum.
I checked previous answers like why enum could not be resolved in JAVA?
and I did the answer but I still get the error. also followed another solution to change the compiler compliance level. but in my case it is originally set to 1.6
what should be changed here ?
Code :
CellTypes.java
public enum CellTypes {
STRING,LIST,PATH
}
in the event of canModify which is overriden
desc :
/**
* #see org.eclipse.jface.viewers.ICellModifier#canModify(java.lang.Object,
* java.lang.String)
*/
just calling setEditor method and setEditor is as follows
public void setEditor(int editorIndex, List<Object> choices, CellTypes UIType) {
try {
if (choices != null) {
String[] choicesArray = new String[choices.size()];
for (int i = 0; i < choices.size(); i++) {
choicesArray[i] = choices.get(i).toString();
}
editors[editorIndex] = new ComboBoxCellEditor(table, choicesArray, SWT.READ_ONLY);
editors[editorIndex].getControl().addTraverseListener(traverseListener);
columnEditorTypes[editorIndex] = EditorTypes.COMBO;
} else if(UIType == CellTypes.PATH) { // it gives "cannot resolve type " here
editors[editorIndex] = standardEditors.get(EditorTypes.PATH);
columnEditorTypes[editorIndex] = EditorTypes.PATH;
}
else
{
editors[editorIndex] = standardEditors.get(EditorTypes.STRING);
columnEditorTypes[editorIndex] = EditorTypes.STRING;
}}
catch(Exception e)
{
e.printStackTrace();
}
}
causes an error of cannot resolve CellTypes type
where ct is recognised as enum and its type is STRING
Change
if (ct = CellTypes.STRING)
to
if (ct == CellTypes.STRING)
You are assigning iso. comparing.
If I understood you correctly, you are comparing the String name of the enum value to an enum value. Try this:
if (CellTypes.valueOf(ct) == CellTypes.STRING)

Categories