Problem in writing special characters to a properties file in Java - java

I need to add key value pairs to a properties file.
All are working fine except # and = everytine a \ is appended before the characters.
Please share me any suggestion.
current properties file data
paper = Normalised
I want to comment this key
#paper = Normalised
but what is happening is \ is getting added
\#paper = Normalised
'''
String valueOfKey = updatedMap.get(key);
updatedMap.remove(key);
updatedMap.put("#" + key, valueOfKey);
String totalPath = propertiesService.getFilePath(request) + "\\" + propertiesModel.getSelectedFile();
propertiesService.updatePropertyfile(updatedMap, request, totalPath);
'''
'''
public boolean updatePropertyfile(Map<String, String> map, HttpServletRequest request, String fileName) {
Properties props = new Properties();
Writer Out = null;
File file = new File(fileName);
try {
FileOutputStream out = new FileOutputStream(file);
Out = new BufferedWriter(new OutputStreamWriter(out));
Set<String> keyset = map.keySet();
Iterator iter = keyset.iterator();
while (iter.hasNext()) {
String key = (String) iter.next();
props.setProperty(key, (String) map.get(key));
}
props.store(Out, "update");
Out.flush();
Out.close();
} catch (IOException e) {
return false;
}
return true;
}
'''
Value in property file getting written
\#paper = Normalised

The hash tag is the lead-in for a comment in Java Properties files:
# Created by generator on 2020-05-01
#current properties file data
paper = Normalised
#want to update like
#paper = Normalised – but this is a comment …
#but what is happening is \# is getting added
\#paper = Normalised # Backslash required …
So the escape with the backslash is the only way to get it working.
Unfortunately, when you need to read the Properties file with another API than java.util.Properties, you have to add this capability to your parser.

Related

PDF file generation. Java

I am forming a pdf file. When generating a file locally in Idea - pdf is generated correctly. And if you send this file to MiniO S3 - instead of Russian letters, the symbols '#' are generated
I myself tried to specify the encoding explicitly via metadata.setContentType ("application / pdf; charset = utf-8"); Does not help :-(
Now I'm more inclined to add fonts. Tell me how I can add this to the existing code.
Thank you in advance!
#SneakyThrows
public byte[] createDocument(PaymentInstructionModel model) {
WordprocessingMLPackage word = Docx4J.load(new ClassPathResource("template.docx").getInputStream());
MainDocumentPart mainDocumentPart = word.getMainDocumentPart();
Map<String, String> variables = objectMapper.convertValue(model, new TypeReference<>() {});
mainDocumentPart.variableReplace(variables);
ByteArrayOutputStream os = new ByteArrayOutputStream();
Docx4J.toPDF(word, os);
return os.toByteArray();
}
byte[] document = documentService.createDocument(model);
String key = String.format("%s/%d-%d-%d_Платёж_№%s.pdf",
event.getPaymentNumber(),
event.getPaymentDate().getYear(),
event.getPaymentDate().getMonthValue(),
event.getPaymentDate().getDayOfMonth(),
event.getPaymentNumber());
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentLength(document.length);
amazonS3.putObject(S3Buckets.CLIENT_PAYMENT_PDF_BUCKET, key, new ByteArrayInputStream(document), metadata);
try this method:
public String escapeHtml(String value) {
if (value == null) {
return "";
} else {
return value
.replaceAll("\u001F", "")
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll("\"", """);
}
}

Java How to write a string in file as bytes and get string back

I need to write a string in a file as bytes in UTF-8 and then get these bytes back from file and convert it back to string and as a consiquence get the same string. May be it sounds easy but there is a hidden problem such as incorrect symbols in file. I mean that after appending in file it must contain something like:
00000008 d0bad0bb d18ed187 00000010 etc...
But it contains stuff like that:
mystring ---a lot of space--- (and the symbol that doesn't display here)
So, what have I already done? I've tried this way:
Before code read this: I keep strings in HashMap < String, String > that's why my code contains get(...) etc.
try {
FileOutputStream oStream = new FileOutputStream("filename.txt");
Set<String> keySet = storage.keySet();
ByteBuffer buffer = ByteBuffer.allocate(1024);
for (String key : keySet) {
byte[] keyInByte = key.getBytes("UTF-8");
byte[] valueInByte = storage.get(key).getBytes("UTF-8");
oStream.write(buffer.putInt(0, valueInByte.length).array());
oStream.write(keyInByte);
oStream.write((buffer.putInt(0, valueInByte.length).array()));
oStream.write(valueInByte);
}
} catch (Exception e) {
System.err.println("permission denied");
}
I have also tried use PrintWriter, FileWriter, etc... but it doesn't give what I need. For example, some of them need toString() method but after toString() I will lose the ability to work with bytes.
! Notice, that I've tried to change my notepad to UTF-8 encode, but it gives no result.
If you want to use Properties you can do this.
new Properties(map).save(new FileOutputStream("filename.proeprties"));
to load the properties
Properties prop = new Properties();
prop.load(new FileInputStream("filename.properties"));
map.putAll(prop);
To save copying the data you can use Properties as a Map.
key1=value1
key2=value2
Note: a key cannot contain a = or a newline.
This is how I would do it in a binary format
DataOutputStream dos = new BufferedOutputStream(new FileOutputStream("filename.dat")));
dos.writeInt(map.size());
for (Map.Entry<String, String> entry : map.entrySet()) {
dos.writeUTF(entry.getKey());
dos.writeUTF(entry.getValue());
}
dos.close();
This is how I would write it in text, using UTF-8
PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOuputStream("filename.txt") "UTF-8"));
pw.println(map.size());
for (Map.Entry<String, String> entry : map.entrySet()) {
pw.println(encode(entry.getKey()));
pw.println(encode(entry.getValue()));
}
pw.close();
public static String encode(String s) {
// if you can assume no new lines, don't do anything.
return s.replaceAll("\\\\", "\\\\\\\\").replaceAll("\n", "\\\\n");
}
This will produce a like like
key1
value1
key2
value2
This you can edit fairly easy. If youc an assume the key doesn't have an = or : or tab, you can use one line like a properties file

how to export the data in file using java

I need to export the values in 4 column.values for 3 columns are populating properly.
I am having trouble with 4th column which is organization column.it is multivalued column.i.e.: it has multiple values.
I have tried to convert from object to String for organization column but didnt help.
Please see the code below:
String appname = "abc";
String path = "//home/exportfile//";
String filename = path+"ApplicationExport-"+appname+".txt";
String ret = "false";
QueryOptions ops = new QueryOptions();
Filter [] filters = new Filter[1];
filters[0] = Filter.eq("application.name", appname);
ops.add(filters);
List props = new ArrayList();
props.add("identity.name");
//Do search
Iterator it = context.search(Link.class, ops, props);
//Build file and export header row
BufferedWriter out = new BufferedWriter(new FileWriter(filename));
out.write("Name,UserName,WorkforceID,organization");
out.newLine();
//Iterate Search Results
if (it!=null)
{
while (it.hasNext()) {
//Get link and create object
Object [] record = it.next();
String identityName = (String) record[0];
Identity user = (Identity) context.getObject(Identity.class, identityName);
//Get Identity attributes for export
String workforceid = (String) user.getAttribute("workforceID");
//Get application attributes for export
String userid="";
List links = user.getLinks();
if (links!=null)
{
Iterator lit = links.iterator();
while (lit.hasNext())
{
Link l = lit.next();
String lname = l.getApplicationName();
if (lname.equalsIgnoreCase(appname))
{
userid = (String) l.getAttribute("User Name");
List orgList = l.getAttribute("Organization");
}
}
}
//Output file
out.write(identityName+","+userid+","+workforceid+","+org);
out.newLine();
out.flush();
}
ret="true";
}
//Close file and return
out.close();
return ret;
The output of this code should be:
for ex:
Name,UserName,WorkforceID,organization
abc,abc,123,xy
qwe,q01,234,xy
any help correcting this code will be greatly appreciated.
EDIT:
This should give you the output you want:
out.write(identityName+","+userid+","+workforceid+","+Arrays.toString(orgList.toArray());
you probably want to declare List orgList outside the while loop since everytime it is being created and also you are using org and i havent seen any org elsewhere in your code

How do I utilize a config file with my Java program?

I'm trying to use a config file that holds a list of hosts/websites and a time frequency for each one.
ex.
google.com 15s
yahoo.com 10s
My objective is to ping each website from the config file at every time period (15 secs).
Should I just read the config file and input the hosts/time into separate arrays?
Seems like there is a more efficient method...
Why use two arrays when the two items are so intimately related?
I'd put them into a Map:
Map<String, Integer> pingUrlTimes = new HashMap<String, Integer>();
pingUrlTimes.put("google.com", 15);
pingUrlTimes.put("yahoo.com", 10);
int pingTime = pingUrlTimes.get("google.com");
Here is a quick rundown of how to use a properties file.
You can create a file with the extension .properties (if under Windows make sure you have file extensions displayed) in the root of your project. The properties can be defined as pairs:
google.com=15
yahoo.com=10
In Java,
To get the ping time of a particular URL:
final String path = "config.properties";
Properties prop = new Properties();
int pingTimeGoogle = prop.load(new FileInputStream(path)).getProperty("google.com");
To cycle through the properties and get the whole list:
final String path = "config.properties";
Properties props = new Properties().load(new FileInputStream(path));
Enumeration e = props.propertyNames();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
System.out.println(key + "=" + props.getProperty(key));
}
Edit: And here's a handy way to transform properties into a Map (Properties implements the Map interface):
final String path = "config.properties";
Properties props = new Properties().load(new FileInputStream(path));
Map<String, Integer> pingUrlTimes = new HashMap<String, Integer>((Map) props);
Cycling through the HashMap can be done like this:
Iterator iterator = pingUrlTimes.keySet().iterator(); // Get Iterator
while (iterator.hasNext()) {
String key = (String) iterator.next();
System.out.println(key + "=" + pingUrlTimes.get(key) );
}

Open Microsoft Word in Java

I'm trying to open MS Word 2003 document in java, search for a specified String and replace it with a new String. I use APACHE POI to do that. My code is like the following one:
public void searchAndReplace(String inputFilename, String outputFilename,
HashMap<String, String> replacements) {
File outputFile = null;
File inputFile = null;
FileInputStream fileIStream = null;
FileOutputStream fileOStream = null;
BufferedInputStream bufIStream = null;
BufferedOutputStream bufOStream = null;
POIFSFileSystem fileSystem = null;
HWPFDocument document = null;
Range docRange = null;
Paragraph paragraph = null;
CharacterRun charRun = null;
Set<String> keySet = null;
Iterator<String> keySetIterator = null;
int numParagraphs = 0;
int numCharRuns = 0;
String text = null;
String key = null;
String value = null;
try {
// Create an instance of the POIFSFileSystem class and
// attach it to the Word document using an InputStream.
inputFile = new File(inputFilename);
fileIStream = new FileInputStream(inputFile);
bufIStream = new BufferedInputStream(fileIStream);
fileSystem = new POIFSFileSystem(bufIStream);
document = new HWPFDocument(fileSystem);
docRange = document.getRange();
numParagraphs = docRange.numParagraphs();
keySet = replacements.keySet();
for (int i = 0; i < numParagraphs; i++) {
paragraph = docRange.getParagraph(i);
text = paragraph.text();
numCharRuns = paragraph.numCharacterRuns();
for (int j = 0; j < numCharRuns; j++) {
charRun = paragraph.getCharacterRun(j);
text = charRun.text();
System.out.println("Character Run text: " + text);
keySetIterator = keySet.iterator();
while (keySetIterator.hasNext()) {
key = keySetIterator.next();
if (text.contains(key)) {
value = replacements.get(key);
charRun.replaceText(key, value);
docRange = document.getRange();
paragraph = docRange.getParagraph(i);
charRun = paragraph.getCharacterRun(j);
text = charRun.text();
}
}
}
}
bufIStream.close();
bufIStream = null;
outputFile = new File(outputFilename);
fileOStream = new FileOutputStream(outputFile);
bufOStream = new BufferedOutputStream(fileOStream);
document.write(bufOStream);
} catch (Exception ex) {
System.out.println("Caught an: " + ex.getClass().getName());
System.out.println("Message: " + ex.getMessage());
System.out.println("Stacktrace follows.............");
ex.printStackTrace(System.out);
}
}
I call this function with following arguments:
HashMap<String, String> replacements = new HashMap<String, String>();
replacements.put("AAA", "BBB");
searchAndReplace("C:/Test.doc", "C:/Test1.doc", replacements);
When the Test.doc file contains a simple line like this : "AAA EEE", it works successfully, but when i use a complicated file it will read the content successfully and generate the Test1.doc file but when I try to open it, it will give me the following error:
Word unable to read this document. It may be corrupt.
Try one or more of the following:
* Open and repair the file.
* Open the file with Text Recovery converter.
(C:\Test1.doc)
Please tell me what to do, because I'm a beginner in POI and I have not found a good tutorial for it.
First of all you should be closing your document.
Besides that, what I suggest doing is resaving your original Word document as a Word XML document, then changing the extension manually from .XML to .doc . Then look at the XML of the actual document you're working with and trace the content to make sure you're not accidentally editing hexadecimal values (AAA and EEE could be hex values in other fields).
Without seeing the actual Word document it's hard to say what's going on.
There is not much documentation about POI at all, especially for Word document unfortunately.
I don't know : is its OK to answer myself, but Just to share the knowledge, I'll answer myself.
After navigating the web, the final solution i found is :
The Library called docx4j is very good for dealing with MS docx file, although its documentation is not enough till now and its forum is still in a beginning steps, but overall it help me to do what i need..
Thanks 4 all who help me..
You could try OpenOffice API, but there arent many resources out there to tell you how to use it.
You can also try this one: http://www.dancrintea.ro/doc-to-pdf/
Looks like this could be the issue.

Categories