I have one function that returns me String :
public String getString(String password){
......
try {
.......
encodedPassword = Base64.encodeToString(msgDigest,1 );
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return encodedPassword;
}
I want to add (concatenate) "=" String to returning string from function
I try using this:
encrptdPassword = getString("1234");
encrptdPassword = encrptdPassword+"=";
Or:
encrptdPassword = encrptdPassword .concat("=");
but I get result like two different objects (space or brake between)
I think problem is in Base64.encodeToString , but I must use 64 based string
Function getString returns me:
A6xnQhbz4Vx2HuGl4lXwZ5U2I8iziLRFnhP5eNfIRvQ
I want to add = to the returning string as:
A6xnQhbz4Vx2HuGl4lXwZ5U2I8iziLRFnhP5eNfIRvQ=
but I receive this on output
A6xnQhbz4Vx2HuGl4lXwZ5U2I8iziLRFnhP5eNfIRvQ =
Or:
A6xnQhbz4Vx2HuGl4lXwZ5U2I8iziLRFnhP5eNfIRvQ
=
...like 2 different strings.
Where I'm wrong?
I assume you're using Base64 from Apache Commons Codec.
The default constructor for this class uses "\r\n" as a line separator, which it adds to the end of every encoded line. If you don't want this, construct the object as:
new Base64(76, '');
If this isn't the class you're calling (it looks like from your code sample you're calling a static method), check the API and see if you can set a line separator for the conversion.
Isn't the 1 in Base64.encodeToString(msgDigest,1 ) padding?
If it's not, then you could just trim() the string to remove the whitespace.
Related
I have a string like this in Java:
"\xd0\xb5\xd0\xbd\xd0\xb4\xd0\xbf\xd0\xbe\xd0\xb9\xd0\xbd\xd1\x82"
How can I convert it to a human readable equivalent?
Note:
actually it is GWT and this string is coming from python as part of a JSON data.
The JSONParser transforms it to something that is totally irrelevant, so I want to be able to convert the string prior to parsing.
The expected, so called by me "human readable", should be "ендойнт" (https://mothereff.in/utf-8#%D0%B5%D0%BD%D0%B4%D0%BF%D0%BE%D0%B9%D0%BD%D1%82)
Assuming that the pattern is a repetition of characters in the form of "\x00", where 00 can be any number or letter in [a-fA-F], you can convert it with something like this:
String values = "\\xd0\\xb5\\xd0\\xbd\\xd0\\xb4\\xd0\\xbf\\xd0\\xbe\\xd0\\xb9\\xd0\\xbd\\xd1\\x82";
for (String val: values.split("\\\\x")) {
if (val.length() > 0 ) System.err.print((char) Integer.parseInt(val, 16));
}
Note that the if condition is due to the first delimiter: see How to prevent java.lang.String.split() from creating a leading empty string?
I don't know if it's just my console or it's not working, but you may try this code:
import java.io.UnsupportedEncodingException;
import javax.xml.bind.DatatypeConverter;
public class Utf8Decoder {
public static void main(String[] args) {
// TODO Auto-generated method stub
String url = "\\xd0\\xb5\\xd0\\xbd\\xd0\\xb4\\xd0\\xbf\\xd0\\xbe\\xd0\\xb9\\xd0\\xbd\\xd1\\x82";
url= url.replaceAll("\\\\x", ""); //remove the \x on the string...
//it is now hex so let's parse it
//convert to human readable text
String result="";
try {
byte[] bytes= DatatypeConverter.parseHexBinary(url);
result = new String(bytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.print("decoded value:"+result);
}
}
I need help before I'm totally despaired :D
As you will see I tried it in different ways even if there are just a really few differences. My problem is that I have a string which I want (or have) to output. This means I need it in a text file. Not that big problem, eh? But the actual problem is that I want line breaks instead of commas. I know I could just replace them after the file is written but it's just unnecessary when there is another way.
The Output looks like this
[/rechtschreibung/_n, /rechtschreibung/_nauf, /rechtschreibung/_naus,
/rechtschreibung/_Ndrangheta, ....]
I want it to look like this
/rechtschreibung/_n
/rechtschreibung/_nauf
/rechtschreibung/_naus
/rechtschreibung/_Ndrangheta
Anyway even when I don't need this method later because I will store this and some other information into a database like sql. It will help me to build up the program step by step and learn some more Java ;)
So here is my code snippet
BufferedWriter bw = null;
//PrintWriter out
//= new PrintWriter(new BufferedWriter(new FileWriter("foo.out")));
try {
bw = new BufferedWriter(new FileWriter("bfwr.txt"));
bw.write(test5.getWoerterListe().toString());
bw.newLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
try {
PrintWriter out = new PrintWriter(new FileWriter("prwr.txt"));
out.print(test5.getWoerterListe());
out.close();
System.out.printf("Testing String");
} catch (IOException e) {
e.printStackTrace();
}
*/
/*
try {
FileWriter test10 = new FileWriter("test.txt");
test10.write(test5.getWoerterListe().toString());
test10.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
*/
Please be nice to me :D
Assistance appreciated =)
EDIT #1
Code directly before first one.
Oberordner test2 = new Oberordner("http://www.duden.de/definition");
Unterordner test3 = new Unterordner(test2.getOberOrdner());
WoerterListe test5 = new WoerterListe(test3.getUnterOrdnerURL());
test5.setWoerterListe();
and from WoerterListe.java the really end part
public ArrayList<String> getWoerterListe(){
return WoerterListe;
}
Additional Information: the string is not stored in the code because there are tenthousands of words like '/rechtschreibung/*'
By the way the language here is german unfortunately I have to use german words =(
I'm not a Java developer and you didn't state what getWoerterListe() returns, but here's my guess.
getWoerterListe() probably return a list of strings, and the default behaviour of toString() in this case is to convert the list to comma seperated values. So instead of calling toString() on the list, loop through it and write out each line followed by a carriage return (or whatever Java uses to end lines).
Code:
String s = "[/rechtschreibung/_n, /rechtschreibung/_nauf, "
+ "/rechtschreibung/_naus, /rechtschreibung/_Ndrangheta, ....]";
String srp = s.replaceAll("\\[|\\]|\\.+" ,"");
String[] sp = srp.split(",");
for (int i = 0; i < sp.length; i++) {
System.out.println(sp[i].trim());
}
Output:
/rechtschreibung/_n
/rechtschreibung/_nauf
/rechtschreibung/_naus
/rechtschreibung/_Ndrangheta
Explanation:
I assumed [/rechtschreibung/_n, /rechtschreibung/_nauf, /rechtschreibung/_naus, /rechtschreibung/_Ndrangheta, ....] is a String. I removed all uncessary character like [ , ] , and any number of . form it. After that, I splited by , and print each element of splited string on the output.
I think the easiest way to explain my problem is with a little example:
My string at the beginning is: Pâtes, and the result should be: Pâtes. What I get as result is still Pâtes How can I fix this?
Here the code:
private String encode(String string) {
try {
byte ptext[] =string.getBytes("UTF8");
string = new String(ptext, "UTF8");
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return string;
}
There are two problems with your code. The first is that you're using UTF8, but the correct character set is UTF-8.
The second is that you're essentially performing a no op. By calling byte ptext[] =string.getBytes("UTF-8"); you are saying that this string is UTF-8. Then you convert it to UTF-8 which it already is.
What I think you mean is that the input is ISO-8859-1 and you want to convert it to UTF-8. (This fits with the example input and output you've given).
Try:
private String encode(String string) {
try {
byte ptext[] = string.getBytes("ISO-8859-1");
string = new String(ptext, "UTF-8");
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return string;
}
This assumes that your initial string was originally read from somewhere and only contains ISO-8859-1 characters. As mentioned in a comment you should try to ensure the data is loaded in correctly from the source (i.e. when it is still just an array of bytes).
It gives a message saying: "Null pointer access: The variable CharacterList can only be null at this location", when I think it should be filled from the FileReader.Read() method:
public String[] ReadPeopleFile(String[] PeopleList, FileReader PeopleReader){
char CharacterList[];///Soon parsed into a string list, by delimiting and separating into two string arrays,
CharacterList = null;
String ParseString = null;
try {
PeopleReader.read(CharacterList);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ParseString = CharacterList.toString();
PeopleList = ParseString.split(";");
return PeopleList;
}
CharacterList is not going to be assigned unless you assign it. You need something more like this:
char characterList[] = new char[1000]; // I'm assuming that 1000 is enough here
int numChars = peopleReader.read(characterList); // I've changed PeopleReader to proper camel-case
String parseString = new String(characterList, 0, numChars);
I'm actually skipping some details here. You should really look at the API documentation for FileReader and maybe find some file reading examples.
I'm passing an object to constructor and then adding parameters of this object to HL7.
ORU_R01 is the type of HL7.
When i print HL7 to console, only the last OBX is printed.
What is wrong with my code?
How can i write this HL7 message to socket?
Is there simpler way in java to handel HL7?
public class FlexSMessageHL7 {
private FileWriter writeHL7ToFile;
private PrismaflexSMessage sMessage;
private ORU_R01 message;
private int i = 0;
private OBX obx = null;
public FlexSMessageHL7(FlexSMessage sMessage) {
this.sMessage = sMessage;
this.message = new ORU_R01();
createHL7SMessage();
}
public void createHL7SMessage() {
// Populate the MSH Segment
MSH msh = message.getMSH();
try {
msh.getFieldSeparator().setValue("|");
msh.getEncodingCharacters().setValue("^~\\&");
msh.getDateTimeOfMessage().setValue(sMessage.getTime().toString());
msh.getSendingApplication().getNamespaceID().setValue(String.valueOf(sMessage.getMachID()));
} catch (DataTypeException e) {
e.printStackTrace();
}
// Populate the OBR Segment:time
OBR obr = message.getPATIENT_RESULT().getORDER_OBSERVATION().getOBR();
try {
obr.getObservationDateTime().setValue(String.valueOf(sMessage.getTime()));
} catch (DataTypeException e) {
e.printStackTrace();
}
// Populate the PID Segment:PatientId
PID pid = message.getPATIENT_RESULT().getPATIENT().getPID();
try {
pid.getPatientID().getIDNumber().setValue(sMessage.getPatID());
} catch (HL7Exception e) {
e.printStackTrace();
}
// Populate the OBX Segment:Param_Code, time, Measure_Value
while (i < sMessage.getMsgInfo()) {
for (PrismaflexSRecord sRecord : sMessage.getsRecordCollection()) {
try {
obx = message.getPATIENT_RESULT().getORDER_OBSERVATION().getOBSERVATION(i).getOBX();
obx.getSetIDOBX().setValue(String.valueOf(i));
obx.getObservationIdentifier().getIdentifier().setValue(sRecord.getParamCode());
obx.getDateTimeOfTheObservation().setValue(String.valueOf(sRecord.getTimeStamp()));
obx.getObservationIdentifier().getNameOfCodingSystem().setValue(String.valueOf(sRecord.getMeasureValue()));
i++;
} catch (HL7Exception e) {
e.printStackTrace();
}
}
}
try {
writeHL7ToFile = new FileWriter(File.createTempFile("prismaflexOutputFrom3001HL7", "txt", new File
("c:\\tmp\\prismaflex")));
writeHL7ToFile.write(message.getMSH().toString());
writeHL7ToFile.flush();
} catch (IOException e) {
e.printStackTrace();
}
// Now, Encode the message and look at the output
try {
Parser parser = new PipeParser();
String encodedMessage = parser.encode(message);
System.out.println("Printing HL7 Encoded Message:");
System.out.println(encodedMessage);
} catch (HL7Exception e) {
e.printStackTrace();
}
}
}
As Nicholas Orlowski pointed out, the problem is in the line ending characters, which according to the HL7 standard are CR characters which make a Windows command prompt only reset the cursor to the beggining of the line and overwrite it with next line's content. Therefore for console output You need to replace the line-endings with something else.
For a recent HL7 app using HAPI, which You also seem to be using, I made a little helper method to achieve this function:
private static String replaceNewlines(String input) {
return input.replaceAll("\\r", "\n");
}
The function can be used on all platforms, as it replaces the CR characters with the OS-specific newline character(s).
Then I can use it to output to console as follows:
LOGGER.trace("Generated message contents:\n" + replaceNewlines(outMessage.encode()));
In this case I am using log4j for logging to console, not simple console printout, but the problem was the same for me.
Hope it helps!
Have you considered using the HAPI? It is written for java, it's counter part nHAPI is written for .net as well. Details here:
http://hl7api.sourceforge.net/
I have had a similar problem in my python HL7py library. Many times the console doesn't like printing characters. I had to write a helper that changed CR to LF (line feed) to display the lines correctly. Hope that helps.
It won't display in the console but it will when you write to the file. Try looking at the variable in debug mode and writing it to a file.