I want to make a class in Java called URLTransformer.
Let's say I have a blog entry and want to format my text (e.g. because some words are in Swedish).
This is my code right now:
public class URLTransformer {
public static void main(String[] args) {
String basurl = "http://www.mybloggsys.com/user_abc/";
String[] rubriker = {
"Nu Kommer Vintern till aland",
"Onskningar ar nagot man vill uppna",
"Just English Letters"
};
for (String rubrik : rubriker) {
String rubrik2=rubrik.toLowerCase().replace(" ", "_").replace("Å", "a").replace("å", "a").replace("ä", "a").replace("Ö", "o");
URLTransformer transformer = new URLTransformer();
URLTransformer(basurl, rubrik2);
String url = transformer.getURL();
String aElement = transformer.getAElement();
System.out.println(rubrik2);
System.out.println(url);
System.out.println(aElement);
}
URLTransformer transformer = new URLTransformer();
}
private String getAElement() {
// TODO Auto-generated method stub
return null;
}
private String getURL() {
// TODO Auto-generated method stub
return null;
}
private static void URLTransformer(String basurl, String rubrik2) {
// TODO Auto-generated method stub
}
}
Now, I can get Eclipse to execute this code but I get a lot of "Null" messages. Is it possible to not get it or does it even matter after compiling my code? In my homework task, the final code should look exactly like this:
Nu kommer Vinter till Åland
http://www.mybloggsys.com/user_abc/nu_kommer_vintern_till_aland
Nu Kommer Vintern till Åland
Önskningar är något man vill uppnå
(url link)/onskningar_ar_nagot_man_vill_uppna
Önskningar är något man vill uppnå
Just English Letters
(url link)/just_english_letters
Just English Letters
Any help will be greatly appreciated, it feels like it almost works just this </a> element thing and null messages that are left.
Here is the code for you:
public class URLTransformer {
private String baseurl;
private String baseString;
// Constructor of the class that uses a base url and a base string
public URLTransformer(String baseurl, String baseString) {
super();
this.baseurl = baseurl;
this.baseString = baseString;
}
// Method that return the href calculated
private String getHref() {
// transform the string to remove non english characters with _ instead of spaces
return baseurl + baseString.toLowerCase().replace(" ", "_").replace("Å", "a").replace("å", "a").replace("ä", "a").replace("Ö", "o");
}
// return a <a> link with a call to the href link method
private String getAElement() {
StringBuilder aElement = new StringBuilder();
aElement.append("<a href=\"");
aElement.append(getHref());
aElement.append("\">");
aElement.append(baseString);
aElement.append("</a>");
return aElement.toString();
}
public static void main(String[] args) {
String basurl = "http://www.mybloggsys.com/user_abc/";
String[] rubriker = { "Nu Kommer Vintern till aland", "Onskningar ar nagot man vill uppna", "Just English Letters" };
// iterate over the
for (String rubrik : rubriker) {
URLTransformer transformer = new URLTransformer(basurl, rubrik); // creation of the class object that is able to make a link from the string
System.out.println(rubrik); // prints the provided string
System.out.println(transformer.getHref()); // use of the getHref method to get an url from the string
System.out.println(transformer.getAElement()); // display of the <a> element
}
}
}
Note : I've added comments to the code and see my comment below to have explanations on what was wrong with the provided code.
Related
I am trying to divide a text file to 150 parts, so I made a function in the object class itself.
This is the full object class :
public TehilimEpisode(int EpisodeID, String[] ab)
{
this.EpisodeID=EpisodeID;
this.Perek=ab;
}
public static void setperek(TehilimEpisode[] pirkoni) throws IOException
{
BufferedReader inputReader = new BufferedReader(new FileReader("C:\\\\*.txt"));
String nextLine; String[] ab;
while ((nextLine = inputReader.readLine()) != null)
{
for(int i=1; i<=150;i++)
{
ab = nextLine.split("$");
pirkoni[i] = new TehilimEpisode(i, ab);
}
}
for(int i=1; i<=150; i++)
pirkoni.toString();
}
#Override
public String toString() {
return String.format(EpisodeID + " & " + Arrays.toString(Perek));
}
#Override
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
return super.clone();
}
#Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
return super.equals(obj);
}
#Override
protected void finalize() throws Throwable {
// TODO Auto-generated method stub
super.finalize();
}
#Override
public int hashCode() {
// TODO Auto-generated method stub
return super.hashCode();
}
}
The function name is setperek. when I am trying to run the function from the main class, it is writing this error :
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at TehilimEpisode.setperek(TehilimEpisode.java:25)
at main.main(main.java:48)
You have to read the whole txt in single string then split it by "$".Here is the example in which I use delimiter \\z that read the whole file in single string and then I split the string by "$".In below example we read the whole book in single line then split it into episode by "$" as you added in your book at the end of episode.
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class FileReadingWithScanner {
public static void main(String[] args) throws IOException {
File file = new File("D:\\book.txt");
String book = "";
Scanner sc = new Scanner(file);
/* Using this delimiter you will be able to read whole file in single line. */
sc.useDelimiter("\\Z");
book = sc.next();
String[] episodeArr = book.split("$");
//Do whatever you want.
}
}
Update
String.split() takes in regex as argument and $ is a metacharacter in Java regex API. Therefore, you need to escape it:
Use this book.split("\\$");
The problem is caused here: ab = scanner.nextLine().split("$"); pirkoni[i] = new TehilimEpisode(i, ab);. Imagine there's no next line. It will try to create the TehilimEpisode object with ab = null. To fix this you should check if there's a next line: for(int i=1; i<=150 && scanner.hasNextLine() ;i++). Select as answer if It worked! :D
Change your for loop to below, here i change scanner.nextLine() method to nextLine String.
while ((nextLine = inputReader.readLine()) != null)
{
for(int i=1; i<=150;i++)
{
ab = nextLine.split("$");
pirkoni[i] = new TehilimEpisode(i, ab);
}
}
There is no need for scanner class in your code, you already have BufferedReader to read the file. Having both is redundant.
toString() method override
Add something like below method to your class.
#Override
public String toString() {
return String.format(EpisodeID + " & " + Arrays.toString(Perek));
}
I want to parse a string in order to get the value of an attribute.For example i have the following String:
calling_number=+385317KFWVM, call_direction=I, conversation_duration=29,
Each attribute and its value is separated by commas.I have declared the name and the type of each attribute in a class named MessageBean.
public static void main(String[] args){
try {
MessageBean attributes_bean = MessageBean.parse("calling_number=+385317KFWVM, call_direction=I, conversation_duration=29,");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public class MessageBean {
private String calling_number;
private String call_direction;
private int conversation_duration;
public static MessageBean parse(String line) throws UnsupportedEncodingException {
MessageBean bean = new MessageBean();
line = URLDecoder.decode(line, "utf-8");
bean.setCalling_number(MessageBean.getParameter(line, "calling_number"));
bean.setCall_direction(MessageBean.getParameter(line, "call_direction"));
bean.setConversation_duration(Integer.parseInt(MessageBean.getParameter(line, "conversation_duration")));
return bean;
}
private static String getParameter(String line, String name) {
String value = "";
Pattern p = Pattern.compile(name + "=([^,]*),");
Matcher m = p.matcher(line);
if (m.find()) {
value = m.group(1);
}
return value;
}
}
I expect my result to be +385317KFWVM, I, 29 .
Instead i get 385317KFWVM, I, 29 which means that i miss the + sign.I understand that there is a problem with my regular expression.I have tried everything like \+ but i still don't get the right results.Any help?
When you run URLDecoder.decode(line, "utf-8") the + is removed from your string.
I am trying to open a csv file using openCSV, iterate over every column and if the userID is different write a new JavaBean pair at the end of the file.
The problem is that the reader only checks the first column of my file and not the whole file. While created, the file contains only a header and nothing else. The program will check every column and if the sudoID is different it will write it to the file. If the sudoID in the first line is equal to the the one imported from my main class it will recognise it and not write it. But if this -same- sudoID is in the second row it will not recognise it and will write it again.
For instance, if my CSV looks like this it will work:
"Patient_id Pseudo_ID",
"32415","PAT106663926"
If it looks like this it will re-write the sudoID:
"Patient_id Pseudo_ID",
"32416","PAT104958880"
"32415","PAT106663926"
Thanks!
My Code:
public class CSVConnection {
#SuppressWarnings({ "deprecation", "resource", "rawtypes", "unchecked" })
public String getID(String sID,String pseudoID) throws IOException, CsvDataTypeMismatchException, CsvRequiredFieldEmptyException{
try {
CsvToBean csv = new CsvToBean();
String csvFilename = "CsvFile.csv";
Writer writer= new FileWriter(csvFilename,true);
CSVReader csvReader = new CSVReader(new FileReader(csvFilename),',','"',1);
ColumnPositionMappingStrategy strategy = new ColumnPositionMappingStrategy();
strategy.setType(PatientCSV.class);
String[] columns = new String[] {"patID","pseudoID"};
strategy.setColumnMapping(columns);
//Set column mapping strategy
StatefulBeanToCsv<PatientCSV> bc = new StatefulBeanToCsvBuilder<PatientCSV>(writer).withMappingStrategy(strategy).build();
List patList = csv.parse(strategy, csvReader);
for (Object patObj : patList) {
PatientCSV pat = (PatientCSV) patObj;
if(((PatientCSV) patObj).getPatID().equals(sID)){
return pat.getPseudoID();
}
else
{
PatientCSV pat1 = new PatientCSV();
pat1.setPatID(sID);
pat1.setPseudoID(pseudoID);
patList.add(pat1);
/*Find a way to import it to the CSV*/
bc.write(pat1);
writer.close();
return pseudoID;
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void main(String [] args) throws IOException, CsvDataTypeMismatchException, CsvRequiredFieldEmptyException{
CSVConnection obj = new CSVConnection();
String sID="32415";
String pseudoID="PAT101830150";
obj.getID(sID,pseudoID);
}
}
and the Java Bean :
public class PatientCSV {
private String patID;
private String pseudoID;
public String getPatID() {
return patID;
}
public void setPatID(String patID) {
this.patID = patID;
}
public String getPseudoID() {
return pseudoID;
}
public void setPseudoID(String pseudoID) {
this.pseudoID = pseudoID;
}
public PatientCSV(String patID, String pseudoID) {
super();
this.patID = patID;
this.pseudoID = pseudoID;
}
public PatientCSV() {
super();
// TODO Auto-generated constructor stub
}
public String toString()
{
return "Patient [id=" + patID + ", pseudoID=" + pseudoID + "]";
}
}
Lets inspect your for loop
for (Object patObj : patList) {
PatientCSV pat = (PatientCSV) patObj;
if(((PatientCSV) patObj).getPatID().equals(sID)){
return pat.getPseudoID();
}
else
{
PatientCSV pat1 = new PatientCSV();
pat1.setPatID(sID);
pat1.setPseudoID(pseudoID);
patList.add(pat1);
/*Find a way to import it to the CSV*/
bc.write(pat1);
writer.close();
return pseudoID;
}
}
So in the case you mention it is not working as expected, meaning that the line that matches your input is the second line:
"Patient_id Pseudo_ID",
"32416","PAT104958880"
"32415","PAT106663926"
So you call: getID("32415", "PAT106663926")
What happens in your loop is:
You take the first element of your csv patients, the one with id: 32416,
check if it matches with the id given as input to your method, 32415.
It does not match so it goes to the else part. There it creates the new patient (with the same patID and pseudoID as the 2nd row of your csv) and stores it in the file.
So by now you should have 2 entries in your csv with the same data "32415","PAT106663926".
I think that this is the error, in your for loop you should check against all entries if there is a match, and then create the patient and store it to the csv.
An example:
PatientCSV foundPatient = null;
for (Object patObj : patList) {
PatientCSV pat = (PatientCSV) patObj;
if(((PatientCSV) patObj).getPatID().equals(sID)){
foundPatient = pat;
}
}
if (foundPatient == null) {
foundPatient = new PatientCSV();
foundPatient.setPatID(sID);
foundPatient.setPseudoID(pseudoID);
patList.add(foundPatient);
/*Find a way to import it to the CSV*/
bc.write(foundPatient);
writer.close();
}
return foundPatient.getPseudoID();
P.S. The above example is written very quickly, just to give you the idea what needs to be done.
i trie to search in google with JSoup. The problem that i have is, that the variable query shows not the URL i want when i start searching.
Also, how does Jsoup search ? Looking for Title or URL or what ?
public class Start {
public static void main(String[] args) {
try {
new Google().Searching("Möbel Beck GmbH & Co.KG");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
public class Google implements Serializable {
private static final long serialVersionUID = 1L;
private static Pattern patternDomainName;
private Matcher matcher;
private static final String DOMAIN_NAME_PATTERN = "([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,6}";
static {
patternDomainName = Pattern.compile(DOMAIN_NAME_PATTERN);
}
public void Searching(String searchstring) throws IOException {
Google obj = new Google();
Set<String> result = obj.getDataFromGoogle(searchstring);
for (String temp : result) {
if (temp.contains(searchstring)) {
System.out.println(temp + " ----> CONTAINS");
} else {
System.out.println(temp);
}
}
System.out.println(result.size());
}
public String getDomainName(String url) {
String domainName = "";
matcher = patternDomainName.matcher(url);
if (matcher.find()) {
domainName = matcher.group(0).toLowerCase().trim();
}
return domainName;
}
private Set<String> getDataFromGoogle(String query) {
Set<String> result = new HashSet<String>();
String request = "https://www.google.com/search?q=" + query;
System.out.println("Sending request..." + request);
try {
// need http protocol, set this as a Google bot agent :)
Document doc = Jsoup.connect(request)
.userAgent("Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)").timeout(6000)
.get();
// get all links
Elements links = doc.select("a[href]");
for (Element link : links) {
String temp = link.attr("href");
if (temp.startsWith("/url?q=")) {
// use regex to get domain name
result.add(getDomainName(temp));
}
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
Parsing google sites directly is not a good idea. You can try Google API
https://developers.google.com/web-search/docs/#java-access
I have a list of String which I wish to convert to Json. I am using org\json\me in order to do so. However, I don't know how to continue from here. A little help will be appreciated. Thanks.
This is my code:
public class PhoneData implements JSONAble {
private Display display;
private Form mainScr;
public PhoneData() {
mainScr = new Form("Phone Data");
String imei = IDENInfo.imeiToString(IDENInfo.getIMEI());
String imsi = new String();
try{
imsi=GPRSInfo.imeiToString(SIMCardInfo.getIMSI(), false );
}catch(SIMCardException ioe){}
String majorOS = DeviceInfo.getPlatformVersion();
int content = CodeModuleManager.getModuleHandle("net_rim_bb_phone_api");
String version = CodeModuleManager.getModuleVersion(content); //DeviceInfo.getSoftwareVersion();
String modelnumber = DeviceInfo.getDeviceName(); //get modelnumber
String [] phoneData = new String[] { modelnumber = "Model Number", majorOS = "majorOS", version = "softwareversion"
,imei = "imei", imsi = "imsi"}; // an Array
}
protected void startApp() throws MIDletStateChangeException {
// TODO Auto-generated method stub
display.setCurrent(mainScr);
PhoneData user = new PhoneData();
}
public void fromJSON(String jsonString) {
// TODO Auto-generated method stub
}
public String toJSON() {
// TODO Auto-generated method stub
return null;
}
}
You'll have to put your data inside a Vector, then use the new JSONArray(yourvector) to make a JSONArray.
Unless you specifically want to use org.json's barebones package, maybe have a look at this question.
You could use the Jettison driver with XStream to serialize / deserialize string <-> json :
http://x-stream.github.io/json-tutorial.html
I had used this sometime back - there are some caveats on how the json schema should be for the parser to parse perfectly well.