Writing and reading inherited objects from a file with bufferred reader - java

I am writing a librarian admin program and I have two classes: members and premium members. there is no real difference other than the fact that premium members can take out 5 books as opposed to only 3. I am using a buffered reader and writer to read these items but I am wonderring how (or If I can at all) read and write both objects to a single .txt file?
here's my code I have so far:
Member class
public String toString(int i) {
String stg = "";
stg += memID + "#" + name + "#" + surname + "#" + address + "#" + email + "#" + cellnum + "#" + num + "#" + accntTyp + "#" + pass + "#" + book1 + "#" + book2 + "#" + book3 + "#";
return stg;
}
I have yet to do premium members class (wanted to get an answer while i do it) but it would pretty much look the same with an exception of 2 extra books.

Related

TranslatableText inside a LiteralText SendMessage

I want to program an item that posts the coordinates of certain ores in the chat.
But now my question is whether I can also put parts of the chat message as a translation or only hardcoded, so that it only outputs what I programmed.
I work with Minecraft fabric for 1.18.2 and the code below is what i have:
private void outputValuableCoordinates(BlockPos blockPos, PlayerEntity player, Block blockBelow) {
player.sendMessage(new LiteralText("Found "
+ blockBelow.asItem().getName().getString()
+ " at " +
"(" + blockPos.getX() + ", " + blockPos.getY() + "," + blockPos.getZ() + ")"), false);
}
And i would make a TranslatableText out of "Found" and "at"

Parse html content for a value

I receive a Http response after a call as Html String and I would like to scrape certain value stored inside the ReportViewer1 variable.
<html>
....................
...........
<script type="text/javascript">
var ReportViewer1 = new ReportViewer('ReportViewer1', 'ReportViewer1_ReportToolbar', 'ReportViewer1_ReportArea_WaitControl', 'ReportViewer1_ReportArea_ReportCell', 'ReportViewer1_ReportArea_PreviewFrame', 'ReportViewer1_ParametersAreaCell', 'ReportViewer1_ReportArea_ErrorControl', 'ReportViewer1_ReportArea_ErrorLabel', 'ReportViewer1_CP', '/app/Telerik.ReportViewer.axd', 'a90a0d41efa6429eadfefa42fc529de1', 'Percent', '100', '', 'ReportViewer1_EditorPlaceholder', 'ReportViewer1_CalendarFrame', 'ReportViewer1_ReportArea_DocumentMapCell', {
CurrentPageToolTip: 'STR_TELERIK_MSG_CUR_PAGE_TOOL_TIP',
ExportButtonText: 'Export',
ExportToolTip: 'Export',
ExportSelectFormatText: 'Export to the selected format',
FirstPageToolTip: 'First page',
LabelOf: 'of',
LastPageToolTip: 'Last Page',
ProcessingReportMessage: 'Generating report...',
NoPageToDisplay: 'No page to display.',
NextPageToolTip: 'Next page',
ParametersToolTip: 'Click to close parameters area|Click to open parameters area',
DocumentMapToolTip: 'Hide document map|Show document map',
PreviousPageToolTip: 'Previous page',
TogglePageLayoutToolTip: 'Switch to interactive view|Switch to print preview',
SessionHasExpiredError: 'Session has expired.',
SessionHasExpiredMessage: 'Please, refresh the page.',
PrintToolTip: 'Print',
RefreshToolTip: 'Refresh',
NavigateBackToolTip: 'Navigate back',
NavigateForwardToolTip: 'Navigate forward',
ReportParametersSelectAllText: '<select all>',
ReportParametersSelectAValueText: '<select a value>',
ReportParametersInvalidValueText: 'Invalid value.',
ReportParametersNoValueText: 'Value required.',
ReportParametersNullText: 'NULL',
ReportParametersPreviewButtonText: 'Preview',
ReportParametersFalseValueLabel: 'False',
ReportParametersInputDataError: 'Missing or invalid parameter value. Please input valid data for all parameters.',
ReportParametersTrueValueLabel: 'True',
MissingReportSource: 'The source of the report definition has not been specified.',
ZoomToPageWidth: 'Page Width',
ZoomToWholePage: 'Full Page'
}, 'ReportViewer1_ReportArea_ReportArea', 'ReportViewer1_ReportArea_SplitterCell', 'ReportViewer1_ReportArea_DocumentMapCell', true, true, 'PDF', 'ReportViewer1_RSID', true);
</script>
...................
...................
</html>
The value is a90a0d41efa6429eadfefa42fc529de1 and this is in the middle of this content:
'/app/Telerik.ReportViewer.axd', 'a90a0d41efa6429eadfefa42fc529de1', 'Percent', '100',
Whats the best way I can parse this value using Java?
Parse the HTML with String class
public class HtmlParser {
public static void main(String args[]){
String result = getValuesProp(html);
System.out.println("Result: "+ result);
}
static String PIVOT = "Telerik.ReportViewer.axd";
public static String getValuesProp(String json) {
String subString;
int i = json.indexOf(PIVOT);
i+= PIVOT.length();
//', chars
i+=2;
subString = json.substring(i);
i = subString.indexOf("'");
i++;
subString = subString.substring(i);
i = subString.indexOf("'");
subString = subString.substring(0,i);
return subString;
}
static String html ="<html>\n" +
"\n" +
"<script type=\"text/javascript\">\n" +
" var ReportViewer1 = new ReportViewer('ReportViewer1', 'ReportViewer1_ReportToolbar', 'ReportViewer1_ReportArea_WaitControl', 'ReportViewer1_ReportArea_ReportCell', 'ReportViewer1_ReportArea_PreviewFrame', 'ReportViewer1_ParametersAreaCell', 'ReportViewer1_ReportArea_ErrorControl', 'ReportViewer1_ReportArea_ErrorLabel', 'ReportViewer1_CP', '/app/Telerik.ReportViewer.axd', 'a90a0d41efa6429eadfefa42fc529de1', 'Percent', '100', '', 'ReportViewer1_EditorPlaceholder', 'ReportViewer1_CalendarFrame', 'ReportViewer1_ReportArea_DocumentMapCell', {\n" +
" CurrentPageToolTip: 'STR_TELERIK_MSG_CUR_PAGE_TOOL_TIP',\n" +
" ExportButtonText: 'Export',\n" +
" ExportToolTip: 'Export',\n" +
" ExportSelectFormatText: 'Export to the selected format',\n" +
" FirstPageToolTip: 'First page',\n" +
" LabelOf: 'of',\n" +
" LastPageToolTip: 'Last Page',\n" +
" ProcessingReportMessage: 'Generating report...',\n" +
" NoPageToDisplay: 'No page to display.',\n" +
" NextPageToolTip: 'Next page',\n" +
" ParametersToolTip: 'Click to close parameters area|Click to open parameters area',\n" +
" DocumentMapToolTip: 'Hide document map|Show document map',\n" +
" PreviousPageToolTip: 'Previous page',\n" +
" TogglePageLayoutToolTip: 'Switch to interactive view|Switch to print preview',\n" +
" SessionHasExpiredError: 'Session has expired.',\n" +
" SessionHasExpiredMessage: 'Please, refresh the page.',\n" +
" PrintToolTip: 'Print',\n" +
" RefreshToolTip: 'Refresh',\n" +
" NavigateBackToolTip: 'Navigate back',\n" +
" NavigateForwardToolTip: 'Navigate forward',\n" +
" ReportParametersSelectAllText: '<select all>',\n" +
" ReportParametersSelectAValueText: '<select a value>',\n" +
" ReportParametersInvalidValueText: 'Invalid value.',\n" +
" ReportParametersNoValueText: 'Value required.',\n" +
" ReportParametersNullText: 'NULL',\n" +
" ReportParametersPreviewButtonText: 'Preview',\n" +
" ReportParametersFalseValueLabel: 'False',\n" +
" ReportParametersInputDataError: 'Missing or invalid parameter value. Please input valid data for all parameters.',\n" +
" ReportParametersTrueValueLabel: 'True',\n" +
" MissingReportSource: 'The source of the report definition has not been specified.',\n" +
" ZoomToPageWidth: 'Page Width',\n" +
" ZoomToWholePage: 'Full Page'\n" +
" }, 'ReportViewer1_ReportArea_ReportArea', 'ReportViewer1_ReportArea_SplitterCell', 'ReportViewer1_ReportArea_DocumentMapCell', true, true, 'PDF', 'ReportViewer1_RSID', true);\n" +
" </script>\n" +
"\n" +
"</html>";
}
I would read the text a line at a time like how most files are read. Because the format will always be the same, you look for a line that begins with the characters "var ReportViewer1." Then you know you have found the line you want. You may need to strip some white space, although it will always be formatted with the same whitespace too (up to you really.)
When you have the line, use the String .split() method to split that line into an array. There are nice delimiters there to split on ... "," or " " or ", " ... again, see what works best for you.
Test the split up line parts for '/app/Telerik.ReportViewer.axd' ... the next member of your split array will be the value you are looking for.
Again, the formatting will always be the same, so you can rely on that to find your variable. Of course, study the html text to make sure it does always follow the same format within the line you are investigating, but looking at it, I assume it probably does.
Again, find your line ... split it on a delimiter ... and use some logic to find the element you are after in the split up line parts.

How to grab data from a class without making it static per say [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
So for example I have this class that outputs my detailed flight output that is in the java doc "Flight.java" :
public String toDetailedString() {
String output =
getDeparture() + " - " + getArrival() + "\n" + Airport.getAirportCity(source) + " (" +
source + ") - " + Airport.getAirportCity(destination) + " (" + destination + ")" +
"\n" + plane.getAirline() + " " + number + " * " + plane.getModel();
return output;
}
and I have an Itinerary class "Itinerary.java" and I want to pull the info from Flight.java without making toDetailedString static, is that possible?
For added info, each of the variables you see "source, number, destination" are all private variables in Flight.java which I know are enclosed encapsulation. Any help is greatly valuable.
Example implementation in Itinerary.java
public String toString() {
return "The total cost is" + getTotalCost() + Flight.toDetailedString();
}
UPDATE:
In my Flight constructor I have:
public Flight(Plane plane, String number, double cost, Time departure, int duration, Airport source, Airport destination) {
this.plane = plane;
this.number = number;
this.cost = cost;
this.departure = departure;
this.duration = duration;
this.source = source;
this.destination = destination;
}
In which I created the object "f1" in my ItineraryTest class:
Flight f1 = new Flight(new Plane(Airline.American, "Airbus A321"),
"495",
79,
new Time(7, 10), 100,
Airport.PHX, Airport.LAX);
Thus I linked my object to the toDetailedString() the object "f1" was renamed to "first" in my Itinerary.java and a second object was created called "f2" and moved to "second" (to avoid confusion) :
public String toString() {
return "The total cost: "
+ getTotalCost()
+ " "
+ first.toDetailedString()
+ second.toDetailedString();
}
I thought I answered my own question, but now receive an error of:
Exception in thread "main" java.lang.NullPointerException at
Itinerary.toString(Itinerary.java:117) at
java.lang.String.valueOf(String.java:2994) at
java.io.PrintStream.println(PrintStream.java:821) at
ItineraryTest.main(ItineraryTest.java:20)
Possible, clean option is creating another class named FlightToDetailedString, with (possibly static) method toDetailedString. That method would accept instance of Flight as parameter
class FlightToDetailedString {
public String toDetailedString(Flight flight) {
String output =
getDeparture() + " - " + getArrival() + "\n" + Airport.getAirportCity(source) + " (" +
source + ") - " + Airport.getAirportCity(destination) + " (" + destination + ")" +
"\n" + plane.getAirline() + " " + number + " * " + plane.getModel();
return output;
}
}
In my example method is not static. With non-static member mehod, FlightToDetailedString could have (and use in toDetailedString) fields of FlightToDetailedString class. For example, Airport could be member variable of FlightToDetailedString. Are you sure you want to limit yourself to one airport?
Why you do not like toDetailedString as non-static member of Flight class in first place? In example you give it is most natural solution. if your Itinerary needs to access details of Flight class, just pass instance of Flight object as argument!
The consumer of toDetailedString() doesn't need access to anything inside Flight.
Your NullPointerException is likely caused by one of the fields in the Flight instance being null.
Finally, consider using a StringBuilder instead of concatenating strings.

How to set the multiple attributes of objectClass for UnboundID & OpenLDAP via Java 7

I'm not sure how to properly pass the multiple attributes needed for an OpenLDAP insert via UnboundID. I have omitted the objectClass attributes & received a "no objectClass" error. I have also tried comma-separated & the bracket/array route like below & received the "value #0 invalid per syntax" error.
String[] ldifLines = {"dn: ou=users,dc=sub,dc=domain,dc=com", "cn: " + uid, "userPassword: " + pw, "description: user", "uidNumber: " + lclDT, "gidNumber: 504", "uid: " + uid, "homeDirectory: " + File.separator + "home" + File.separator + this.getStrippedUser(), "objectClass: {posixAccount, top}"};
LDAPResult ldapResult = lclLC.add(new AddRequest(ldifLines));
So, the question is, how do I successfully pass these objectClass attributes in the string array included above? Again, I have tried: "objectClass: top, posixAccount" as well. Thanks in advance!
It uses an LDIF representation, so if an attribute has multiple values, then the attribute appears multiple times. Like:
String[] ldifLines =
{
"dn: ou=users,dc=sub,dc=domain,dc=com",
"objectClass: top",
"objectClass: posixAccount"
"cn: " + uid,
"userPassword: " + pw,
"description: user",
"uidNumber: " + lclDT,
"gidNumber: 504",
"uid: " + uid,
"homeDirectory: " + File.separator + "home" +
File.separator + this.getStrippedUser(),
};
LDAPResult ldapResult = lclLC.add(new AddRequest(ldifLines));
Also, the LDAP SDK allows you to use a shortcut and just do it in a single call without the need to create the array or the AddRequest object, like:
LDAPResult ldapResult = lclLC.add(
"dn: ou=users,dc=sub,dc=domain,dc=com",
"objectClass: top",
"objectClass: posixAccount"
"cn: " + uid,
"userPassword: " + pw,
"description: user",
"uidNumber: " + lclDT,
"gidNumber: 504",
"uid: " + uid,
"homeDirectory: " + File.separator + "home" +
File.separator + this.getStrippedUser());

create tableview using html content in android

I have to develop one android native application using stringbuffer with html content.
Here i have used below code:
PayPalInvoiceItem item1 = new PayPalInvoiceItem();
sb.append("<html><body><table>");
for (int i = 0; i < Constants.mItem_Detail
.size(); i++) {
String title = Constants.mItem_Detail
.get(i).get(
SingleMenuItem.KEY_PNAME);
String qty = Constants.mItem_Detail.get(i)
.get(SingleMenuItem.KEY_QTY);
String cost = Constants.mItem_Detail.get(i)
.get(SingleMenuItem.KEY_PRICE);
String total = Constants.mItem_Detail
.get(i).get(
SingleMenuItem.KEY_TOTAL);
total_count=total_count+Integer.parseInt(qty);
StringBuffer buffer = sb.append("<tr>" + "<td>" + title
+ "</td><td>" + qty + " * " + cost
+ "</td>" + " = <td>" + total
+ " " + "</td></tr>");
item1.setName(buffer.toString());
Now i have to run the application means my output is looking like
<html><body><table>"<tr>" "<td>"krishna
"</td><td>" 1 " * " 100
+ "</td>" = <td>" 100
+ " " + "</td></tr>
But i need the o/p like:
krishna 1 100 100
veni 2 30 60
How can i do????
please help me ???
EDIT:
here i have to change the below line item1.setName(buffer.toString());
to
item.setName(buffer.toString(), "text/html; charset=utf-8"); means am getting following error:
The method setName(String) in the type PayPalInvoiceItem is not applicable for the arguments (String,
String)
How can i resolve these error ????
What is the 'item' you are trying to setName on? by the sounds of things you probably just need to create a WebView like this:
WebView view = new WebView(this);
view.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
view.loadData(stringBuffer.toString(), "text/html", "UTF-8");
setContentView(view);
you also seem to have not terminated the HTML correctly i.e your last write to the StringBuffer should be:
stringBuffer.append("</table></body></html>");
also check your line:
total_count=total_count+Integer.parseInt(qty);
should it not be:
total_count=total_count+Integer.parseInt(total);

Categories

Resources