I try to use a Wicket Modal Window to set the PropertyModel of an Entity. The problem is this Entity has a FIleUploadFields that i read non work nice with Ajax. I need to use AjaxSubmitLink inside the modal and i don't be able to get this work fine.
setMultiPart(true);
setMaxSize(Bytes.megabytes(100));
fileUpload = new FileUploadField("fileUpload");
fileUpload.setOutputMarkupId(true);
fileUpload.setOutputMarkupPlaceholderTag(true);
add(fileUpload);
save_btn = new AjaxLink("save_btn") {
#Override
public void onClick(AjaxRequestTarget art) {
final FileUpload uploadedFile = fileUpload.getFileUpload();
if (uploadedFile != null && uploadedFile.getSize() > 0) {
try {
if (GestioneDocumentiDcs.isTextDocument(uploadedFile)) {
String ext = GestioneDocumentiDcs.getTextExtension(uploadedFile.getContentType());
String nomeFile = "c_" + _corso.getId() + "_m_" + materialeCorso.getId() + ext;
byte[] b = ByteStreams.toByteArray(uploadedFile.getInputStream());
gd.salvaFile(b, gd.getPathCorso(_corso) + "/" + nomeFile);
materialeCorso.setPercorso(nomeFile);
materialeCorso.setDimensione(uploadedFile.getSize());
materialeCorso.setDataUpload(LocalDate.now());
}
} catch (Exception e) {
System.out.println("ERRORE: " + Utils.StampaStackError(e));
}
}
this is my code inside the Modal
AjaxLink does not submit the form, so nothing will be transferred to the server. You need either AjaxButton or AjaxSubmitLink.
Related
so Basically I an working on this project car registration and I find difficulties in changing part of the page so I used the boarder pane to and I reached a point that I can change the middle pane but to null I believe that the problem comes from here
This is my code:
private Pane view;
#FXML
public Pane getPage(String fileName) {
try {
URL fileUrl = App.class.getResource("/org.example/" + fileName + ".fxml");
if (fileUrl == null) {
throw new java.io.FileNotFoundException("FXML file can't be found");
}
view = new FXMLLoader().load(fileUrl);
} catch (Exception e){
System.out.println("No page " + fileName + " please check FxmlLoader.");
}
return view;
}
This is where I believe the problem comes from:
URL fileUrl = App.class.getResource("/org.example/" + fileName + ".fxml");
because I get (No page addingACar.fxml please check FxmlLoader.
)
my question is I am not sure how to reach the file I assigned as a URL
I wanna to upload an image in java and copied in a directory with WebService in Symfony
i tried it with Postman and it worked but when i did it in Java, it didn't work, i don't know how to pass a file like paramatre in the Url request
Please help me to find a solution
Symfony Code:
$file = $request->files->get('nomImage');
$status = array('status' => "success","fileUploaded" => false);
// If a file was uploaded
if(!is_null($file)){
// generate a random name for the file but keep the extension
$filename = uniqid().".".$file->getClientOriginalExtension();
$path = "C:\wamp64\www\pidev\web\uploads\images";
$file->move($path,$filename); // move the file to a path
$status = array('status' => "success","fileUploaded" => true);
}
return new JsonResponse($status);
Postman Screenshot:
I sent the URL with Postman and add the image in Body with nomImage like key and the image like value and it worked
Java Code:
This code is to connect to the URL and i wanted to get the image like file in the URL like in Postman
public void ajoutProduit(File image)
{
ConnectionRequest con = new ConnectionRequest();
con.setUrl("http://localhost/PIDEV/web/app_dev.php/Api/produit/ajout?nomImage="+image);
NetworkManager.getInstance().addToQueueAndWait(con);
}
This is my form and the uploading of the image and execute the Copy of the image which it didn't work
public class AjoutProduit {
private Form fAjout = new Form("", new BoxLayout(BoxLayout.Y_AXIS));
public AjoutProduit() {
TextField nomProduit = new TextField("", "Nom du produit");
TextField descProduit = new TextField("", "Description du produit");
ComboBox<String> opProduit = new ComboBox<>(
"",
"echanger",
"donner",
"recycler",
"reparer"
);
final String[] jobPic = new String[1];
Label jobIcon = new Label();
Button image = new Button("Ajouter une image ");
final String[] image_name = {""};
final String[] pathToBeStored={""};
/////////////////////Upload Image
image.addActionListener((ActionEvent actionEvent) -> {
Display.getInstance().openGallery(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ev) {
if (ev != null && ev.getSource() != null) {
String filePath = (String) ev.getSource();
int fileNameIndex = filePath.lastIndexOf("/") + 1;
String fileName = filePath.substring(fileNameIndex);
Image img = null;
try {
img = Image.createImage(FileSystemStorage.getInstance().openInputStream(filePath));
} catch (IOException e) {
e.printStackTrace();
}
image_name[0] = System.currentTimeMillis() + ".jpg";
jobIcon.setIcon(img);
System.out.println(filePath);
System.out.println(image_name[0]);
try {
pathToBeStored[0] = FileSystemStorage.getInstance().getAppHomePath()+ image_name[0];
OutputStream os = FileSystemStorage.getInstance().openOutputStream(pathToBeStored[0]);
ImageIO.getImageIO().save(img, os, ImageIO.FORMAT_JPEG, 0.9f);
os.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}, Display.GALLERY_IMAGE);});
////////////Copied with URL Symfony
Button myButton = new Button("Valider");
myButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent actionEvent) {
ServiceProduit sp = new ServiceProduit();
ServiceEchange se = new ServiceEchange();
String path = "C:/Users/omark/.cn1/"+image_name[0];
File file = new File(path);
sp.ajoutProduit(file);
}
});
fAjout.addAll(nomProduit,descProduit,opProduit,jobIcon,myButton,image);
fAjout.show();
}
Try the x-www-url-form-encoded. If that works then use MultipartRequest to submit binary data to the server. It implicitly handles form encode submission for you. If something doesn't work use the network monitor tool in Codename One to inspect the outgoing request/response which often provide helpful information about the process.
This isn't correct:
ConnectionRequest con = new ConnectionRequest();
con.setUrl("http://localhost/PIDEV/web/app_dev.php/Api/produit/ajout?nomImage="+image);
NetworkManager.getInstance().addToQueueAndWait(con);
You're submitting a URL using the GET style argument passing. You need to submit the date of the image and not the image itself. You need to use addArgument() or addData() etc. to include the content in the request.
i resolved the problem, i modified the " Java Code ":
MultipartRequest cr = new MultipartRequest();
cr.setUrl("http://localhost/PIDEV/web/app_dev.php/Api/produit/ajout");
cr.setPost(true);
String mime = "image/png";
try {
cr.addData("file", filePath, mime);
} catch (IOException e) {
e.printStackTrace();
}
String fichernom = System.currentTimeMillis() + ".png";
cr.setFilename("file", fichernom);
InfiniteProgress prog = new InfiniteProgress();
Dialog dlg = prog.showInifiniteBlocking();
cr.setDisposeOnCompletion(dlg);
NetworkManager.getInstance().addToQueueAndWait(cr);
I have a JSF2 commandlink with an image. When the image is clicked, the server will download a PDF file. While the file is downloaded after the image link is clicked, it also causes the entire page to scroll to the top of the page. the code snippet for the link is as follows:
<p:commandLink ajax="false"
action="#{refereeAssessmentSummaryBean.stateLatestFormInPAVer(project.appId)}">
<p:graphicImage name="images/pdf.png"
title="#{msg['label.downloadpdf']}" />
</p:commandLink>
How can I use the commandlink to download the PDF file, without the webpage scrolling to the top of the page every time I click on it?
Edit: FWIW, added PDF download code. This code is called as a shared method from the backing bean. As you can see, the code will set the content type before streaming the PDF data to the client.
public void downloadEformPdf(Integer appId, Integer revNo, Integer meetingId,
String password, boolean showSaveDialog, boolean getEditedIfAvailable, boolean showVersionInfo) {
User user = WebUtils.getCurrentUser();
PermissionResult permissionResult = ServiceProxy.getPermissionService().checkViewOnlineProposalPermission(user, appId, meetingId);
if (permissionResult != PermissionResult.GRANTED) {
if (!(permissionResult == PermissionResult.REJECTED_GRBE_COI_NOT_APPROVED
|| permissionResult == PermissionResult.REJECTED_GRBE_COI_NOT_DECLARED)) {
throw new PermissionDeniedException("Permission Denied");
}
}
Application appl = ServiceProxy.getAppService().getApplication(appId);
String scheme = appl.getScheme();
boolean withNomination = false;
boolean isEditedVersion = false;
byte[] pdfData;
if (getEditedIfAvailable) {
if (revNo == null) {
Appmatching appMatching = ServiceProxy.getAppFormService().getLatestAppMatching(appId,false);
revNo = appMatching.getMainRevno();
}
Appattacheditedeform editedEntry = ServiceProxy.getAppService().getEditedProposalForApplication(appId, revNo, true);
// give GRB, ER the edited version if it exists
if (editedEntry != null) {
Filestorage storage = editedEntry.getFilestorage();
pdfData = storage.getContent();
isEditedVersion = true;
} else {
pdfData = ServiceProxy.getReportService().getHMRFReportContentByRevNo(
appId.intValue(), revNo, withNomination);
}
} else { //Get the unedited version
//Get latest rev no.
if (revNo == null) {
Appmatching appMatching = ServiceProxy.getAppFormService().getLatestAppMatching(appId,false);
revNo = appMatching.getMainRevno();
}
pdfData = ServiceProxy.getReportService().getHMRFReportContentByRevNo(
appId.intValue(), revNo, withNomination);
}
FacesContext context = FacesContext.getCurrentInstance();
ExternalContext extContext = context.getExternalContext();
extContext.responseReset();
PDDocument doc = null;
try {
if (pdfData != null) {
PDFParser parser = new PDFParser(new ByteArrayInputStream(pdfData));
parser.parse();
doc = parser.getPDDocument();
AccessPermission ap = new AccessPermission();
ap.setReadOnly();
if (password != null) {
StandardProtectionPolicy spp = new StandardProtectionPolicy(password, password, ap);
spp.setEncryptionKeyLength(128);
doc.protect(spp);
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
doc.save(bos);
doc.close();
byte[] docbuff = bos.toByteArray();
String refNo = appl.getRefNo();
String filename = null;
if (showVersionInfo) {
if (isEditedVersion) {
filename = scheme.toLowerCase() + "_eform_" + refNo + "_(v" + revNo + ")_(Edited).pdf";
} else {
filename = scheme.toLowerCase() + "_eform_" + refNo + "_(v" + revNo + ")_(PA).pdf";
}
} else {
filename = scheme.toLowerCase() + "_eform_" + refNo + ".pdf";
}
extContext.setResponseContentType("application/pdf");
extContext.setResponseContentLength(docbuff.length);
extContext.setResponseHeader("Content-Disposition", (!showSaveDialog) ? "inline"
: "attachment" + "; filename=\"" + filename + "\"");
OutputStream os = extContext.getResponseOutputStream();
os.write(docbuff);
os.close();
context.responseComplete();
} else {
extContext.setResponseContentType("text/html");
Writer writer = extContext.getResponseOutputWriter();
writer.write("Cannot retrieve PDF form for this proposal.");
writer.close();
context.responseComplete();
}
} catch (IOException e) {
logger.log(Level.ERROR, e.getMessage(), e);
} catch (COSVisitorException e) {
logger.log(Level.ERROR, e.getMessage(), e);
} catch (BadSecurityHandlerException e) {
logger.log(Level.ERROR, e.getMessage(), e);
} finally {
}
}
How do you generate the PDF?
Did you set a mimetype so that the brower will recognize that you respond with a pdf?
Did you also prevent primefaces from continuing the response after you have written your PDF file to it? (use facesContext.responseComplete(); for that)
When you use the default HTML link tag <a />, you have to set href='javascript:void(0)' to avoid the current page to scroll to the top.
Maybe there is a way with a p:commandLink to do the same thing
<p:commandLink url="javascript:void(0)" ... /> ??
Hope this will help you to resolve your problem
I think it's because you are using ajax=false.
If you are not using ajax the whole page will be reloaded.
Either remove it or change to ajax=true and give it a try.
Edit:
I was wrong. ajax=false is required when downloading files.
I have to program an Eclipse-Plugin but I have never done this before so I have some questions.
The plugin should appear in the context menu when you right click a Java project in the project explorer of Eclipse. It should open a dialog where the user can enter a file name he is looking for within the selected project and then the file gets highlighted (if there is a file with this name).
What I managed to do so far is to setup the plugin development project, the extension point for the plugin and the dialog.
But now I don't know how to get access to the selected project. Can you tell me how this is done or a link to the corresponding API?
Thanks in advance :)
I assume you have a Handler class for the right-click action in your plugin. The Handler extends the AbstractHandler and overrides the method execute(..).
Then you can do something like this:
public class YourHandler extends AbstractHandler {
private ExecutionEvent event;
#Override
public Object execute(ExecutionEvent event) throws ExecutionException {
// First get the tree of the right-clicked project.
ISelection sel = HandlerUtil.getActiveMenuSelection(event);
IResource resource = null;
IProject project = null;
try {
IStructuredSelection selection = (IStructuredSelection) sel;
// Get the first element of the tree (return type Object).
Object firstElement = selection.getFirstElement();
// Get the IResource and from this the IProject of the selection.
if (firstElement instanceof IAdaptable) {
IResource resource = (IResource) (((IAdaptable) firstElement)
.getAdapter(IResource.class));
project = res.getProject();
}
} catch (ClassCastException e) {
// Do nothing.
}
// Then you can do something with the project.
return project;
}
Look also at the Eclipse API for IProject for what you can do: http://help.eclipse.org/kepler/topic/org.eclipse.platform.doc.isv/reference/api/org/eclipse/core/resources/IProject.html
For example getting a file from name:
IFile getFile(String name)
Returns a handle to the file with the given name in this project.
Hope this helps.
By the way: if you need some nice tutorials about developing Eclipse plugins, I can recommend this website http://www.vogella.com/eclipse.html
Cheers.
I write some util class to do the job. Hope it help you
public class SelectionUtil {
private IWorkbenchWindow window;
private IWorkbenchPage activePage;
private TreeSelection treeSelection;
private TreePath[] treePaths;
HashMap<Object, Object> selectData;
private IProject theProject;
private IResource theResource;
private IFile theFile;
private IPackageFragment theFragment;
private String workspaceName;
private String projectName;
private String fileName;
private String fileNameFile;
private String fragmentName;
private TreePath treePath;
public SelectionUtil(ExecutionEvent event) {
this.window = HandlerUtil.getActiveWorkbenchWindow(event);
// Get the active WorkbenchPage
this.activePage = this.window.getActivePage();
// Get the Selection from the active WorkbenchPage page
ISelection selection = this.activePage.getSelection();
if (selection instanceof ITreeSelection) {
this.treeSelection = (TreeSelection) selection;
this.treePaths = treeSelection.getPaths();
this.treePath = treePaths[0];
selectData = new ProjectSelectionUtil()
.populatePojectData(treePath);
setData();
} else {
String selectionClass = selection.getClass().getSimpleName();
MessageDialog
.openError(
this.window.getShell(),
"Unexpected Selection Class",
String.format(
"Expected a TreeSelection but got a %s instead.\nProcessing Terminated.",
selectionClass));
}
}
public void setData() {
this.theProject = (IProject) selectData.get("Project");
this.theResource = (IResource) selectData.get("Resource");
this.theFragment = (IPackageFragment) selectData.get("Fragment");
this.workspaceName = this.theResource.getWorkspace().getRoot()
.getLocation().toOSString();
this.projectName = this.theProject.getName();
if (this.theFragment != null)
this.fragmentName = this.theFragment.getElementName();
try {
if (!this.theResource.getName().isEmpty()
&& this.theResource.getName().length() > 5)
this.fileName = this.theResource.getName().substring(0,
this.theResource.getName().length() - 5);
} catch (NullPointerException e) {
System.out
.println(" GactusWindowSelectionUtil SetData NullPointerException"
+ e.getMessage() + e.getLocalizedMessage());
} catch (StringIndexOutOfBoundsException e) {
System.out
.println(" StringIndexOutOfBoundsException SetData NullPointerException"
+ e.getMessage() + e.getLocalizedMessage());
}
}
public String toString() {
ProjectInformation myProject = new ProjectInformation(theProject);
return "Segment Count " + treePath.getSegmentCount() + " Iproject"
+ myProject.toString();
}
}
Unix / Linux support auto-complete of files and directories when pressing "tab".
I need to create this ability in my windows application. I have a text field for user input of file name, which I want to respond to a "tab" press like it will do when we're in a unix console:
If there is one option - Auto-complete.
Some options - show a list of the options.
No options - nada.
For my SSH connection to my unix machine I use the ch.ethz.ssh API.
Is there a way to do so?
First you want to have a text field without focus cycling, and tab suppression:
jTextField1.setFocusCycleRoot(true);
jTextField1.setFocusTraversalKeysEnabled(false);
Then a data model for the files (here local directory, but SSH is likewise):
private File dir = new File("C:/Work");
private String typedPrefix = null;
private List<String> filesWithPrefix = new ArrayList<>();
Then a key pressed handling for the TAB:
Consume the event.
Get the prefix upto the caret for searching file names.
If you merely need to restrict already found file names, so do, otherwise physical search them.
Look for the longest common prefix in the file names. Display that.
private void jTextField1KeyPressed(java.awt.event.KeyEvent evt) {
System.out.println("KeyPressed " + evt);
if (evt.getKeyCode() == KeyEvent.VK_TAB) {
evt.consume();
int caretPos = jTextField1.getCaretPosition();
try {
final String newPrefix = jTextField1.getText(0, caretPos);
System.out.println("newPrefix: " + newPrefix);
if (!newPrefix.isEmpty()) {
if (typedPrefix == null || !newPrefix.startsWith(typedPrefix)) {
// Must physically reload possible values:
String[] fileNames = dir.list(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return name.startsWith(newPrefix);
}
});
filesWithPrefix.clear();
Collections.addAll(filesWithPrefix, fileNames);
typedPrefix = newPrefix;
} else {
// Can reduce prior selection:
for (ListIterator<String> it = filesWithPrefix.listIterator(); it.hasNext(); ) {
String fileName = it.next();
if (!fileName.startsWith(newPrefix)) {
it.remove();
}
}
typedPrefix = newPrefix;
}
System.out.println("filesWithPrefix: " +filesWithPrefix);
if (!filesWithPrefix.isEmpty()) {
// Find longest common prefix:
String longestCommonPrefix = null;
for (String fileName : filesWithPrefix) {
if (longestCommonPrefix == null) {
longestCommonPrefix = fileName;
} else {
while (!fileName.startsWith(longestCommonPrefix)) {
longestCommonPrefix = longestCommonPrefix.substring(0, longestCommonPrefix.length() - 1);
}
}
}
if (longestCommonPrefix.length() > typedPrefix.length()) {
jTextField1.setText(longestCommonPrefix);
jTextField1.setCaretPosition(longestCommonPrefix.length());
typedPrefix = longestCommonPrefix;
}
if (filesWithPrefix.size() > 1) {
// Show popup:
;;;
} else if (filesWithPrefix.size() == 1) {
// File selected:
System.beep();
}
}
}
} catch (BadLocationException ex) {
Logger.getLogger(TabsJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
What is missing is the display of the ambiguous file names. Popup menu would be nice, wouldn't it?
Popup:
// Show popup:
JPopupMenu popup = new JPopupMenu();
for (String fileName : filesWithPrefix) {
popup.add(new AbstractAction(fileName) {
#Override
public void actionPerformed(ActionEvent e) {
jTextField1.setText(e.getActionCommand());
}
});
}
Point pt = jTextField1.getCaret().getMagicCaretPosition();
popup.show(jTextField1, pt.x, pt.y + 5);