I want to open XHTML file which resides in resources. I tried with HTMLComponent of LWUIT. But it is opening only HTML files only. What would be correct way to open XHTML file using any LWUIT component.?
I tried with below code. Its working for HTML files with simple tags. Not working for all tags and attributes.
String htmlFileName = "index.html";
HTMLComponent htmlC = new HTMLComponent(new FileRequestHandler(HtmlScreen.this));
htmlC.setHTMLCallback(new SimpleHTMLCallback(this));
htmlC.setPage("jar://"+"/res/"+htmlFileName.trim());
FileRequestHandler.java:
class FileRequestHandler implements com.divaa.app.DocumentRequestHandler {
HtmlScreen htmlDemo;
static final String DEFAULT_RES = "images";
public FileRequestHandler(HtmlScreen htmlDemo) {
this.htmlDemo=htmlDemo;
}
public InputStream resourceRequested(DocumentInfo docInfo) {
String url=docInfo.getUrl();
// If a from was submitted on a local file, just display the parameters
if ((docInfo.getParams()!=null) && (!docInfo.getParams().equals(""))) {
String method="GET";
if (docInfo.isPostRequest()) {
method="POST";
}
String params=docInfo.getParams();
String newParams="";
if (params!=null) {
for(int i=0;i<params.length();i++) {
char c=params.charAt(i);
if (c=='&') {
newParams+=", ";
} else {
newParams+=c;
}
}
}
return getStream("<h2>Form submitted locally.</h2><b>Method:</b> "+method+"<br><br><b>Parameters:</b><br>"+newParams+"<hr>Continue to local URL","Form Results");
}
url=url.substring(6); // Cut the jar://
byte[] buf;
try {
buf = getBuffer(Display.getInstance().getResourceAsStream(getClass(), url));
if (url.endsWith(".html")) { //only set source to HTML files (not images)
htmlDemo.setSource(new String(getBuffer(new ByteArrayInputStream(buf))));
}
return new ByteArrayInputStream(buf);
} catch (Exception ex) {
System.out.println("ex.toString exception........ "+ex.toString());
ex.printStackTrace();
}
return null;
}
SimpleHTMLCallBack.java:
class SimpleHTMLCallback extends DefaultHTMLCallback {
HtmlScreen htmlDemo;
public SimpleHTMLCallback(HtmlScreen htmlDemo) {
this.htmlDemo=htmlDemo;
}
public boolean linkClicked(HTMLComponent htmlC, String url) {
return true; // Signals the HTMLComponent to prcoess this link as usual (i.e. call DocumentRequestHandler.resourceRequested)
}
public void titleUpdated(HTMLComponent htmlC, String title) {
htmlDemo.setTitle(title);
}
}
Thanks...
Related
I have a Jhipster application that generate PDF with iText library, this PDF is saved in the computer in the route that I indicated.
I would like that when generating the pdf, a dialog box will appear to download the pdf. I am indifferent if the pdf is saved in the project folder or not saved in any place.
I have seen many posts giving possible answers on this page and on the internet, but many are already obsolete and others have not worked for me.
generatePDF
public void generatePDF(User u) {
String dest = "D:/PDF/result.pdf";
String src = "D:/PDF/template.pdf";
try {
PdfDocument pdf = new PdfDocument(new PdfReader(src), new PdfWriter(dest));
PdfAcroForm form = PdfAcroForm.getAcroForm(pdf, true);
Map<String, PdfFormField> fields = form.getFormFields();
fields.get("name").setValue(u.getFirstName());
fields.get("surname").setValue(u.getLastName());
fields.get("email").setValue(u.getEmail());
pdf.close();
} catch (IOException e) {
log.debug(e.getMessage());
}
}
UserResource
#GetMapping("/print-user/{id}")
#Timed
public ResponseEntity<User> printUserTemplate(#PathVariable Long id) {
User user = userRepository.findOne(id);
userService.generatePDF(user);
return ResponseUtil.wrapOrNotFound(Optional.ofNullable(user));
}
EDIT
entity.component.ts
downloadFile() {
this.entityService.downloadFile().subscribe();
}
entity.service.ts
downloadFile(): Observable<any> {
return this.http.get(SERVER_API_URL + 'api/downloadFile');
}
Use this to download the file:
#GetMapping("/downloadFile")
public ResponseEntity<Resource> downloadFile(HttpServletRequest request) {
// Load file as Resource
Resource resource = testService.loadFileAsResource();
// Try to determine file's content type
String contentType = null;
try {
contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
} catch (IOException ex) {
log.info("Could not determine file type.");
}
// Fallback to the default content type if type could not be determined
if (contentType == null) {
contentType = "application/octet-stream";
}
return ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType)).header(
HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"").body(resource);
}
And this to generate the file:
public Resource loadFileAsResource() {
try {
Path path = Paths.get("D:\\PDF\\template.pdf");
Path filePath = path.normalize();
Resource resource = new UrlResource(filePath.toUri());
if (resource.exists()) {
return resource;
} else {
return null;
}
} catch (MalformedURLException ex) {
ex.printStackTrace();
return null;
}
}
References:
https://www.callicoder.com/spring-boot-file-upload-download-rest-api-example/
download a file from Spring boot rest service
Good day, I was trying to test on uploading an image to my database but when i'm trying to retrieve the image, nothing shows..
Here's my code for uploading the image
String m_dataForImage;
public String getDataForImage() { return m_dataForImage; }
public void setDataForImage(String value) { this.m_dataForImage = value; }
String m_ShowPhoto;
public String getShowPhoto() { return m_ShowPhoto; }
public void setShowPhoto(String value) { this.m_ShowPhoto = value; }
String m_fileName;
public String getFileName() { return m_fileName; }
public void setFileName(String value) { this.m_fileName = value; }
public void onUploadFile(javax.faces.event.ActionEvent event) {
if (event instanceof BaseActionEventUpload){
try{
ConnectionPool.getInstance();
Base.open(ConnectionPool.dataSourcePooled);
BaseActionEventUpload bae =(BaseActionEventUpload)event;
setFileName(bae.getClientFileName());
m_ShowPhoto = bae.getHexByteString();
byte[] imageByte = bae.getHexBytes();
setShowPhoto("/hex("+ValueManager.encodeHexString(imageByte)+")");//trying to convert byte to hex
photo_storage photo = new photo_storage();
photo.set("timestamp","ss");
photo.set("Primary_Key", "123");
photo.set("File_Name",getFileName());
photo.set("Image_Data",getShowPhoto());
photo.saveIt();
}catch(Throwable t){
t.printStackTrace();
Statusbar.outputAlert(t.toString());
}finally {
Base.close();
}
}
}
and for showing the image:
public void onShowImage(javax.faces.event.ActionEvent event) {
try{
ConnectionPool.getInstance();
Base.open(ConnectionPool.dataSourcePooled);
List<photo_storage> photo = photo_storage.where("Primary_Key = ?",123);
for (photo_storage so:photo){ setShowPhoto("/hex("+ValueManager.encodeHexString(so.getBytes("Image_Data"))+")");
setFileName(so.getString("File_Name"));
setDataForImage(so.getString("Image_Data"));
}catch(Throwable t){
t.printStackTrace();
Statusbar.outputAlert(t.toString());
}finally {
Base.close();
}
}
Im currently using Intellij and CaptainCasa..
Can anyone help?
Thanks in advance.
It seems that it should be
photo.set("Image_Data",imageByte);
instead of
photo.set("Image_Data",getShowPhoto());
because imageByte is where the uploaded image stored.
Hi I'm trying to make a PACS server using Java. dcm4che appears to be quite popular. But I'm unable to find any good examples about it.
As a starting point I inspected dcmqrscp and it successfully stores a DICOM image. But I cannot manage to handle a C-MOVE call. Here's my CMove handler. It finds requested the DICOM file adds a URL and other stuff, it doesn't throw any exception yet client doesn't receive any files.
private final class CMoveSCPImpl extends BasicCMoveSCP {
private final String[] qrLevels;
private final QueryRetrieveLevel rootLevel;
public CMoveSCPImpl(String sopClass, String... qrLevels) {
super(sopClass);
this.qrLevels = qrLevels;
this.rootLevel = QueryRetrieveLevel.valueOf(qrLevels[0]);
}
#Override
protected RetrieveTask calculateMatches(Association as, PresentationContext pc, final Attributes rq, Attributes keys) throws DicomServiceException {
QueryRetrieveLevel level = QueryRetrieveLevel.valueOf(keys, qrLevels);
try {
level.validateRetrieveKeys(keys, rootLevel, relational(as, rq));
} catch (Exception e) {
e.printStackTrace();
}
String moveDest = rq.getString(Tag.MoveDestination);
final Connection remote = new Connection("reciverAE",as.getSocket().getInetAddress().getHostAddress(), 11113);
if (remote == null)
throw new DicomServiceException(Status.MoveDestinationUnknown, "Move Destination: " + moveDest + " unknown");
List<T> matches = DcmQRSCP.this.calculateMatches(keys);
if (matches.isEmpty())
return null;
AAssociateRQ aarq;
Association storeas = null;
try {
aarq = makeAAssociateRQ(as.getLocalAET(), moveDest, matches);
storeas = openStoreAssociation(as, remote, aarq);
} catch (Exception e) {
e.printStackTrace();
}
BasicRetrieveTask<T> retrieveTask = null;
retrieveTask = new BasicRetrieveTask<T>(Dimse.C_MOVE_RQ, as, pc, rq, matches, storeas, new BasicCStoreSCU<T>());
retrieveTask.setSendPendingRSPInterval(getSendPendingCMoveInterval());
return retrieveTask;
}
private Association openStoreAssociation(Association as, Connection remote, AAssociateRQ aarq)
throws DicomServiceException {
try {
return as.getApplicationEntity().connect(as.getConnection(),
remote, aarq);
} catch (Exception e) {
throw new DicomServiceException(
Status.UnableToPerformSubOperations, e);
}
}
private AAssociateRQ makeAAssociateRQ(String callingAET,
String calledAET, List<T> matches) {
AAssociateRQ aarq = new AAssociateRQ();
aarq.setCalledAET(calledAET);
aarq.setCallingAET(callingAET);
for (InstanceLocator match : matches) {
if (aarq.addPresentationContextFor(match.cuid, match.tsuid)) {
if (!UID.ExplicitVRLittleEndian.equals(match.tsuid))
aarq.addPresentationContextFor(match.cuid,
UID.ExplicitVRLittleEndian);
if (!UID.ImplicitVRLittleEndian.equals(match.tsuid))
aarq.addPresentationContextFor(match.cuid,
UID.ImplicitVRLittleEndian);
}
}
return aarq;
}
private boolean relational(Association as, Attributes rq) {
String cuid = rq.getString(Tag.AffectedSOPClassUID);
ExtendedNegotiation extNeg = as.getAAssociateAC().getExtNegotiationFor(cuid);
return QueryOption.toOptions(extNeg).contains(
QueryOption.RELATIONAL);
}
}
I added the code below to send a DICOM file as a response:
String cuid = rq.getString(Tag.AffectedSOPClassUID);
String iuid = rq.getString(Tag.AffectedSOPInstanceUID);
String tsuid = pc.getTransferSyntax();
try {
DcmQRSCP.this.as=as;
File f = new File("D:\\dcmqrscpTestDCMDir\\1.2.840.113619.2.30.1.1762295590.1623.978668949.886\\1.2.840.113619.2.30.1.1762295590.1623.978668949.887\\1.2.840.113619.2.30.1.1762295590.1623.978668949.888");
FileInputStream in = new FileInputStream(f);
InputStreamDataWriter data = new InputStreamDataWriter(in);
// !1! as.cmove(cuid,1,keys,tsuid,"STORESCU");
as.cstore(cuid,iuid,1,data,tsuid,rspHandlerFactory.createDimseRSPHandler(f));
} catch (Exception e) {
e.printStackTrace();
}
Throws this exception
org.dcm4che3.net.NoRoleSelectionException: No Role Selection for SOP Class 1.2.840.10008.5.1.4.1.2.2.2 - Study Root Query/Retrieve Information Model - MOVE as SCU negotiated
You should add a role to the application instance like:
applicationEntity.addTransferCapability(
new TransferCapability(null, "*", TransferCapability.Role.SCP, "*"));
I need to insert a string at the beginning of the clipboard without losing inline formatting of text containing the same. Currently this is not happening in my code!
public String getClipboard()
{
Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
try
{
if (t != null && t.isDataFlavorSupported(DataFlavor.stringFlavor))
{
String text = (String) t.getTransferData(DataFlavor.stringFlavor);
return text;
}
}
catch (UnsupportedFlavorException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
public void setClipboard(String str)
{
StringSelection ss = new StringSelection(str);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, this);
}
public void uso()
{
String claveVM = "Text I want insert";
setClipboard(claveVM + getClipboard());
}
You can't do it with plain text (string). You need RTF or HTML.
I am developing one Application which show Gold rate and create graph for this.
I find one website which provide me this gold rate regularly.My question is how to extract this specific value from html page.
Here is link which i need to extract = http://www.todaysgoldrate.co.in/todays-gold-rate-in-pune/ and this html page have following tag and content.
<p><em>10 gram gold Rate in pune = Rs.31150.00</em></p>
Here is my code which i use for extracting but i didn't find way to extract specific content.
public class URLExtractor {
private static class HTMLPaserCallBack extends HTMLEditorKit.ParserCallback {
private Set<String> urls;
public HTMLPaserCallBack() {
urls = new LinkedHashSet<String>();
}
public Set<String> getUrls() {
return urls;
}
#Override
public void handleSimpleTag(Tag t, MutableAttributeSet a, int pos) {
handleTag(t, a, pos);
}
#Override
public void handleStartTag(Tag t, MutableAttributeSet a, int pos) {
handleTag(t, a, pos);
}
private void handleTag(Tag t, MutableAttributeSet a, int pos) {
if (t == Tag.A) {
Object href = a.getAttribute(HTML.Attribute.HREF);
if (href != null) {
String url = href.toString();
if (!urls.contains(url)) {
urls.add(url);
}
}
}
}
}
public static void main(String[] args) throws IOException {
InputStream is = null;
try {
String u = "http://www.todaysgoldrate.co.in/todays-gold-rate-in-pune/";
//Here i need to extract this content by tag wise or content wise....
Thanks in Advance.......
You can use library like Jsoup
You can get it from here --> Download Jsoup
Here is its API reference --> Jsoup API Reference
Its really very easy to parse HTML content using Jsoup.
Below is a sample code which might be helpful to you..
public class GetPTags {
public static void main(String[] args){
Document doc = Jsoup.parse(readURL("http://www.todaysgoldrate.co.intodays-gold-rate-in-pune/"));
Elements p_tags = doc.select("p");
for(Element p : p_tags)
{
System.out.println("P tag is "+p.text());
}
}
public static String readURL(String url) {
String fileContents = "";
String currentLine = "";
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(url).openStream()));
fileContents = reader.readLine();
while (currentLine != null) {
currentLine = reader.readLine();
fileContents += "\n" + currentLine;
}
reader.close();
reader = null;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage(), "Error Message", JOptionPane.OK_OPTION);
e.printStackTrace();
}
return fileContents;
}
}
http://java-source.net/open-source/crawlers
You can use any of that's apis, but don't parse the HTML with the pure JDK, because it's too painfull.