Modify Filepath from single backslash to double backslash in Groovy - java
I am fairly new to Groovy (Apache) and Java. I am working on a code in Groovy to browse for a .csv file and then utilize it's absolute path for some other function. The problem I am having is the path is given in single \ backslashes but from all the searching I need to get the pathfile into the double \\ backslash form.
I have tried .replace("\\","\\\\") and .replaceAll("\\","\\\\") as well as .split("\\").join("\\\\") as well as trying to search the web for the correct answer.
I am using Groovy and SwingBuilder, so maybe this might affect it. Below is trimmed down code I am using:
import groovy.swing.SwingBuilder
// import groovy.csv.*
import java.awt.BorderLayout as BL
import java.awt.FlowLayout
import java.awt.GridLayout
import javax.swing.SpringLayout
import static java.awt.GridBagConstraints.*
import javax.swing.filechooser.FileFilter
import javax.swing.JFileChooser
import java.awt.*
import javax.swing.*
import javax.swing.border.*
import javax.swing.WindowConstants as WC
import javax.swing.JOptionPane
import javax.swing.JTabbedPane
import javax.swing.JScrollPane
import org.apache.poi.ss.usermodel.*
import org.apache.poi.xssf.usermodel.*
import org.apache.poi.hssf.usermodel.*
import java.nio.file.Path
csvPath = ""
def username = System.getProperty("user.name")
def defaultPath = 'C:\\Users\\' + username + '\\Desktop\\output.xml'
def readCSV(inputFile, outputFile = defaultPath, startRow = 3, objectNameCol = 'A', objectTypeCol = 'B', objectInstanceCol = 'C', objectDescCol = 'D') {
// Some code here
}
def showPreview() {
def preview = swing.frame(title:'CSV Preview', size:[500,300]) {
panel {
borderLayout()
scrollPane( verticalScrollBarPolicy:JScrollPane.VERTICAL_SCROLLBAR_ALWAYS ) {
table() {
tableModel(list:pointsList.object) {
closureColumn(header:'Name', read:{row -> return row.#name}, write:{ row, val -> row.#name = val} )
closureColumn(header:'Description', read:{row -> return row.#description}, write:{ row, val -> row.#description = val})
closureColumn(header:'Object Type', read:{row -> return pointTypeMap[row.#type.toInteger()]}, write:{ row, val -> row.#type = pointTypeMap.find{ it.value == val}?.key}) //fix this, lookup key
closureColumn(header:'Object ID', read:{row -> return row.#id.toInteger()}, write:{ row, val -> row.#id = val})
}
}
}
}
}
preview.show()
}
def openCSVDialog = new JFileChooser(
dialogTitle: "Choose a CSV file",
fileSelectionMode: JFileChooser.FILES_ONLY,
//the file filter must show also directories, in order to be able to look into them
fileFilter: [getDescription: {-> "*.csv"}, accept:{file-> file ==~ /.*?\.csv/ || file.isDirectory() }] as FileFilter)
swing = new SwingBuilder();
// Graphical User Interface
int sizex_01 = 325
int sizey_01 = 450
int locationx_01 = (1920 - sizex_01)/2
int locationy_01 = (1080 - sizey_01)/2
gui = swing.frame(title:'Discovery File Converter', location : [locationx_01, locationy_01], size:[sizex_01,sizey_01]) { // location : [locationx_01, locationy_01]
menuBar {
menu(text:'Preview') {
menuItem() {
action(name:'Preview CSV Data', closure:{ showPreview() })
}
}
}
gridBagLayout()
try
{
panel(constraints: gbc(gridx:0,gridy:0,gridwidth:REMAINDER, fill:HORIZONTAL)) {
label(icon:imageIcon('https://static.freeimages.com/images/convert-image.png'),
constraints:gbc(anchor:CENTER), )
}
}
catch(Exception ex)
{}
finally
{}
tabbedPane(id: 'tabs', tabLayoutPolicy:JTabbedPane.SCROLL_TAB_LAYOUT, constraints:gbc(ipadx:50)) //constraints:gbc(ipadx:300)
{ //JTabbedPane.WRAP_TAB_LAYOUT
panel(name:'General')
{
discoveryRow01 = 0
gridBagLayout()
// Line 1
label("Select spreadsheet parameters:", constraints:gbc(gridx:0,gridy:discoveryRow01, anchor:LINE_START)); discoveryRow01++
// Line 2
label("Object Name Column:", constraints:gbc(gridx:0,gridy:discoveryRow01, insets:[5,0,0,0], anchor:LINE_START))
textField(id:"objectNameColText", text: 'A', editable:true,
constraints:gbc(gridx:1,gridy:discoveryRow01, insets:[5,0,0,0],ipadx:20)); discoveryRow01++ //, fill:HORIZONTAL
// Line 3
label("Object Type Column:", constraints:gbc(gridx:0,gridy:discoveryRow01, insets:[5,0,0,0], anchor:LINE_START))
textField(id:"objectTypeColText", text: 'B', editable:true,
constraints:gbc(gridx:1,gridy:discoveryRow01, insets:[5,0,0,0],ipadx:20)); discoveryRow01++
// Line 4
label("Object Instance Column:", constraints:gbc(gridx:0,gridy:discoveryRow01, insets:[5,0,0,0], anchor:LINE_START))
textField(id:"objectTypeColText", text: 'C', editable:true,
constraints:gbc(gridx:1,gridy:discoveryRow01, insets:[5,0,0,0],ipadx:20)); discoveryRow01++
// Line 5
label("Object Description Column:", constraints:gbc(gridx:0,gridy:discoveryRow01, insets:[5,0,0,0], anchor:LINE_START))
textField(id:"objectDescColText", text: 'D', editable:true,
constraints:gbc(gridx:1,gridy:discoveryRow01, insets:[5,0,0,0],ipadx:20)); discoveryRow01++
// Line 6
label("Starting Object Row:", constraints:gbc(gridx:0,gridy:discoveryRow01, insets:[5,0,0,0], anchor:LINE_START))
textField(id:"startRowText", text: '2', editable:true,
constraints:gbc(gridx:1,gridy:discoveryRow01, insets:[5,0,0,0],ipadx:20)); discoveryRow01++
button( "Browse",
constraints:gbc(gridx:0,gridy:discoveryRow01, anchor:WEST),
actionPerformed: { evt ->
result = openCSVDialog.showOpenDialog()
switch ( result )
{
case JFileChooser.APPROVE_OPTION:
csvPath = openCSVDialog.getSelectedFile()
println csvPath
println "\nfile name=" + csvPath.toString()
csvFilePathBox.text = csvPath.toString()
// below code does not work yet for previewing
// def parsedCSV = new File(csvPath) //.replaceAll(' {1,5}','') // Reads info from discovery file
// println "parsedCSV worked"
break
case JFileChooser.CANCEL_OPTION:
break
case JFileChooser.ERROR_OPTION:
break
}
})
textField(id:"csvFilePathBox", constraints:gbc(gridx:1,gridy:discoveryRow01,ipadx:100,
gridwidth:REMAINDER, fill:HORIZONTAL))
}
}
button( "Update", constraints: gbc(gridx:0,gridy:2, gridwidth:REMAINDER, insets:[20,0,0,0], ipadx:20,ipady:20),
actionPerformed: { evt ->
// General Options
objectNameCol = objectNameColText.text.toUpperCase()
objectTypeCol = objectTypeColText.text.toUpperCase()
objectInstanceCol = objectInstanceColText.text.toUpperCase()
objectDescCol = objectDescColText.text.toUpperCase()
startRow = startRowText.text.toInteger()
csvFilePath = csvPath
def properties = new Properties()
readCSV(csvFilePath,outputFile, startRow, objectNameCol, objectTypeCol, objectInstanceCol, objectDescCol)
}
)
}
gui.show()
An example of the pathfile that the code tries to use is
C:\Users\abcd\Desktop\Sandbox\ALC Integration\file.csv
and it's pretty apparent Groovy and a lot of languages do not like this but it is "Windows" viewer-friendly when browsing for the file.
The other part that might be causing this is what is coded in the JFileChooser. Some other notes is I am working in a constrained environment for Groovy in ALC Eikon. Help understanding this challenge would be greatly appreciated!
Related
How to use excel text function "NUMBERVALUE" from Apache POI formula
I am using Apache POI to evaluate a formula cell that has a text function "NUMBERVALUE", then I got an exception Caused by: org.apache.poi.ss.formula.eval.NotImplementedFunctionException: _xlfn.NUMBERVALUE Interesting enough, when I try to regist this function WorkbookEvaluator.registerFunction("NUMBERVALUE", new NumberRValue()); it gives me another error: java.lang.IllegalArgumentException: NUMBERVALUE is not a function from the Excel Analysis Toolpack. I also tried to use the user-defined functions by implementing FreeRefFunction, it backs to the first error again. Caused by: org.apache.poi.ss.formula.eval.NotImplementedFunctionException: _xlfn.NUMBERVALUE How to implement a text function in Apache POI?
WorkbookEvaluator.registerFunction only works for functions apache poi at least knows per name. This are all functions listed through: java.util.Collection<String> unsupportedFuncs = org.apache.poi.ss.formula.WorkbookEvaluator.getNotSupportedFunctionNames(); System.out.println(unsupportedFuncs); All the listed functions can be registered using WorkbookEvaluator.registerFunction either as org.apache.poi.hssf.record.formula.functions.Function, when in org.apache.poi.hssf.record.formula.atp.AnalysisToolPak or else as org.apache.poi.hssf.record.formula.functions.FreeRefFunction if not. But NUMBERVALUE function is not in this list. So this only can be added as a user defined function. See User Defined Functions of apache poi's documentation. The function must implement org.apache.poi.ss.formula.functions.FreeRefFunction and must be registered in UDF toolpack of the Workbook. Following complete example shows a basic implementation of _xlfn.NUMBERVALUE. Implementation is done using the description in NUMBERVALUE function. It is a working draft until now and might need to be improved to better fulfill compatibility to Excel's own results. import java.io.FileInputStream; import java.util.Locale; import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.formula.functions.FreeRefFunction; import org.apache.poi.ss.formula.udf.AggregatingUDFFinder; import org.apache.poi.ss.formula.udf.DefaultUDFFinder; import org.apache.poi.ss.formula.udf.UDFFinder; import org.apache.poi.util.LocaleUtil; public class EvaluateNUMBERVALUE { public static void main( String[] args ) throws Exception { Workbook workbook = WorkbookFactory.create(new FileInputStream("./ExcelWithNUMBERVALUE.xlsx")); String[] functionNames = { "_xlfn.NUMBERVALUE" } ; FreeRefFunction[] functionImpls = { new NumberValue() } ; UDFFinder udfs = new DefaultUDFFinder( functionNames, functionImpls ) ; UDFFinder udfToolpack = new AggregatingUDFFinder( udfs ) ; workbook.addToolPack(udfToolpack); LocaleUtil.setUserLocale(Locale.US); FormulaEvaluator formulaEvaluator = workbook.getCreationHelper().createFormulaEvaluator(); DataFormatter dataFormatter = new DataFormatter(); for (Sheet sheet: workbook) { for (Row row : sheet) { for (Cell cell : row) { String cellValue = dataFormatter.formatCellValue(cell, formulaEvaluator); System.out.println(cellValue); } } } } } Class NumberValue used in above code: import java.lang.NumberFormatException; import java.util.Locale; import java.text.DecimalFormatSymbols; import org.apache.poi.ss.formula.OperationEvaluationContext; import org.apache.poi.ss.formula.eval.ValueEval; import org.apache.poi.ss.formula.eval.NumberEval; import org.apache.poi.ss.formula.eval.ErrorEval; import org.apache.poi.ss.formula.eval.EvaluationException; import org.apache.poi.ss.formula.eval.OperandResolver; import org.apache.poi.ss.formula.functions.FreeRefFunction; import org.apache.poi.util.LocaleUtil; public final class NumberValue implements FreeRefFunction { #Override public ValueEval evaluate( ValueEval[] args, OperationEvaluationContext ec ) { Locale locale = LocaleUtil.getUserLocale(); DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols(locale); String text = null; //If the Decimal_separator and Group_separator arguments are not specified, separators from the current locale are used. String decSep = String.valueOf(decimalFormatSymbols.getDecimalSeparator()); String groupSep = String.valueOf(decimalFormatSymbols.getGroupingSeparator()); Double result = Double.NaN; ValueEval v1 = null; ValueEval v2 = null; ValueEval v3 = null; try { if (args.length == 1) { v1 = OperandResolver.getSingleValue( args[0], ec.getRowIndex(), ec.getColumnIndex()); text = OperandResolver.coerceValueToString(v1); } else if (args.length == 2) { v1 = OperandResolver.getSingleValue( args[0], ec.getRowIndex(), ec.getColumnIndex()); v2 = OperandResolver.getSingleValue( args[1], ec.getRowIndex(), ec.getColumnIndex()); text = OperandResolver.coerceValueToString(v1); decSep = OperandResolver.coerceValueToString(v2).substring(0, 1); //If multiple characters are used in the Decimal_separator or Group_separator arguments, only the first character is used. } else if (args.length == 3) { v1 = OperandResolver.getSingleValue( args[0], ec.getRowIndex(), ec.getColumnIndex()); v2 = OperandResolver.getSingleValue( args[1], ec.getRowIndex(), ec.getColumnIndex()); v3 = OperandResolver.getSingleValue( args[2], ec.getRowIndex(), ec.getColumnIndex()); text = OperandResolver.coerceValueToString(v1); decSep = OperandResolver.coerceValueToString(v2).substring(0, 1); //If multiple characters are used in the Decimal_separator or Group_separator arguments, only the first character is used. groupSep = OperandResolver.coerceValueToString(v3).substring(0, 1); //If multiple characters are used in the Decimal_separator or Group_separator arguments, only the first character is used. } } catch (EvaluationException e) { e.printStackTrace() ; return e.getErrorEval(); } if("".equals(text)) text = "0"; //If an empty string ("") is specified as the Text argument, the result is 0. text = text.replace(" ", ""); //Empty spaces in the Text argument are ignored, even in the middle of the argument. For example, " 3 000 " is returned as 3000. String[] parts = text.split("["+decSep+"]"); String sigPart = ""; String decPart = ""; if (parts.length > 2) return ErrorEval.VALUE_INVALID; //If a decimal separator is used more than once in the Text argument, NUMBERVALUE returns the #VALUE! error value. if (parts.length > 1) { sigPart = parts[0]; decPart = parts[1]; if (decPart.contains(groupSep)) return ErrorEval.VALUE_INVALID; //If the group separator occurs after the decimal separator in the Text argument, NUMBERVALUE returns the #VALUE! error value. sigPart = sigPart.replace(groupSep, ""); //If the group separator occurs before the decimal separator in the Text argument , the group separator is ignored. text = sigPart + "." + decPart; } else if (parts.length > 0) { sigPart = parts[0]; sigPart = sigPart.replace(groupSep, ""); //If the group separator occurs before the decimal separator in the Text argument , the group separator is ignored. text = sigPart; } //If the Text argument ends in one or more percent signs (%), they are used in the calculation of the result. //Multiple percent signs are additive if they are used in the Text argument just as they are if they are used in a formula. //For example, =NUMBERVALUE("9%%") returns the same result (0.0009) as the formula =9%%. int countPercent = 0; while (text.endsWith("%")) { countPercent++; text = text.substring(0, text.length()-1); } try { result = Double.valueOf(text); result = result / Math.pow(100, countPercent); //If the Text argument ends in one or more percent signs (%), they are used in the calculation of the result. checkValue(result); } catch (EvaluationException e) { e.printStackTrace() ; return e.getErrorEval(); } catch (Exception anyex) { return ErrorEval.VALUE_INVALID; //If any of the arguments are not valid, NUMBERVALUE returns the #VALUE! error value. } return new NumberEval(result); } static final void checkValue(double result) throws EvaluationException { if (Double.isNaN(result) || Double.isInfinite(result)) { throw new EvaluationException(ErrorEval.NUM_ERROR); } } } What about the prefix _xlfn.? Excel uses this to mark functions which were introduced after Excel 2007. The prefix is stored as part of the function name. If the Excel version knows that function because it is later than Excel 2007, then the GUI will not show that prefix and evaluates the function. If the Excel version doesn't know that function, then the GUI will show the prefix to inform the user about that incompatibility. See Issue: An _xlfn. prefix is displayed in front of a formula Since the prefix is stored, the user defined function must be registered having the function name including the prefix: String[] functionNames = { "_xlfn.NUMBERVALUE" };. This code is public available. It is free to be reused in any kind of project. Of course it is without any warranty from my side.
Exception in thread "main" java.lang.ClassCastException: class [B cannot be cast to class [C ([B and [C are in module java.base of loader 'bootstrap')
I am trying to run my java project from cmd and taking back this error: **Exception in thread "main" java.lang.ClassCastException: class [B cannot be cast to class [C ([B and [C are in module java.base of loader 'bootstrap') at jodd.util.UnsafeUtil.getChars(UnsafeUtil.java:67) at jodd.json.JsonParser.parse(JsonParser.java:201) at IndexTester.main(IndexTester.java:78)** import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.Map; import jodd.json.JsonParser; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.TextField; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.LeafReader; import org.apache.lucene.index.SlowCompositeReaderWrapper; import org.apache.lucene.index.Terms; import org.apache.lucene.index.TermsEnum; import org.apache.lucene.queryparser.classic.ParseException; import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.lucene.queryparser.simple.SimpleQueryParser; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TopDocs; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; public class IndexTester { public static void main(String[] args) throws IOException, ParseException { if (args.length != 3) { System.err.println("Incorrect number of arguments! Usage:"); System.err.println(""); System.err.println("java IndexTester should_clear_index path_to_data path_to_index "); System.err.println("\tif should_clear_index is \"1\", the index will be rebuilt. Otherwise, it will try and use an existing index."); System.err.println("\tpath_to_index should point to an empty directory somewhere."); System.exit(-1); } String shouldClearIndex = args[0]; String inputPath = args[1]; // where to find the file containing the JSON to index String idxDirPath = args[2]; // where to put/find the Lucene index we want to search File inputFile = new File(inputPath); // set up analyzer: StandardAnalyzer analyzer = new StandardAnalyzer(); // set up the index File idxDir = new File(idxDirPath); Directory dir = FSDirectory.open(idxDir.toPath()); if (shouldClearIndex.compareTo("1") == 0) { System.out.println("Rebuilding index..."); IndexWriterConfig idxConfig = new IndexWriterConfig(analyzer); idxConfig.setOpenMode(IndexWriterConfig.OpenMode.CREATE); IndexWriter idxWriter = new IndexWriter(dir, idxConfig); // Now, populate the index: int idx = 0; JsonParser jParser = new JsonParser(); for (String line : Files.readAllLines(inputFile.toPath(), StandardCharsets.UTF_8)) { // On large amounts of data, this can take a while if (idx % 10000 == 0) { System.out.println(idx); } idx++; // each line of the input file is a serialized JSON object Map j = jParser.parse(line); // simple types (strings, numbers, etc.) are handled like so: String title = (String)j.get("title"); // complex types (lists or dicts) get turned into instances of // java.util.Map and java.util.List. String ab = (String)j.get("abstract"); // Look at the docs for TextField to see about other types- Lucene can index numbers, dates, etc. Field tiField = new Field("title", title, TextField.TYPE_STORED); // The TYPE_STORED directive tells Lucene to actually store the original token in the index. This is handy // for all sorts of reasons! // set up any additional fields here Document thisDoc = new Document(); thisDoc.add(tiField); // add our document to the index idxWriter.addDocument(thisDoc); } System.out.println("Done!"); System.out.println(idx + " documents indexed."); idxWriter.close(); } do { // Open up the index for querying: DirectoryReader reader = DirectoryReader.open(dir); // Tell me about the index (comment in/out as needed- this may be useful for debugging): // LeafReader slowC = SlowCompositeReaderWrapper.wrap(reader); // Terms idxTerms = slowC.terms("title"); // change to a different field as needed // TermsEnum tEnum = idxTerms.iterator(null); // System.out.println("Terms in the index for the title field:"); // while (tEnum.next() != null) { // String s = tEnum.term().utf8ToString(); // System.out.println(s + "\t" + tEnum.docFreq()); // } // Now search IndexSearcher searcher = new IndexSearcher(reader); // Things to note re: QueryParser: // 1. The first argument is the "default" field to search- // if nothing else is specified, in the query, this is what // will be searched. // 2. You always want to make sure to use the same Analyzer for your // query as you did when you built the index! // // Other query parser classes will behave similarly, but may have different argument ordering. QueryParser qParser = new QueryParser("title", analyzer); System.out.print("Query: "); String queryText = System.console().readLine(); if (queryText.compareTo("") != 0) { Query q = qParser.parse(queryText); TopDocs results = searcher.search(q, 10); System.out.println("Got " + results.totalHits + " hits!"); for (ScoreDoc d : results.scoreDocs) { System.out.println(d.doc + "\t" + d.score); Document res = reader.document(d.doc); System.out.println(res.getField("title").stringValue()); } } } while (true); // keep querying until user hits ctrl-C } } This is my code and thiis is my .txt file: [https://openeclass.uom.gr/modules/document/file.php/DAI148/%CE%94%CE%B9%CE%AC%CE%BB%CE%B5%CE%BE%CE%B7%2006%20-%20%CE%94%CE%B9%CE%B1%CE%B2%CE%B1%CE%B8%CE%BC%CE%B9%CF%83%CE%BC%CE%AD%CE%BD%CE%B7%20%CE%91%CE%BD%CE%AC%CE%BA%CF%84%CE%B7%CF%83%CE%B7%2C%20%CE%9C%CE%BF%CE%BD%CF%84%CE%AD%CE%BB%CE%BF%20%CE%94%CE%B9%CE%B1%CE%BD%CF%85%CF%83%CE%BC%CE%B1%CF%84%CE%B9%CE%BA%CE%BF%CF%8D%20%CE%A7%CF%8E%CF%81%CE%BF%CF%85/Using%20Lucene/data.txt.zip]
Please switch to the latest Jodd JSON v6. There is probably an issue with the UnsafeUtil.getChars. What you can do is the following: jParser.parse(line.toCharArray()); i.e. to skip using the UnsafeUtil.getChars(). The new version of Jodd is not using the Unsafe class anymore.
Oracle: Success with compilation error with Java in SQL AES256
I have a Java code that encrypts JSON data using AES 256. It works exactly as intended in the command prompt. But when I convert the same to SQL (Oracle server), it throws an error "success with compilation error". Below is the code: create or replace JAVA SOURCE NAMED encryptData AS import java.io.*; import java.security.*; import javax.crypto.*; import javax.crypto.spec.*; import javax.xml.bind.DatatypeConverter; import java.lang.Exception; import java.util.Scanner; import java.io.FileInputStream; import java.io.BufferedReader; import java.io.FileReader; public class encryptData { public static string encryptJSONCall(String jsonPath, String decSEK) { String decSEK = decSEK; File file = new File(jsonPath); Scanner sc = new Scanner(file); sc.useDelimiter("\\Z"); String json = removeWhitespaces(sc.next().replace("\n", "").replace("\r", "")); String encryptedResult = encryptBySymmetricKey(json, decSEK); System.out.println(encryptedResult); return encryptedResult; } public static String removeWhitespaces(String json) { boolean quoted = false; boolean escaped = false; String out = ""; for(Character c : json.toCharArray()) { if(escaped) { out += c; escaped = false; continue; } if(c == '"') { quoted = !quoted; } else if(c == '\\') { escaped = true; } if(c == ' ' &! quoted) { continue; } out += c; } return out; } public static String encryptBySymmetricKey(String json, String decryptedSek) { byte[] sekByte = DatatypeConverter.parseBase64Binary(decryptedSek); Key aesKey = new SecretKeySpec(sekByte, "AES"); try { Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, aesKey); byte[] encryptedjsonbytes = cipher.doFinal(json.getBytes()); String encryptedJson = DatatypeConverter.printBase64Binary(encryptedjsonbytes); return encryptedJson; } catch(Exception e) { return "Exception "+e; } } } / CREATE OR REPLACE FUNCTION encryptData_func(P_json varchar2,p_decSEK VARCHAR2) RETURN VARCHAR2 AS LANGUAGE JAVA NAME 'encryptData.encryptJSONCall( java.lang.String,java.lang.String ) return java.lang.String'; The problem is I am not able to find what is causing the error because there is no other explanation give out by the system. It just says "success with compilation error". Where am I going wrong?
I presume CREATE OR REPLACE FUNCTION encryptData_func ... returned that error. If that's so, connect to that Oracle user and run select * from user_errors where name = 'ENCRYPTDATA_FUNC'; --> note uppercase here! For example: SQL> create or replace function f_test 2 return number 3 as 4 begin 5 retval = 1; 6 end; 7 / Warning: Function created with compilation errors. SQL> select line, position, text 2 from user_errors 3 where name = 'F_TEST'; LINE POSITION TEXT ---------- ---------- ---------------------------------------------------- 5 10 PLS-00103: Encountered the symbol "=" when expecting one of the following: := . ( # % ; The symbol ":= was inserted before "=" to continue. Now that you know what's wrong with it, you'll be able to fix it (hopefully).
Compare 2 CSV files in JMeter
Screen capture of Result tree Code keeps running in infinite loop , wheather the data matches or not. Also i want to ignore the first/header column when comparing. Can you please help with this. Thanks I am using below code to compare 2 csv files. Input Files: File1 ColumnA A B C File2 ColumnA A B D Code #import java.io.File;# #import java.io.FileReader;# #import java.io.LineNumberReader;# String strfile1 = vars.get("thisScriptPath") + "file1.csv"; String strfile2 = vars.get("thisScriptPath") + "file2.csv"; def file1 = new File('/path/to/file1') def file2 = new File('/path/to/file2') def file1Lines = file1.readLines('UTF-8') def file2Lines = file2.readLines('UTF-8') if (file1Lines.size() != file2Lines.size()) { SampleResult.setSussessful(false) SampleResult.setResponseMessage('Files size is different, omitting line-by-line compare') } else { def differences = new StringBuilder() file1Lines.eachWithIndex { String file1Line, int number -> String file2Line = file2Lines.get(number) if (!file1Line.equals(file2Line)) { differences.append('Difference # ').append(number).append('. Expected: ').append(file1Line).append('. Actual: ' + file2Line) differences.append(System.getProperty('line.separator')) } } if (differences.toString().length() > 0) { SampleResult.setSuccessful(false) SampleResult.setResponseMessage(differences.toString()) } } REFER IMAGE
String pattern wit ha dollar present
I have the below data in a text file. CS##NEWSLTR$$ RY##GLMALAW$$ VW##NWL$$ VW##GLS$$ IS##4$$ ST##NJ$$ ST##NY$$ SORTX##0050004018001$$ RC##18 No. 4 GLMALAW 1$$ CR##18 No. 4 M & A Law. 1$$ SO3##The M & A Lawyer$$ DL##April, 2014$$ TI##DUSTING OFF APPRAISAL RIGHTS: THE DEVELOPMENT OF A NEW INVESTMENT STRATEGY$$ here i'm actually trying to fetch these values into a java array with the below code. package strings; import com.sun.org.apache.xalan.internal.xsltc.runtime.BasisLibrary; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; /** * * #author u0138039 */ public class Strings { /** * #param args the command line arguments */ public static void main(String[] args) { Scanner inFile1 = null; try { inFile1 = new Scanner(new File("C:\\Users\\u0138039\\Desktop\\Adhil\\WDA.TP.GLASSER.IB.F486806.A.D140605.T.txt")).useDelimiter("$\\\\\\\\\\\\$"); } catch (FileNotFoundException ex) { Logger.getLogger(Strings.class.getName()).log(Level.SEVERE, null, ex); } List<String> tokens = new ArrayList<String>(); while (inFile1.hasNext()) { tokens.add(inFile1.nextLine()); } String[] tokenArray = tokens.toArray(new String[0]); for (int i = 0; i < tokenArray.length; i++) { String s = tokenArray[i]; System.out.println("a["+i+"]" +tokenArray[i]); } } } here my concept is that the line ends with a $$ and this is how it should be stored in an array, but when i run the above program i get the below output. a[0]CS##NEWSLTR$$ a[1]RY##GLMALAW$$ a[2]VW##NWL$$ a[3]VW##GLS$$ a[4]IS##4$$ a[5]ST##NJ$$ a[6]ST##NY$$ a[7]SORTX##0050004018001$$ a[8]RC##18 No. 4 GLMALAW 1$$ a[9]CR##18 No. 4 M & A Law. 1$$ a[10]SO3##The M & A Lawyer$$ a[11]DL##April, 2014$$ a[12]TI##DUSTING OFF APPRAISAL RIGHTS: THE DEVELOPMENT OF A NEW INVESTMENT a[13] STRATEGY$$ here a[12] and a[13] belong to same array number(index), but here these are divided into 2. The expected output is as below(since the end $$ of a[12] came in a[13]) a[0]CS##NEWSLTR$$ a[1]RY##GLMALAW$$ a[2]VW##NWL$$ a[3]VW##GLS$$ a[4]IS##4$$ a[5]ST##NJ$$ a[6]ST##NY$$ a[7]SORTX##0050004018001$$ a[8]RC##18 No. 4 GLMALAW 1$$ a[9]CR##18 No. 4 M & A Law. 1$$ a[10]SO3##The M & A Lawyer$$ a[11]DL##April, 2014$$ a[12]TI##DUSTING OFF APPRAISAL RIGHTS: THE DEVELOPMENT OF A NEW INVESTMENT STRATEGY$$ please let me know where am i going wrong and how to fix it. Thanks
Forget the useDelimiter List<String> tokens = new ArrayList<String>(); int next = 0; while (inFile1.hasNext()) { String line = inFile1.nextLine(); if( next >= tokens.size() ){ tokens.add( line ); } else { tokens.set( next, tokens.get(next) + line ); } if( line.endsWith( "$$" ) ) next++; }
You're issuing a inFile1.nextLine() so naturally, the strings in a[12] and a[13] would be separated. One approach I can think of is putting the content of the file in a String object, then do a split using "\$\$" . String s = "Hello$$World$$Sample$$"; for(String sa: s.split("\\$\\$")) { System.out.println(sa); } Output: Hello World Sample But this will not include the trailing "$$" since you used it in the split. You can easily add that do the end of your string, but this is just one approach. Hope this helps.
String partialLine = null; while (inFile1.hasNext()) { String line = inFile1.nextLine(); if (partialLine != null) { line = partialLine + line; partialLine = null; } if (line.endsWith("$$") { tokens.add(line); } else { partialLine = line; } } if (partialLine != null) { // Probably empty line. } A bit of buffering: not adding a partial line (missing $$), but keeping it in partialLine. As you see even several partial lines would work.