On the Wicket page I have an image (AbstractDefaultAjaxBehavior.INDICATOR) which is shown on submit and then i start a AjaxSelfUpdatingTimerBehavior to monitor a file.
Now I also have a DownloadLink to download the same file. However after download the image which I mentioned above (which is rotating) stops rotating. Is there a solution to this issue? I am new to wicket. Please suggest.
public LoggingPage() {
Form<Void> form;
this.add(form = new Form<Void>("resourceForm") {
private static final long serialVersionUID = 1L;
#Override
protected void onSubmit() {
submit();
}
});
add(new DownloadLink("downloadButton", new AbstractReadOnlyModel<File>()
{
private static final long serialVersionUID = 1L;
#Override
public File getObject()
{
File file;
try
{
file = new File(LoggingPage.this.fileDetail.getLocation());
}
catch (Exception e)
{
throw new RuntimeException(e);
}
return file;
}
}));
}//cons ends
private void submit() {
if (this.serverDetail != null && this.fileType != null && this.fileDetail != null)
{
if (this.fileViewer != null)
{
this.repeater.removeAll();
}
File file = new File(this.fileDetail.getLocation());
file = new File("C:/ueshome/logs/safe.log");
this.fileViewer = new FileViewer(file);
this.fileViewer.startTailing();
log.debug("load of allLog: " + this.fileViewer.getOldLog());
buildItem(this.fileViewer.getOldLog().getLog().toString());
this.container.add(new AjaxSelfUpdatingTimerBehavior(Duration.seconds(1))
{
#Override
protected void onPostProcessTarget(final AjaxRequestTarget target)
{
target.appendJavascript("$('#container').scrollTop( 999999999 )");
log.debug("onPostProcessTarget: " + LoggingPage.this.fileViewer.hashCode() + "at: " + System.currentTimeMillis());
final FileAttributes fileAttributes = LoggingPage.this.fileViewer.getNewLog();
String newLog = fileAttributes.getLog().toString();
log.debug("nextlog inside load()");
if (newLog != null && newLog.trim().length() > 0)
{
log.debug("~~~~~~~~~~~~~~~~~~~~````*****:" + newLog);
log.debug("String.valueOf(fileAttributes.getSize()))~~~~~~~~~~~~~~~~~~~~````*****:" + String.valueOf(fileAttributes.getSize()));
log.debug("String.valueOf(fileAttributes.getLastModified()): " + String.valueOf(fileAttributes.getLastModified()));
if (LoggingPage.this.repeater.getSizeInBytes() >= logSize)
{
LoggingPage.this.repeater.removeAll();
}
Component item = buildItem(newLog);
target.prependJavascript(String.format(
"var item=document.createElement('%s');item.id='%s';Wicket.$('%s').appendChild(item);",
"div", item.getMarkupId(), LoggingPage.this.container.getMarkupId()));
// LoggingPage.this.imgContainer.setVisible(true);
// target.addComponent(LoggingPage.this.imgContainer);
target.addComponent(item);
target.appendJavascript("$('#fileAttributesContainer').show(); ");
target.appendJavascript("$('#container').scrollTop( 999999999 )");
target.appendJavascript("$('#imageContainer').show(); ");
}
else
{
target.appendJavascript("$('#fileAttributesContainer').show(); ");
target.appendJavascript("$('#container').scrollTop( 999999999 )");
target.appendJavascript("$('#imageContainer').show(); ");
}
target.appendJavascript("alert('You are in Ajax Self')");
}
First I have to admit that I have no idea right now what could be wrong with your code. It looks rather different than how I would solve your task.
As I understand you want to have a image (an animated gif) that is animated after the user hits the submit button, right. And it should stop the animation after a certain condition is met (file generation finished etc.). Also you want to have a download link for your file.
What I would do is
use a animated gif that will be shown
add a AjaxSelfUpdatingTimerBehavior that checks your file and if a certain condition is met it changes the image (maybe by changing the image itself, sets the visibility of the image or by changing some css attribute for the image container)
for the file download I would use an ajax button or if nothing should be changed on your side a normal link that delivers an resource stream for your file
Hope this helps a little bit.
Related
I have added my Android side code:
I know that I need to use a platform channel to pass data,I am unable to figure out:
import io.flutter.embedding.android.FlutterActivity;
public class MainActivity extends AppCompatActivity {
private Button Btn;
// Intent defaultFlutter=FlutterActivity.createDefaultIntent(activity);
String path;
private Button bt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Btn = findViewById(R.id.btn);
isStoragePermissionGranted();
Btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
path=takeScreenshot();
// activity.startActivity(defaultFlutter);
}
});
//write flutter xode here
//FlutterActivity.createDefaultIntent(this);
}
private String takeScreenshot() {
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
try {
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";
// create bitmap screen capture
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
File imageFile = new File(mPath);
Log.d("path",mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
return mPath;
///openScreenshot(imageFile);
} catch (Throwable e) {
// Several error may come out with file handling or DOM
e.printStackTrace();
return "Error";
}
}
public boolean isStoragePermissionGranted() {
String TAG = "Storage Permission";
if (Build.VERSION.SDK_INT >= 23) {
if (this.checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.v(TAG, "Permission is granted");
return true;
} else {
Log.v(TAG, "Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon installation
Log.v(TAG,"Permission is granted");
return true;
}
}
}
I will receive a file from the android side, upon receiving I need to display it in a flutter. I also need to use cached engine for transferring data as normally it would cause a delay
You can use the cached engine, this will help me cover up for the delay.
Then you can add a invoke method onpressed that you can send method name and the data you want to pass.
On flutter side,you can create a platform and invoke method through which you can receive requirements and further process it,
I have a PDF that has image fields inside it. I am not using a PDPushButton with javascript to attach pictures because if I do that the button's top layer gets replaced with the picture that I am attaching which is not what I want. So I am explicitly using a ImageField that is available in Adobe LiveCycle Designer. I am able to extract the files attached on it using PDFBox but I am not able to find any way of seeing which image fields have files attached to them and which ones do not. For example if I have the following code here:
ImageField[1], ImageField[2], ImageField[3]
I want to see something like
ImageField[1]: null,
ImageField[2]: true,
ImageField[3]: trueenter code here
etc assuming ImageField[2] and ImageField[3] has images attached to them.
Below is the code that I was working on:
I have a constant:
Then I am looping through the whole set of image field names and see which field is a instance of PDXObjectImage and then if it is a PDXObjectImage then I check if that object.getRGBImage().getHeight() > 0 assuming that only files uploaded have a height > 1 which means a file has been attached.
private static String[] IMAGE_FIELD_ROW = {"ImageField1[0]","ImageField2[0]",....} => 100 rows of string values such as "ImageField3[0]", "ImageField4[0]", ...etc.
for(int i = 0; i<IMAGE_FIELD_ROW.length; i++)
{
if(field.getPartialName().equals(IMAGE_FIELD_ROW[i]))
{
Map<String, PDAppearanceStream> stateAppearances = field.getWidget().getAppearance().getNormalAppearance();
for (Map.Entry<String, PDAppearanceStream> entry: stateAppearances.entrySet())
{
PDAppearanceStream appearance = entry.getValue();
PDResources resources = appearance.getResources();
if (resources == null)
return;
Map<String, PDXObject> xObjects = resources.getXObjects();
if (xObjects == null)
return;
for (Map.Entry<String, PDXObject> entryNew : xObjects.entrySet())
{
PDXObject xObject = entryNew.getValue();
System.out.println("printing out the xobject name: "+ entryNew.getKey());
if (xObject instanceof PDXObjectForm)
{
PDXObjectForm form = (PDXObjectForm)xObject;
PDResources resources2 = form.getResources();
if (resources2 == null)
return;
Map<String, PDXObject> xObjects2 = resources2.getXObjects();
if (xObjects2 == null)
{
return;
}
for (Map.Entry<String, PDXObject> entry2 : xObjects2.entrySet())
{
PDXObject xObject2 = entry2.getValue();
if (xObject2 instanceof PDXObjectForm)
{
continue;
}
else if (xObject2 instanceof PDXObjectImage)
{
PDXObjectImage ig = (PDXObjectImage)xObject2;
if(ig.getRGBImage().getHeight() > 0)
{
images.put(field.getPartialName(), "true");
}
else
{
images.put(field.getPartialName(), null);
}
//imageIds.add(imageId);
}
else
{
continue;
}
}
}
}
}
}
}
Images is a map variable: Mapimages.
Also my code file is large and so I didn't want to overwhelm anybody by pasting the whole file. Below is the dropbox link for the sample PDF file that I am using:
https://www.dropbox.com/s/g2wqm8ipsp8t8l5/GSA%20500%20PDF_v4.pdf?dl=0
Your PDF is a hybrid AcroForm/XFA document; where the XFA part uses fields with an imageEdit user interface, the AcroForm part uses pushbutton fields.
Thus, it allows you two ways to check whether an image field is set: Either you look at the AcroForm buttons and inspect their appearances for images, or you retrieve the XFA XML and inspect that.
Checking the XFA XML
Initially I did overlook the PDFBox version in the question title and implemented this for PDFBox 2.0.x. As it turns out, though, the identical code can be used for PDFBox 1.8.11, merely some additional exceptions may be thrown and, therefore, must be considered.
The latter option, inspecting the XFA XML, actually is a bit easier for the document at hand. Simply search the XML for an element with the name in question and check its contents. As an additional sanity check one can verify the content type attribute of the element:
boolean isFieldFilledXfa(Document xfaDom, String fieldName) {
NodeList fieldElements = xfaDom.getElementsByTagName(fieldName);
for (int i = 0; i < fieldElements.getLength(); i++) {
Node node = fieldElements.item(i);
if (node instanceof Element) {
Element element = (Element) node;
if (element.getAttribute("xfa:contentType").startsWith("image/")) {
return element.getTextContent().length() > 0;
}
}
}
return false;
}
(CheckImageFieldFilled helper method)
With it you can check your document:
PDDocument document = PDDocument.load(SOURCE);
PDAcroForm acroForm = document.getDocumentCatalog().getAcroForm();
Document xfaDom = acroForm.getXFA().getDocument();
System.out.println("Filled image fields from ImageField1..ImageField105:");
for (int i=1; i < 106; i++) {
if (isFieldFilledXfa(xfaDom, "ImageField" + i)) {
System.out.printf("* ImageField%d\n", i);
}
}
(CheckImageFieldFilled test method testCheckXfaGsa500Pdf_v4)
The output:
Filled image fields from ImageField1..ImageField105:
* ImageField1
* ImageField3
* ImageField6
Checking the AcroForm Appearances
The implementation here only works as is for PDFBox 2.0.x. The structure of the content stream parser classes has been considerably overhauled in 2.0.0, making a back-port of this code to 1.8.x a bit tedious.
To check whether the push button appearance actually shows an image (and not only has an image in its resources), one can use a simple PDFGraphicsStreamEngine subclass like this:
public class WidgetImageChecker extends PDFGraphicsStreamEngine
{
public WidgetImageChecker(PDAnnotationWidget widget) {
super(widget.getPage());
this.widget = widget;
}
public boolean hasImages() throws IOException {
count = 0;
PDAppearanceStream normalAppearance = widget.getNormalAppearanceStream();
processChildStream(normalAppearance, widget.getPage());
return count != 0;
}
#Override
public void drawImage(PDImage pdImage) throws IOException {
count++;
}
#Override
public void appendRectangle(Point2D p0, Point2D p1, Point2D p2, Point2D p3) throws IOException { }
#Override
public void clip(int windingRule) throws IOException { }
#Override
public void moveTo(float x, float y) throws IOException { }
#Override
public void lineTo(float x, float y) throws IOException { }
#Override
public void curveTo(float x1, float y1, float x2, float y2, float x3, float y3) throws IOException { }
#Override
public Point2D getCurrentPoint() throws IOException { return null; }
#Override
public void closePath() throws IOException { }
#Override
public void endPath() throws IOException { }
#Override
public void strokePath() throws IOException { }
#Override
public void fillPath(int windingRule) throws IOException { }
#Override
public void fillAndStrokePath(int windingRule) throws IOException { }
#Override
public void shadingFill(COSName shadingName) throws IOException { }
final PDAnnotationWidget widget;
int count = 0;
}
(CheckImageFieldFilled helper class)
With it you can create a check method like this:
boolean isFieldFilledAcroForm(PDAcroForm acroForm, String fieldName) throws IOException {
for (PDField field : acroForm.getFieldTree()) {
if (field instanceof PDPushButton && fieldName.equals(field.getPartialName())) {
for (final PDAnnotationWidget widget : field.getWidgets()) {
WidgetImageChecker checker = new WidgetImageChecker(widget);
if (checker.hasImages())
return true;
}
}
}
return false;
}
(CheckImageFieldFilled helper method)
and use it like this:
PDDocument document = PDDocument.load(SOURCE);
PDAcroForm acroForm = document.getDocumentCatalog().getAcroForm();
System.out.println("Filled image fields (AcroForm) from ImageField1..ImageField105:");
for (int i=1; i < 106; i++) {
if (isFieldFilledAcroForm(acroForm, "ImageField" + i + "[0]")) {
System.out.printf("* ImageField%d\n", i);
}
}
(CheckImageFieldFilled test testCheckAcroFormGsa500Pdf_v4)
The output, just like above:
Filled image fields (AcroForm) from ImageField1..ImageField105:
* ImageField1
* ImageField3
* ImageField6
I'm using JavaFX's Drag and Drop system in my application, and it has been working well so far.
Now I want to support drag and drop to outside applications, eg. dragging files from my application to the explorer. How would I achieve that?
I've achieved what you described by using:
Vector<File> files = new Vector<File>();
private ClipboardContent filesToCopyClipboard = new ClipboardContent();
...
final ObjectWithAReturnablePathField draggableObj = new ObjectWithAReturnablePathField();
...
draggableObj.setOnDragDetected(new EventHandler<MouseEvent>()
{
#Override
public void handle(MouseEvent me)
{
Dragboard db = draggableObj.startDragAndDrop(TransferMode.ANY);
try
{
File f = new File(new URI(draggableObj.getFilePath()));
files.add(f);
filesToCopyClipboard.putFiles(files);
}
catch (URISyntaxException e)
{
e.printStackTrace();
}
db.setContent(filesToCopyClipboard);
me.consume();
}
});
draggableObj.setOnDragDone(new EventHandler<DragEvent>()
{
#Override
public void handle(DragEvent me)
{
me.consume();
}
});
Which means:
It's possible to achieve file transference between JavaFX 2 and a native application by filling a ClipboardContent with a list using the TransferMode.ANY on the setOnDragDetected method of any Draggable Object (Any Node) which can return a Path for a file. In my case, I've created a class called Thumb extending ImageView and (among others things) I made a method called getFilePath() which returns the Path from the Image used to initialize the ImageView(). I'm sorry BTW for the poor example and the poor english, but I'm running out of time to give a more detailed answer as of now. I hope it helps. Cheers
Here is a sample source for an action listener on an ImageView image extraction to OS' explorer (With a custom process for jpg image to remove alpha-channel to display it correctly):
inputImageView.setOnDragDetected(new EventHandler <MouseEvent>() {
#Override
public void handle(MouseEvent event) {
// for paste as file, e.g. in Windows Explorer
try {
Clipboard clipboard Clipboard.getSystemClipboard();
Dragboard db = inputImageView.startDragAndDrop(TransferMode.ANY);
ClipboardContent content = new ClipboardContent();
Image sourceImage = inputImageView.getImage();
ImageInfo imageInfo = (ImageInfo) inputImageView.getUserData();
String name = FilenameUtils.getBaseName(imageInfo.getName());
String ext = FilenameUtils.getExtension(imageInfo.getName());
///Avoid get "prefix lenght too short" error when file name lenght <= 3
if (name.length() < 4){
name = name+Long.toHexString(Double.doubleToLongBits(Math.random()));;
}
File temp = File.createTempFile(name, "."+ext);
if (ext.contentEquals("jpg")|| ext.contentEquals("jpeg")){
BufferedImage image = SwingFXUtils.fromFXImage(sourceImage, null); // Get buffered image.
BufferedImage imageRGB = new BufferedImage(image.getWidth(),image.getHeight(),
BufferedImage.OPAQUE);
Graphics2D graphics = imageRGB.createGraphics();
graphics.drawImage(image, 0, 0, null);
ImageIO.write(imageRGB, ext, temp);
graphics.dispose();
ImageIO.write(imageRGB,
ext, temp);
}else{
ImageIO.write(SwingFXUtils.fromFXImage(sourceImage, null),
ext, temp);
}
content.putFiles(java.util.Collections.singletonList(temp));
db.setContent(content);
clipboard.setContent(content);
event.consume();
temp.deleteOnExit();
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
});
With the help of use of an Object that is passed to the imageView's setUserData method, it helps me to retrieve database id and pic name:
public class ImageInfo {
private String imageInfo;
private int inputId;
#Override
public String toString() {
return imageInfo;
}
public ImageInfo(String imageInfo, int inputId) {
this.imageInfo = imageInfo;
this.inputId = inputId;
}
public String getName() {
return imageInfo;
}
public void setName(String imageInfo) {
this.imageInfo = imageInfo;
}
public int getIndex() {
return inputId;
}
public void setIndex(int areaindex) {
this.inputId = inputId;
}
}
I hope it will help somenone at an expected time :-)
Regards
This problems occur when I click on Login button on the android emulator, it appear on Username textbox.
Kindly help me to resolve it...your help is appreciate ~
java.lang.IllegalArgumentException: Illegal character in scheme at index 0:
android.os.NetworkOnMainThreadException
--
Update 7.9.2011
I post my code over here:
http://pastebin.com/EX0ArwaE --> Login.java
http://pastebin.com/WgGctGHN --> CustomHttpClient.java
So first the Android stuff: You're getting this NetworkOnMainThreadException because you're trying to make a HTTP request on your main application thread which is the UI thread. You shouldn't do any blocking operations in this thread. Use an AsyncTask instead.
I'm not quite sure what's causing the IllegalArgumentException but I guess it's this line:
response = CustomHttpClient.executeHttpPost("http://127.0.0.1/es/check.php", postParameters);
You have probably changed the URL (localhost usually doesn't make sense on a phone). The scheme part is the http. Maybe you have something like " http://..." (note the leading space character) in the original code?
Short note on the PHP:
$sql = 'SELECT * from people WHERE username = "' .$_POST['un'] . '" and password = "' .md5($_POST['pw']) . '"';
That's what you call an SQL injection.
Update: Here's some example. Didn't test it, hopefully it works.
public class LoginLayout extends Activity {
EditText un,pw;
TextView error;
Button ok;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
un=(EditText)findViewById(R.id.et_un);
pw=(EditText)findViewById(R.id.et_pw);
ok=(Button)findViewById(R.id.btn_login);
error=(TextView)findViewById(R.id.tv_error);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new LoginTask().execute(un.getText().toString(), pw.getText().toString());
}
});
}
private class LoginTask extends AsyncTask<String, Void, Object> {
protected Object doInBackground(String... params) {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", params[0]));
postParameters.add(new BasicNameValuePair("password", params[1]));
String response = null;
try {
response = CustomHttpClient.executeHttpPost("http://127.0.0.1/es/check.php", postParameters);
String res = response.toString();
res = res.replaceAll("\\s+","");
return res;
} catch (Exception e) {
return e;
}
}
protected void onPostExecute(Object result) {
if (result instanceof String) {
if (result.equals("1")) {
error.setText("Correct Username or Password");
} else {
error.setText("Sorry!! Wrong Username or Password Entered");
}
} else if (result instanceof Exception) {
un.setText(result.toString());
}
}
}
}
Here is our ExcelExport action that inherits from ActionResult:
public class ExcelResult<Model> : ActionResult
{
string _fileName;
string _viewPath;
Model _model;
ControllerContext _context;
public ExcelResult(ControllerContext context, string viewPath, string fileName, Model model)
{
this._context = context;
this._fileName = fileName;
this._viewPath = viewPath;
this._model = model;
}
protected string RenderViewToString()
{
if (!_viewPath.EndsWith(".aspx"))
{
return _viewPath;
}
using (var writer = new StringWriter())
{
var view = new WebFormView(_context, _viewPath);
var vdd = new ViewDataDictionary<Model>(_model);
var viewCxt = new ViewContext(_context, view, vdd, new TempDataDictionary(), writer);
viewCxt.View.Render(viewCxt, writer);
return writer.ToString();
}
}
void WriteFile(string content)
{
HttpContext context = HttpContext.Current;
context.Response.Clear();
context.Response.AddHeader("content-disposition", "attachment;filename=\"" + _fileName + "\"");
context.Response.Charset = "";
//context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.ContentType = "application/ms-excel";
context.Response.Write(RemoveImages(content));
context.Response.End();
}
public override void ExecuteResult(ControllerContext context)
{
string content = this.RenderViewToString();
this.WriteFile(content);
}
public static string RemoveImages(string html)
{
StringBuilder retval = new StringBuilder();
using (StringReader reader = new StringReader(html))
{
string line = string.Empty;
do
{
line = reader.ReadLine();
if (line != null)
{
if (!line.StartsWith("<img"))
{
retval.Append(line);
}
}
} while (line != null);
}
return retval.ToString();
}
}
The export works fine, but in IE only (works in FF), if you export, and choose to open the file instead of save it, and then click export again right away, it tries to open another file with the same name and therefore Excel won't let you until you close your working document.
In FF however, the name just adds an integer that increments by 1 each time you click export.
What do I have to do to achieve the same functionality in IE?
I faced the same problem and out of the box you cant do anything because that's the way IE and Excel handle this. You are also not able to identify that a file of the same name is already opened. But you can use either JavaScript or the user session to identify that the user has already loaded the export within a timespan and and change the file name on server side for this download. That worked for me after 2 days of searching and mailing.