Copy a file's contents while ignoring characters between < and > in Java - strip-tags

I'm looking to write a program that reads from a html file and copies the contents but it ignores the html tags without using replaceAll. Also the stripping of html tags must be done in a different method. The file looks like this :
<html>
<head>
<title>My web page</title>
</head>
<body>
<p>There are many pictures of my cat here,
as well as my <b>very cool</b> blog page,
which contains <font color="red">awesome
stuff about my trip to Vegas.</p>
Here's my cat now:<img src="cat.jpg">
</body>
</html>
And I'd like my program to display the following:
My web page
There are many pictures of my cat here,
as well as my very cool blog page,
which contains awesome
stuff about my trip to Vegas.
Here's my cat now:

public static void main(String[] args) {
String html = " <html>\n"
+ " <head>\n"
+ " <title>My web page</title>\n"
+ " </head>\n"
+ " <body>\n"
+ " <p>There are many pictures of my cat here,\n"
+ " as well as my <b>very cool</b> blog page,\n"
+ " which contains <font color=\"red\">awesome\n"
+ " stuff about my trip to Vegas.</p>\n"
+ "\n"
+ "\n"
+ " Here's my cat now:<img src=\"cat.jpg\">\n"
+ " </body>\n"
+ " </html>";
boolean inTag = false;
StringBuilder finalString = new StringBuilder();
int length = html.length();
for (int i = 0; i < length; i++) {
char c = html.charAt(i);
if ('<' == c) {
inTag = true;
} else if ('>' == c) {
inTag = false;
} else if (!inTag) {
finalString.append(c);
}
}
System.out.print(finalString);
}

Related

Spring boot - I want to write a POST endpoint to consume multipart/form-data WITHOUT any file uplload, I need to post json data as key-value pair pair

I want to do something like this -
#ApiOperation("Solve for tasks in JSON file")
#PostMapping(value = "/tasks/file",
consumes = {MediaType.MULTIPART_FORM_DATA_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<Plan> solveTest(#RequestBody(value = "file") InputStream filrInputStream) {}
I tried adding jersey multipart dependency in my spring boot app and tried my api method signature as below, but when I try posting my json string I get input stream as empty-
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-multipart</artifactId>
</dependency>
#ApiImplicitParams({
#ApiImplicitParam(
name = "file",
dataType = "java.io.InputStream",
examples = #io.swagger.annotations.Example(
value = {
#ExampleProperty(value = "[\r\n"
+ " {\r\n"
+ " \"duration\": 0,\r\n"
+ " \"xxxxxxTG\": \"string\",\r\n"
+ " \"sequence\": 0,\r\n"
+ " \"xxxxxx\": \"string\",\r\n"
+ " \"taskId\": \"string\",\r\n"
+ " \"taskType\": \"string\",\r\n"
+ " \"xcoordinate\": 0,\r\n"
+ " \"ycoordinate\": 0\r\n"
+ " }\r\n"
+ "]", mediaType = "multipart/form-data")
}))
})
#PostMapping(value = "/tasks/file",
consumes = {MediaType.MULTIPART_FORM_DATA_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE}
)
public ResponseEntity<Plan> solveTest1(#FormDataParam("file") InputStream file, #FormDataParam("file") FormDataContentDisposition fileMetaData)

Possible to download JPA repository in Vaadin as CSV file?

Assume that we have defined a entity and it's connected to a database. Now we can access the database by using a repository.
#Autowired
private DataLoggRepository dataLoggRepository;
If I want to get all the rows from the database and download it. Then I can write this code:
List<DataLogg> dataLoggers = dataLoggRepository.findAll();
Now, how can I donwload the object dataLoggers as a CSV file in Vaadin in a proper way?
Here you can see how to create a link to download a file:
Anchor csvLink = new Anchor(new StreamResource("file.csv",
() -> {
String csvString = ...// create the csv
return new ByteArrayInputStream(csvString.getBytes());
}), "Download CSV");
csvLink.getElement().setAttribute("download", true);
To create the CSV you have various options like OpenCSV or directly create the CSV from the SQL query.
Here is a working example
// Download all data
Anchor download = new Anchor(); // Add this to the layout
loggerId.addValueChangeListener(e-> {
String fileName = String.valueOf(loggerId.getValue()) + ".csv";
List<DataLogg> selectedLogger = dataLoggRepository.findByLoggerId(loggerId.getValue());
download.setHref(getStreamResource(fileName, selectedLogger));
});
download.getElement().setAttribute("download",true);
download.add(new Button("Download", new Icon(VaadinIcon.DOWNLOAD_ALT)));
Function
public StreamResource getStreamResource(String filename, List<DataLogg> selectedLogger) {
// Create a large CSV file in a form of StringBuilder and then convert it all to bytes
StringWriter stringWriter = new StringWriter();
stringWriter.write("id, dateTime, DO0, DO1, DO2, DO3, AI0, AI1, AI2, AI3, loggerId, samplingTime\n");
for (int i = 0; i < selectedLogger.size(); ++ i) {
DataLogg dataLogg = selectedLogger.get(i);
String row = dataLogg.getId() + "," +
dataLogg.getDateTime() + "," +
dataLogg.getDO0() + "," +
dataLogg.getDO1() + "," +
dataLogg.getDO2() + "," +
dataLogg.getDO3() + "," +
dataLogg.getAI0() + "," +
dataLogg.getAI1() + "," +
dataLogg.getAI2() + "," +
dataLogg.getAI3() + "," +
dataLogg.getLoggerId() + "," +
dataLogg.getSamplingTime() + "\n";
stringWriter.write(row);
}
// Try to download
try {
byte[] buffer = stringWriter.toString().getBytes("UTF-8");
return new StreamResource(filename, () -> new ByteArrayInputStream(buffer));
} catch (UnsupportedEncodingException e) {
byte[] buffer = new byte[] {0};
return new StreamResource(filename, () -> new ByteArrayInputStream(buffer));
}
}

java.io.File's .createNewFile() doesn't create a file

class FileClassOne {
public static void main(String args[]) {
File myDir = new File(File.separator);
System.out.println("myDir.getAbsolutePath() = " + myDir.getAbsolutePath());
System.out.println("myDir.isDirectory() = " + myDir.isDirectory());
System.out.println("myDir.isFile() = " + myDir.isFile());
System.out.println();
myDir = new File(File.separator+"Java"+File.separator+"FilePartOne");
System.out.println("myDir.getAbsolutePath() = " + myDir.getAbsolutePath());
System.out.println("myDir.isDirectory() = " + myDir.isDirectory());
System.out.println("myDir.isFile() = " + myDir.isFile());
System.out.println();
File myFile = new File(myDir, "Temp.txt");
System.out.println("myFile.getAbsolutePath() = " + myFile.getAbsolutePath());
System.out.println("myFile.isDirectory() = " + myFile.isDirectory());
System.out.println("myFile.isFile() = " + myFile.isFile());
System.out.println("myFile.exists() = " + myFile.exists());
try {
myFile.createNewFile();
} catch (IOException e) {
System.out.println(e.getMessage());
}
Output:
myDir.getAbsolutePath() = C:\
myDir.isDirectory() = true
myDir.isFile() = false
myDir.getAbsolutePath() = C:\Java\FilePartOne
myDir.isDirectory() = false
myDir.isFile() = false
myFile.getAbsolutePath() = C:\Java\FilePartOne\Temp.txt
myFile.isDirectory() = false
myFile.isFile() = false
myFile.exists() = false
The system cannot find the path specified
This code if from an online tutorial that works in the video and it's copied verbatim. IDE is eclipse.
I would say its likely because of missing directories along the path "C:\Java\FilePartOne".
The statement:
myFile.createNewFile();
Will attempt to create a file on a given path, not create any missing directories. You therefore get the error "The system cannot find the path specified" if any directories are missing when executing the statement.
A quick way to fix this would be to either create the missing folders yourself or add the code below just before myFile.createNewFile();.
myFile.getParentFile().mkdirs();

InvalidSelectorException - Xpath shielding

The variable may come across characters that are used in Xpath, respectively, there is a syntax error, how can you win ?
Example variable (this is just an example, the characters in it can be different):
string textElementa = "it ' is"
Search element by Xpath:
IWebElement elem = diver.FindElement(By.XPath("//div[normalize-space()='" + textElementa + "']"));
The Html code to:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div>
<span>it</span> <span>'</span> <span>is</span>
</div>
</body>
</html>
I've tried all this, but it doesn't work for me.
https://stackoverflow.com/questions/35854525
I also tried this:
public static string ToXPath(string value)
{
return "'" + XmlEncode(value) + "'";
}
public static string XmlEncode(string value)
{
StringBuilder text = new StringBuilder(value);
text.Replace("&", "&");
text.Replace("'", "&apos;");
text.Replace(#"""", """);
text.Replace("<", "<");
text.Replace(">", ">");
return text.ToString();
}

How to print output on new line?

case Constants.QUEUEESCALATION:
{
var body = '';
angular.forEach(caseChangeRecord, function(change, key) {
body += change.fieldName + Constants.QUEUEESCALATION_MSG + checkIfDate(change.originalValue) + Constants.TO + checkIfDate(change.newValue) + Constants.FULLSTOP + '\n';
});
return {
objectType: Constants.TYPE_INFO,
objectIcon: 'fa-list-ul',
objectBody: body
};
}
After appending \n in last it will shown output on same line instated of new line.
ACTUAL OUTPUT:
assignedQueue has been changed from Q1 to Q48. assignedQueueDate has been changed from 06/27/2017 to 07/03/2017.
REQUIRE OUTPUT:
assignedQueue has been changed from Q1 to Q48.
assignedQueueDate has been changed from 06/27/2017 to 07/03/2017.
Add a space before \n. It's working from my side.
body += change.fieldName + Constants.QUEUEESCALATION_MSG + checkIfDate
(change.originalValue) + Constants.TO + checkIfDate(change.newValue) +
Constants.FULLSTOP + ' \n';
Update :
and your html should be like using innerHtml
<div class="timeline-body" [innerHTML]="item.body"></div>
Divide rows by '\n' token and wrap your item.body into <pre>:
<div class="timeline-body">
<pre>
{{item.body}}
</pre>
</div>

Resources