Groovy render chunk file - file

I am using StreamingMarkupBuilder for generate very big xml file. File is so big, that i have set
JAVA_OPT="-XX:NewSize=2048m -XX:MaxNewSize=4096m -XX:SurvivorRatio=8 -Xms4096m -Xmx4096m -XX:MaxPermSize=4096m"
(2048m, 1024m not enough)
Without chunk i got file so far, response answer:
*0:0:0:0:0:0:0:1 - - [03/Jan/2018:17:15:37 +0200] "GET ... HTTP/1.1" 200 167467288*
Service:
def builder = new StreamingMarkupBuilder()
def Header = {
mkp.xmlDeclaration()
mkp.declareNamespace('': 'http://...')
...
...
Header{
SourceDocuments {
SalesInvoices {
// !!!big scope of data came in this loop!!!
for (row in data) {
Invoice {
...
...
}
}
}
}
}
XmlUtil.serialize(builder.bind(Header))
NOTE: Only builder.bind(Header) as last result line create file very slowly.
Controller:
response.contentType = grailsApplication.config.grails.mime.types[exportFormat]
response.setHeader("Content-disposition", "attachment; filename=" + reportName + "." + exportFormat)
response.outputStream << result
I am looking for chunk solution for response file and minimize JAVA_OPT environments heaps sizes. Actually to get a solution with DOM would be perfect because of performance, and I would like appreciate that, but will be nice if solution of chunk exists on different way that have groovy.

this answer is not about chunking but about performance
here are 4 examples of rendering xml with time result comparison
note that minimal memory consumption will be with StreamingMarkupBuilder because it renders xml directly to output (file) without building it in memory
in other cases we are building xml in memory and then rendering to output
the fastest one will be with CompileStatic annotation for the main loop
START: StreamingMarkupBuilder
END: 23946 sec
START: DOMBuilder
END: 8282 sec
START: NodeBuilder
END: 8778 sec
START: NodeBuilder+CompileStatic
END: 2978 sec
code:
import groovy.util.Node
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
class Const{
static long MAX_ITEMS=999999
}
//=============StreamingMarkupBuilder==========================
long t=System.currentTimeMillis()
println "START: StreamingMarkupBuilder"
def xdata = new groovy.xml.StreamingMarkupBuilder().bind{
root {
for(int i=0;i<Const.MAX_ITEMS;i++){
a('id':i,'123_'+i)
}
}
}
new File('c:/11/111.xml').withOutputStream{stream->
stream.withWriter("UTF-8"){ w-> xdata.writeTo( w ) }
}
println " END: ${System.currentTimeMillis()-t} sec"
xdata=null
System.gc()
Thread.sleep(5000)
//=============DOMBuilder======================================
t=System.currentTimeMillis()
println "START: DOMBuilder"
DocumentBuilderFactory domFactory=DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder domBuilder = domFactory.newDocumentBuilder();
xdata = new groovy.xml.DOMBuilder(domBuilder).
root{
for(int i=0;i<Const.MAX_ITEMS;i++){
a('id':i,'123_'+i)
}
}
new File('c:/11/112.xml').withOutputStream{stream->
groovy.xml.XmlUtil.serialize(xdata, stream)
}
println " END: ${System.currentTimeMillis()-t} sec"
xdata=null
System.gc()
Thread.sleep(5000)
//=============NodeBuilder=====================================
t=System.currentTimeMillis()
println "START: NodeBuilder"
xdata = new NodeBuilder().
root{
for(int i=0;i<Const.MAX_ITEMS;i++){
a('id':i,'123_'+i)
}
}
new File('c:/11/113.xml').withOutputStream{stream->
groovy.xml.XmlUtil.serialize(xdata, stream)
}
println " END: ${System.currentTimeMillis()-t} sec"
xdata=null
System.gc()
Thread.sleep(5000)
//=============NodeBuilder+CompileStatic=======================
t=System.currentTimeMillis()
println "START: NodeBuilder+CompileStatic"
#groovy.transform.CompileStatic
def longLoopData(Node parent){
for(int i=0;i<Const.MAX_ITEMS;i++){
parent.appendNode('a', ['id':i], '123_'+i)
}
}
xdata = new NodeBuilder().
root{
longLoopData(current)
}
new File('c:/11/114.xml').withOutputStream{stream->
groovy.xml.XmlUtil.serialize(xdata, stream)
}
println " END: ${System.currentTimeMillis()-t} sec"
xdata=null
System.gc()
Thread.sleep(5000)

Related

How to run multiple instances(datasets) from same CPLEX model?

I have a MIP model in CPLEX as a mod file. I have datasets in multiple '.txt' files. Is there a way to automate the process in CPLEX to solve the model for many instances. Currently, I run the model every single time for every instance. I have my instances as "M1_D1.txt", "M2_D1.txt",...."M100_D10.txt". However, the model to solve is the same.
In Matlab, it is easier to automate the process. But I could not find anywhere how to automate in CPLEX.
define variables
retrieve data from .dat file
define objective function
define constraints
you could use a main block (flow control)
Here is an example:
sub.mod
float maxOfx = ...;
dvar float x;
maximize x;
subject to {
x<=maxOfx;
}
execute
{
writeln("x= ",x);
}
try1.dat
maxOfx=1;
try2.dat
maxOfx=2;
and then
main.mod
{string} datFiles=...;
main {
var source = new IloOplModelSource("sub.mod");
var cplex = new IloCplex();
var def = new IloOplModelDefinition(source);
for(var datFile in thisOplModel.datFiles)
{
var opl = new IloOplModel(def,cplex);
var data2= new IloOplDataSource(datFile);
opl.addDataSource(data2);
opl.generate();
if (cplex.solve()) {
opl.postProcess();
var o=new IloOplOutputFile("res"+datFile+".txt");
o.writeln("OBJ = " + cplex.getObjValue());
o.close();
writeln("OBJ = " + cplex.getObjValue());
} else {
writeln("No solution");
}
opl.end();
}
}
main.dat
datFiles={"Try1.dat","try2.dat"};
In command line oplrun main.mod main.dat
In the IDE, you need to have main.mod and main.dat in a run configuration

How to read plain text file in kotlin?

There may be various way to read plain text file in kotlin.
I want know what are the possible ways and how I can use them.
1. Using BufferedReader
import java.io.File
import java.io.BufferedReader
fun main(args: Array<String>) {
val bufferedReader: BufferedReader = File("example.txt").bufferedReader()
val inputString = bufferedReader.use { it.readText() }
println(inputString)
}
2. Using InputStream
Read By Line
import java.io.File
import java.io.InputStream
fun main(args: Array<String>) {
val inputStream: InputStream = File("example.txt").inputStream()
val lineList = mutableListOf<String>()
inputStream.bufferedReader().forEachLine { lineList.add(it) }
lineList.forEach{println("> " + it)}
}
Read All Lines
import java.io.File
import java.io.InputStream
fun main(args: Array<String>) {
val inputStream: InputStream = File("example.txt").inputStream()
val inputString = inputStream.bufferedReader().use { it.readText() }
println(inputString)
}
3. Use File directly
import java.io.File
import java.io.BufferedReader
fun main(args: Array<String>) {
val lineList = mutableListOf<String>()
File("example.txt").useLines { lines -> lines.forEach { lineList.add(it) }}
lineList.forEach { println("> " + it) }
}
I think the simplest way to code is using kotlin.text and java.io.File
import java.io.File
fun main(args: Array<String>) {
val text = File("sample.txt").readText()
println(text)
}
The answers above here are all based on Kotlin Java. Here is a Kotlin Native way to read text files:
val bufferLength = 64 * 1024
val buffer = allocArray<ByteVar>(bufferLength)
for (i in 1..count) {
val nextLine = fgets(buffer, bufferLength, file)?.toKString()
if (nextLine == null || nextLine.isEmpty()) break
val records = parseLine(nextLine, ',')
val key = records[column]
val current = keyValue[key] ?: 0
keyValue[key] = current + 1
}
fun parseLine(line: String, separator: Char) : List<String> {
val result = mutableListOf<String>()
val builder = StringBuilder()
var quotes = 0
for (ch in line) {
when {
ch == '\"' -> {
quotes++
builder.append(ch)
}
(ch == '\n') || (ch == '\r') -> {}
(ch == separator) && (quotes % 2 == 0) -> {
result.add(builder.toString())
builder.setLength(0)
}
else -> builder.append(ch)
}
}
return result
}
See: https://github.com/JetBrains/kotlin-native/blob/master/samples/csvparser/src/csvParserMain/kotlin/CsvParser.kt
Anisuzzaman's answer lists several possibilities.
The main differences between them are in whether the file is read into memory as a single String, read into memory and split into lines, or read line-by-line.
Obviously, reading the entire file into memory in one go can take a lot more memory, so that's something to avoid unless it's really necessary.  (Text files can get arbitrarily big!)  So processing line-by-line with BufferedReader.useLines() is often a good approach.
The remaining differences are mostly historical.  Very early versions of Java used InputStream &c which didn't properly distinguish between characters and bytes; Reader &c were added to correct that.  Java 8 added ways to read line-by-line more efficiently using streams (e.g. Files.lines()).  And more recently, Kotlin has added its own extension functions (e.g. BufferedReader.useLines()) which make it even simpler.
To read a text file, it must first be created. In Android Studio, you would create the text file like this:
1) Select "Project" from the top of the vertical toolbar to open the project "tool window"
2) From the drop-down menu at the top of the "tool window", select "Android"
3) Right-click on "App" and select "New"
then -> "Folder" (the one with the green Android icon beside it)
then -> "Assets Folder"
4) Right-click on the "assets" folder after it appears in the "tool window"
5) Select "New" -> "File"
6) Name the file, and included the extension ".txt" if it is text file, or ".html" if it is for WebView
7) Edit the file or cut and paste text into it. The file will now display under the "Project" files in the "tool window" and you will be able to double-click it to edit it at any time.
TO ACCESS THIS FILE, use a prefix of "application.assets." followed by someFunction(fileName). For example (in Kotlin):
val fileName = "townNames.txt"
val inputString = application.assets.open(fileName).bufferedReader().use { it.readText() }
val townList: List<String> = inputString.split("\n")
how to apply Documents path on that:
fun main(args: Array<String>) {
val inputStream: InputStream = File("example.txt").inputStream()
val inputString = inputStream.bufferedReader().use { it.readText() }
println(inputString)
}

Java File mkdirs() returns true but does not create folder under load

I am facing issue with File.mkdirs(). I am creating few hundred folders in parallel, but seems like few times, this mkdir() api returns true but folder wasn't really created(java 1.8). I have pasted my sample code below, any ideas?
My Sample code and output is here: https://pastebin.com/aYWDw6JZ
It creates folders most of the time but fails sometimes.
public void run() {
// TODO Auto-generated method stub
long randData = (long) (System.currentTimeMillis() + (Math.random() * 100000));
String folderPath = File.separatorChar + "data" + File.separatorChar + "ext" + File.separatorChar + randData;
File testFolder = new File(folderPath);
if (!testFolder.exists()) {
if(testFolder.mkdirs() == false)
System.out.println(System.currentTimeMillis() + ": folder creation failed!");
}
String filename = testFolder + File.separator + "test.txt";
File testFile = new File(filename);
FileOutputStream fileOutputStream = null;
boolean bCreated = false;
try {
//Thread.sleep(1000);
if(testFolder.exists() == false) {
System.out.println("Folder not created!");
System.out.println("Folder: " + testFolder.getAbsolutePath() + " does not exist!");
}else
bCreated = true;
fileOutputStream = new FileOutputStream(testFile);
fileOutputStream.close();
testFile.delete();
testFolder.delete();
//System.out.println("success:" + testFile.getAbsolutePath());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Folder created? " + testFolder + ": " + bCreated);
//back off and see if the folder is really created
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("Checking again, " + testFolder.getAbsolutePath() + " created? " + testFolder.exists());
}
}
Output:
java.io.FileNotFoundException: \data\ext\1521045935714\test.txt (The system cannot find the path specified)
at java.io.FileOutputStream.open0(Native Method)
at java.io.FileOutputStream.open(FileOutputStream.java:270)
at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
at java.io.FileOutputStream.<init>(FileOutputStream.java:162)
at DiskFolderCreationThread.run(DiskFolderCreationThread.java:30)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Folder created? \data\ext\1521045935714: true
Checking again, C:\data\ext\1521045935714 created? false
Just want to update my finding as a solution. I found out that in my application, multiple threads are trying to create folder and if two threads are simultaneously trying to create folder with the same name, I see this mkdirs() behavior, otherwise its fine. I eliminated this condition and make sure the folder names are unique across threads and no issues now.

How to read and add only numbers to array from a text file

I'm learning java and I have a question regarding reading from file
i want to read only numbers from file that contains strings as well.
here is an example of my file:
66.56
"3
JAVA
3-43
5-42
2.1
1
and here is my coding:
public class test {
public static void main (String [] args){
if (0 < args.length) {
File x = new File(args[0]);
try{
Scanner in = new Scanner( new FileInputStream(x));
ArrayList<Double> test = new ArrayList<>();
while(in.hasNext()){
if(in.hasNextDouble()){
Double f=in.nextDouble();
test.add(f);}
else
{in.next();}
}
catch(IOException e) { System.err.println("Exception during reading: " + e); }
}
my problem is it only add 66.56,2.1 and 1
it doesn't add 3 after "3 or it ignores 3-43 and 5-42
can you tell me how to skip Strings and only add doubles here?
thanks
All the said three ie; "3, 3-43 and 4-42 are strings
Either u read a string and split it and check for number at " and - or you put in a space between characters and integers.
The JVM after compilation would treat it all as string if it cannot be converted to a double.
And the File reader wont stop reading till at least a space or a newline.
Hence your code would never work the way you intend it to unless you do as I said above.
Solution 1:
Change your input file to something like this:
66.56
" 3
JAVA
3 - 43
5 - 42
2.1
1
Solution 2:
Considering the highly variable nature of your input file I am posting a solution only made for your current input. If the input changes a more versatile algorithm would need to be implemented.
public static void main(String[] args) {
File x = new File(args[0]);
try {
Scanner in = new Scanner(new FileInputStream(x));
ArrayList<Double> test = new ArrayList<>();
while (in.hasNext()) {
if (in.hasNextDouble()) {
Double f = in.nextDouble();
test.add(f);
} else {
String s=in.next();
if(s.contains("\"")){
String splits[]=s.split("\"");
test.add(Double.parseDouble(splits[1]));
}
else if (s.contains("-")){
String splits[]=s.split("-");
test.add(Double.parseDouble(splits[0]));
test.add(Double.parseDouble(splits[1]));
}
}
}
System.out.println(test);
} catch (IOException e) {
System.err.println("Exception during reading: " + e);
}
}
You can write custom Type Sensor Utility class to check whether the object can be converted to Integer or not. I would approach to this problem like this.
Moreover I can see that you have values like 2.1 and " 3 to handle these scenarios write additional methods like isDoubleType() or isLongType() etc.
Also you need to write some custom logic to solve this problem.
public class TypeSensor {
public String inferType(String value) throws NullValueException {
int formatIndex = -1;
if (null == value) {
throw new NullValueException("Value provided for type inference was null");
}else if (this.isIntegerType(value)) {
return "Integer";
}else{
LOGGER.info("Value " + value + " doesnt fit to any predefined types. Defaulting to String.");
return "String";
}
}
}
private boolean isIntegerType(String value) {
boolean isParseable = false;
try {
Integer.parseInt(value);
LOGGER.info("Parsing successful for " + value + " to Integer.");
isParseable = true;
} catch (NumberFormatException e) {
LOGGER.error("Value " + value + " doesn't seem to be of type Integer. This is not fatal. Exception message is->"
+ e.getMessage());
}
return isParseable;
}
}

Not writing to the file Scala

I have the following code, which is supposed to write to a file one line at a time, until it reaches ^EOF.
import java.io.PrintWriter
import java.io.File
object WF {
def writeline(file: String)(delim: String): Unit = {
val writer = new PrintWriter(new File(file))
val line = Console.readLine(delim)
if (line != "^EOF") {
writer.write(line + "\n")
writer.flush()
}
else {
sys.exit()
}
}
}
var counter = 0
val filename = Console.readLine("Enter a file: ")
while (true) {
counter += 1
WF.writeline(filename)(counter.toString + ": ")
}
For some reason, at the console, everything looks like it works fine, but then, when I actually read the file, nothing has been written to it! What is wrong with my program?
Every time you create a new PrintWriter you're wiping out the existing file. Use something like a FileWriter, which allows you to specify that you want to open the file for appending:
val writer = new PrintWriter(new FileWriter(new File(file), true))
That should work, although the logic here is pretty confusing.
Use val writer = new FileWriter(new File(file), true) instead. The second parameter tells the FileWriter to append to the file. See http://docs.oracle.com/javase/6/docs/api/java/io/FileWriter.html
I'm guessing the problem is that you forgot to close the writer.

Resources