I have written a code in java, where there are forms (input fields) and finally a send email button at the bottom. when the user clicks on the button, the data from the input fields should get extracted then be used as data for the body in the email.
this is the code i have:
if (role.getValue().equals("1")) {
Desktop desktop = Desktop.getDesktop();
String message = "mailto:username#domain.com?subject=Profildaten&body=" +
"Externe%20Referenz:%20" +
person.getExternalReference() + "%20" + "-%20" +
person.getExternalReferenceType() + "%0A" +
person.getTitle() + "%20" +
person.getContactLandline() + "%0A" +
"Mobil:%20" + person.getContactMobile() + "%0A" +
"Addresse:" + person.getContactStreet();
URI uri = URI.create(message);
try {
desktop.mail(uri);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
It all works perfectly, but the only issue is for Address: person.getContactStreet() the actual input field requires the user to enter a street name, and usually it would be two words, e.g. Cromwell Road - with a space inbetween cromwell and road. now the body of the email doesnt allow to have spaces and other invalid characters, hence why it is popping an error message saying invalid characters have been entered. how can i make it accept this or convert the invalid characters automatically to url encodings?
Have a look at this site, it tells you how to encode the URLS in the body automatically.
Best way to encode URL in Java
Related
I am trying to implement http/1.0 in a project with a website that's loaded with a serversocket i've coded. It works fine with character based files. But with image files that i've specified to return the base64 encoded version of the image doesn't work even though the right headers are set such as content-type: image/png and content-transfer-encoding: base64 RFC 2045. I've tried to look at the packets from chrome's networking tool and it looks like it's treating it as a document event though it's an image file. I have no clue whatsoever to do since i've been stuck on this issue for a couple of DAYS! I've searched all of stackoverflow, all of google and i am basically stuck.
I posted this question a day or 2 ago where it was recommended to use a byte reader (which i've also tried) without luck. Any visual inputs are of great appreciation.
I have 2 methods that are relevant.
The first one is the one where i choose the way to read the file depending on if it's an image or text.
public String readUri(String reqUri) {
returnFile = "";
if (this.fileExists(reqUri)) {
fileType = this.fileType(reqUri); // returns e.g image from image/png
if (fileType.equals("text")) {
// bufferedreader ...
} else if (fileType.equals("image")) {
File imgPath = new File(reqUri);
try {
FileInputStream fileInputStreamReader = new FileInputStream(imgPath);
byte[] bytes = new byte[(int)imgPath.length()];
fileInputStreamReader.read(bytes);
returnFile = Base64.getEncoder().encodeToString(bytes);
fileInputStreamReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return returnFile;
}
The second one collects this data from the above method. This method is called in my get request controller and sends back the data to the client through the serversocket.
StringBuilder response = new StringBuilder();
public String response(
String HTTPVersion, int statusCode, String fileContent, String contentType) {
response.append(
HTTPVersion + " " +
statusCode + " " +
this.getHTTPStatusText(statusCode) + "\n"
);
response.append("Content-transfer-encoding: BASE64");
response.append("Content-Type: " + contentType + "\n");
response.append("content-length: " + fileContent.length() + "\n");
response.append("Date: " + date() + "\n");
response.append("\n");
response.append(fileContent + "\n");
return response.toString();
}
Here is a request/response from chromes networking tool:
This is how the image is currently loaded with the base64 encoding:
HTTP IS NOT MIME
RFC 2045 is MIME, and although HTTP is similar in some respects to MIME, it is not MIME, and it differs in other respects. In particular it DOES NOT USE Content-Transfer-Encoding. It DOES USE Content-Encoding with a similar meaning. See https://www.rfc-editor.org/rfc/rfc1945#section-10.3 and https://www.rfc-editor.org/rfc/rfc1945#appendix-C.3 et seq.
Also, you are terminating the lines of the response header with only Java \n which is LF. The standards call for CR LF (Java \r\n) and always have. Some receivers are tolerant, following Postel's dictum, but you shouldn't rely on that. And worse your code doesn't appear to terminate the CTE line at all, although since Chrome parsed it okay I'm guessing you just posted the wrong code. Also you should NOT add a line terminator after the body that isn't counted in Content-Length, although if you are using original HTTP/1.0, i.e. without keepalive, this won't matter, because there can't be another request and response on the same transport connection.
I have a program that has a button which prints out the html text of a web address.I have got a variable that will have an address in the text box already, the issue is if I change the text in the text box to another address it will still print out the same html address. I've worded this issue badly but hopefully it's understandable. I want to be able to enter an URL and get that address html instead of going into the code eveytime and change the variable manually.
/* Create a HttpInteract object. */
public HttpInteract(String url) {
/* Split the "URL" into "host name" and "path name", and
* set host and path class variables.
* if URL is only a host name, use "/" as path
*/
System.out.println("URL splits into host name and path name.");
host = "cgi.csc.liv.ac.uk";
System.out.println("Host is:" +host);
path = "/~gairing/test.txt";
System.out.println("Path is:" +path);
//Request message. Connection closes after response because http 1.0
//is non persistent
requestMessage= "GET "+path+ " HTTP/1.1\r\n"
+"Host: " +host+ "\r\n"
+"\r\n" ;
return;
}
Simple example using URL:
// Note that you need protocol for valid URL
URL url = new URL("http://cgi.csc.liv.ac.uk/~gairing/test.txt");
System.out.println("Host:" + url.getHost());
System.out.println("Path:" + url.getPath());
I am trying to create an HL7 message in Java and then print the resulting message. I am faking basic patient information and then adding the Drug Prescription information. Then, I want to print the complete message but I wasn't able to use the API correctly. I am new at using HL7, so I know I'm probably missing some required segments and even using the wrong ones, can you please help? This is my current code:
public RXO runDrugPrescriptionEvent(CMSGeneric cmsgen) {
CMSDrugPrescriptionEvent cmsic = (CMSDrugPrescriptionEvent) cmsgen;
ADT_A28 adt23 = new ADT_A28();
try {
adt23.initQuickstart("ADT", "A08", cmsic.getPDE_EVENT_ID());
// We set the sex identity (male or female)
if (cmsic.getBENE_SEX_IDENT_CD() == 1) {
adt23.getPID().getSex().setValue("Male");
}
else {
adt23.getPID().getSex().setValue("Female");
}
// We set a fake name and family name
adt23.getPID().insertPatientName(0).getGivenName().setValue("CMS Name " + MainTest.NEXT_PATIENT_ID);
adt23.getPID().insertPatientName(0).getFamilyName().setValue("CMS Family name " + MainTest.NEXT_PATIENT_ID);
MainTest.NEXT_PATIENT_ID++;
RXO rxo = new RXO(adt23, new DefaultModelClassFactory());
rxo.getRxo1_RequestedGiveCode().getCe1_Identifier().setValue("" + cmsic.getPDE_DRUG_CD());
rxo.getRxo18_RequestedGiveStrength().setValue("" + cmsic.getPDE_DRUG_STR_CD());
rxo.getRxo19_RequestedGiveStrengthUnits().getCe1_Identifier().setValue("" + cmsic.getPDE_DRUG_STR_UNITS());
rxo.getRxo5_RequestedDosageForm().getCe1_Identifier().setValue("" + cmsic.getPDE_DRUG_DOSE_CD());
rxo.getRxo11_RequestedDispenseAmount().setValue("" + cmsic.getPDE_DRUG_QTY_DIS());
HapiContext context = new DefaultHapiContext();
Parser parser = context.getPipeParser();
String encodedMessage = adt23.getParser().encode(rxo.getMessage());
logger.debug("Printing Message:");
logger.debug(encodedMessage);
return rxo;
} catch (IOException e) {
System.out.println("IOException creating HL7 message. " + e.getMessage());
e.printStackTrace();
} catch (HL7Exception e) {
System.out.println("HL7Exception creating HL7 message. " + e.getMessage());
e.printStackTrace();
}
return null;
}
With this code, the logger prints the following message:
MSH|^~\&|||||20160331101349.8+0100||ADT^A08|110001|PDE-00001E6FADAD3F57|2.3
PID|||||CMS Family name 100~^CMS Name 100|||Female
But I was expecting to see the RXO segment as well. How can I achieve that?
I found that changing the message type from ADT_A28 to ORP_O10 would let me have all the fields I need, as ADT_A28 wasn't the appropriate message for the kind of information I needed. There's a complete example on how to set a great amount of segments in this type of message here. Then, I was able to print the complete message using the PipeParser:
HapiContext context = new DefaultHapiContext();
Parser parser = context.getPipeParser();
String encodedMessage = parser.encode(msg);
logger.debug("Printing EREncoded Message:");
logger.debug(encodedMessage);
I have exactly the same problem as
Autocomplete textview google places api
But the fixes suggested to him don't fix the problem with my case.
I uses the exact same code. But it does not work.
tanks for the api tip
i debuged the problem and saw i am getting a respond of zero_results
Any suggestion?
String input = "";
try {
input = "input=" + URLEncoder.encode(place[0], "utf-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
// place type to be searched
String types = "types=geocode";
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = input + "&" + types + "&" + sensor + "&" + key;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/place/autocomplete/json?input="
+ output + "?" + parameters;
You problem is you API key configuration. Make sure you are creating an API key in "Public API access" section.
You can find how to get the finger print in this post:
How to obtain Signing certificate fingerprint (SHA1) for OAuth 2.0 on Android?
Then in google console register you API key. Remember add to the final you name package declared in your Android Manifest.
finger print example:
F7:DB:FF:EB:6E:AD:C1:D6:84:05:1D:BA:F7:94:0D:E4:1F:2E:3C:8C;cl.hcarrasco.tm
Enable Google Places API:
Remember too do this:
I hope this can help you.
I desperately need your expertise in resolving a Windows-7 issue.
Scenario: I have a frame-based Help package that is set up for context-sensitive help calls. A Java application is able to control what page the Help packages opens to by passing a tag representing the desired HTML named anchor to an HTML file called pophelp. This file has javascripting that reads the passed tag from the end of the URL and maps it to the appropriate HTML file in the help package and opens it.
Issue: The above scenario works in Windows XP, but no longer in Windows 7.
Calling mechanism from Java application: rundll32 url.dll,FileProtocolHandler file://filepath/pophelp.html?tag
Summary of findings so far: It appears that url.dll no longer allows parameters to be passed with URLs in Windows 7. Parameters are being stripped. I also tried the same type of call using Desktop.getDesktop().browse() from Java, but it too seems to strip off all parameters after .html.
Sample code:
Original call that works in Windows XP --
Running command: rundll32 url.dll,FileProtocolHandler file://C:\Program Files\App System\App-Editor-8.0.1\help\pophelp.html?TAG=callsubflow
Result: ?TAG=callsubflow is not passed.
New code using Desktop.getDesktop().browse() --
public static void main(String[] args) {
String url = "file:///C:/Program Files/App System/App-Editor-8.0.1/help/pophelp.html?TAG=callsubflow";
try {
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
if (desktop.isSupported(Desktop.Action.BROWSE)) {
desktop.browse(new URI(url.replace(" ", "%20")));
}
}
} catch (IOException e) {
System.out.println("Unable to open "+url+": "+e.getMessage());
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
Result: ?TAG=callsubflow is not passed.
Any assistance would be appreciated!
I really can't tell why Windows removes parameters on local files. As mentioned in the comments this seams to be some kind of weird restrictions for security. But I once had a similar problem and I found a workaround that fits in this situation as well.
Simply create a local temporary HTML file (without parameters) that redirects you to the desired one (with parameters).Have a look at these two methods:
// creates w3c conform redirect HTML page
public String createRedirectPage(String url){
return "<!DOCTYPE HTML>" +
"<meta charset=\"UTF-8\">" +
"<meta http-equiv=\"refresh\" content=\"1; url=" + url + "\">" +
"<script>" +
"window.location.href = \"" + url + "\"" +
"</script>" +
"<title>Page Redirection</title>" +
"<!-- Note: don't tell people to `click` the link, just tell them that it is a link. -->" +
"If you are not redirected automatically, follow the <a href='" + url + "'>link</a>";
}
// creates temporary file with content of redirect HTML page
public URI createRedirectTempFile(String url) {
BufferedWriter writer = null;
File tmpFile = null;
try {
// creates temporary file
tmpFile = File.createTempFile("pophelp", ".html", null);
// deletes file when the virtual machine terminate
tmpFile.deleteOnExit();
// writes redirect page content to file
writer = new BufferedWriter(new FileWriter(tmpFile));
writer.write(createRedirectPage(url));
writer.close();
}
catch (IOException e) {
return null;
}
return tmpFile.toURI();
}
Now you can use these like this:
String url = "file:///C:/Program Files/App System/App-Editor-8.0.1/help/pophelp.html?TAG=callsubflow";
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
if (desktop.isSupported(Desktop.Action.BROWSE)) {
desktop.browse(createRedirectTempFile(url.replace(" ", "%20")));
}
}
I have a solution, not a quick (or pretty) solution, but a solution nonetheless :)
rundll32 url.dll,FileProtocolHandler does pass params when using URLs with http/s protocol (try rundll32 url.dll,FileProtocolHandler http://www.google.com?q=google), so you can setup small http server (like Jetty i guess) to serve your help files and show them using
rundll32 url.dll,FileProtocolHandler http://localhost:[helpServerIp]/help/pophelp.html?TAG=callsubflow