I write discord bot with using JDA and i have one important question how to download attachments or work with them? Because my IntelliJ say "Deprecated API usage" for method like attachment.downloadToFile("name.png);
So now we shouldn't download users files send in message? Or how we should do it in good way? I search a lot of wiki from JDA and different posts, but everywhere i didn't see, a new option to handle this download files, becasue all methods to download, are "Deprecated API" even method like "attachment.retrieveInputStream().join()" retrieveInputStream its too not good way :(
Search a lot on wiki/others pages for more information but nothing found :(
The deprecation notice says this:
Deprecated.
Replaced by getProxy(), see FileProxy.downloadToFile(File)
This means you should use attachment.getProxy().downloadToFile(File) instead.
Example:
attachment.getProxy().downloadToFile(new File("myimage.png")).thenAccept(file -> {
System.out.println("Written to file " + file.getAbsolutePath() + ".");
});
Or using NIO instead:
attachment.getProxy().downloadToPath().thenAccept(path -> {
System.out.println("Written to file " + path + ". Total size: " + Files.size(path));
});
In GWT we need to use # in a URL to navigate from one page to another i.e for creating history for eg. www.abc.com/#questions/10245857 but due to which I am facing a problem in sharing the url. Google scrappers are reading the url only before # i.e. www.abc.com.
Now I want to remove # from my url and want to keep it straight as www.abc.com/question/10245857.
I am unable to do so. How can I do this?
When user navigates the app I use the hash urls and History object (as
to not reload the pages). However sometimes it's nice/needed to have a
pretty URL (e.g. for sharing, showing in public, etc..) so I would like to know how to
provide the pretty URL of the same page.
Note:
We have to do this to make our webpages url crawlable and to link the website with outside world.
There are 3 issues here, and each can be solved:
The URL should appear prettier to the user
Going directly to the pretty URL should work.
WebCrawlers should be able to get the content
These may all seem like the same issue, but they are quite distinct in this context.
Display Pretty URLs
Can be done with a small javascript file which uses HTML5 state methods. You can see a simple demo here, with source here. This makes all changes to "#" appear without the "#" (on modern browsers).
Relevent code from fiddle:
var stateObj = {locationHash: hash};
history.replaceState(stateObj, "Page Title", baseURL + hash.substring(1));
Repsond to Pretty URLs
This is relatively simple, as long as you have a listener in GWT to load based on the "#" at page load already. You can just throw up a simple re-direct servlet which reinserts the "#" mark where it belongs when requests come in.
For a servlet, listening for the pretty URL:
if(request.getPathInfo()!=null && request.getPathInfo().length()>1){
response.sendRedirect("#" + request.getPathInfo());
return;
}
Alternatively, you can serve up your GWT app directly from this servlet, and initialize it with parameters from the URL, but there's a bit of relative-path bookkeeping to be aware of.
WebCrawlers
This is the trickiest one. Basically you can't get around having static(ish) pages here. That's not too hard if there are a finite set of simple states that you're indexing. One simple scheme is to have a separate servlet which returns the raw content you normally fetch with GWT, in minimal formatted HTML. This servlet can have a different URL pattern like "/indexing/". These wouldn't be meant for humans, just for the webcrawlers. You can attach a simple javascript in the <head> to redirect users to the pretty url once the page loads.
Here's an example for the doGet method of such a servlet:
response.setContentType("text/html;charset=UTF-8");
response.setStatus(200);
pw = response.getWriter();
pw.println("<html>");
pw.println("<head><script>");
pw.println("window.location.href='http://www.example.com/#"
+ request.getPathInfo() + "';");
pw.println("</script></head>");
pw.println("<body>");
pw.println(getRawPageContent(request.getPathInfo()));
pw.println("</body>");
pw.println("</html>");
pw.flush();
pw.close();
return;
You should then just have some links to these indexing pages hidden somewhere on your main app URL (or behind a link on your main app URL).
I am using Selenium2/WebDriver to test my web applications. All the tests are written in Java and run with Maven.
While opening a page with webdriver I'd like to capture all the requests made by page (images, js and css files, etc). I use this data mainly for two reasons
checking for 404 (and other errors) in calls
checking if analytics code is working (checking if it's sending proper requests)
Depending on the project I use either Firebug with Netexport or Browsermob proxy. In both cases I can easily obtain a HAR (Html ARchive) file, parse it and extract the data I want.
Here's the problem:
I am not happy with neither of these solutions. I have especially problems with getting HAR file when a page contains video that is being loaded too long. I am looking for something more stable.
So, the questions are:
Is there any alternative to Browsermob? I know about FiddlerCore but it's a .NET library and my tests are written in Java. I've also heard about Ajax DynaTrace and I know that there is some way to integrate it with Selenium but the documentation I found was for Selenium-RC not WebDriver.
Is there any way to integrate DynaTrace with WebDriver or use FiddlerCore with Java?
Is there any other way to achieve the goals I mentioned? I am looking for a proxy that I can easily control from my code. Exporting data to HAR would be a great plus.
I found a google groups discussion on the topic. These links look like promising alternative to Browsermob:
A Selenium CaptureNetworkTraffic Example in Java
HOWTO: Collect WebDriver HTTP Request and Response Headers
Automating the Capture of Web Timings with Selenium 2
There is an alternative with firefox ver 42+, there is addon called Firefox HarExport
File harExportApi = new File(System.getProperty("user.dir")
+ "/src/main/resources/firebug/harexporttrigger-0.5.0-beta.7.xpi");
netExportProfile.addExtension(harExportApi);
netExportProfile.setPreference("extensions.netmonitor.har.enableAutomation", true);
netExportProfile.setPreference("extensions.netmonitor.har.contentAPIToken", "test");
netExportProfile.setPreference("extensions.netmonitor.har.autoConnect", true);
cap.setCapability(FirefoxDriver.PROFILE, netExportProfile);
and running following script will give us all the request responses
String getHarLogScript = "var options = {\n" +
" token: \"test\",\n" +
" getData: true,\n" +
" title: \"my custom title\",\n" +
" jsonp: false,\n" +
" };\n" +
"\n" +
" HAR.triggerExport(options).then(result => {\n" +
" var har = JSON.parse(result.data);\n" +
"\n" +
" // Use performance.timing to provide onContentLoad\n" +
" +
" +
" var t = performance.timing;\n" +
" var pageTimings = har.log.pages[0].pageTimings;\n" +
" pageTimings.onContentLoad = t.domContentLoadedEventStart - t.navigationStart;\n" +
" pageTimings.onLoad = t.loadEventStart - t.navigationStart;\n" +
"\n" +
" window.HarEntries=har.log.entries\n" +
"\n" +
" console.log(\"HAR log (\" + result.data.length + \") \", har.log);\n" +
" }, err => {\n" +
" console.error(err);\n" +
" });"
LOG.info("Loading HAR log entries object into browser HarEntries object");
SeleniumUtils.executeScript(driver, getHarLogScript);
harEntries = ((List<Object>) SeleniumUtils.executeScript(driver, "return window.HarEntries"));
I've been working recently on this kind of proxy. Project is pretty fresh, I'm still working on documentation but it may be worth checking. Sources and examples are here
Add dependency to your project
<dependency>
<groupId>com.moxproxy</groupId>
<artifactId>moxproxy.core</artifactId>
<version>1.0.2</version>
</dependency>
Start proxy
MoxProxy proxy = LocalMoxProxy.builder()
.withPort(89)
.build();
proxy.startServer();
Setup selenium webdriver to use proxy on localhost with port 89 and run test
Collect traffic
List<MoxProxyProcessedTrafficEntry> requestTraffic = proxy.getAllRequestTraffic();
List<MoxProxyProcessedTrafficEntry> responseTraffic = proxy.getAllResponseTraffic();
Beside collecting traffic proxy provides posibility to modify requests and responses - details on github
I am looking for an approach that will allow me to (somehow) dynamically pass the server name, server port, and web context to my Flex client so it can create a ChannelSet for it's RemoteObjects to use. These three properties are, of course, readily available to my Java server-side code so I just need a way to get them to the client.
By default, Adobe says you should compile your Flex application against the server configuration file "services-config.xml". This is a highly inflexible practice that Spring says should be avoided (I agree).
One popular approach is to use Flex's http service to download an XML configuration file. I like this idea, but I don't want to hard-code an XML file and keep it inside my WAR file. Is there a way to dynamically generate this from Java code?
Another idea I had is to somehow use flashvars to pass the properties in from the containing HTML page to the SWF file. But again, I don't want to hard code them into the HTML page. Is there a way (maybe with Javascript?) to dynamically set the value of these when the page loads?
This is how I do it. I hope you'll find it useful:
public static function getRemoteObject(destination:String, channelName:String,
showBusyCursor:Boolean=true):RemoteObject{
var remoteService:RemoteObject=new RemoteObject(destination);
var channelSet:ChannelSet=new ChannelSet();
var url:String = Application(Application.application).url;
var secure:Boolean = URLUtil.isHttpsURL(url);
var protocol:String = URLUtil.getProtocol(url);
var amf:AMFChannel;
if (secure){
amf = new SecureAMFChannel(channelName, protocol +
"://{server.name}:{server.port}" +
(Application.application as Application).parameters.contextRoot +
"/graniteamf/amf");
}else{
amf = new AMFChannel(channelName, protocol +
"://{server.name}:{server.port}" +
(Application.application as Application).parameters.contextRoot
+ "/graniteamf/amf");
}
channelSet.addChannel(amf);
remoteService.channelSet=channelSet;
remoteService.showBusyCursor=showBusyCursor;
return remoteService;
}
So as you can see the only things you need to provide are destination - which must be configured in server side XML and contextRoot - passed as flashVar. Passing as flashVar in my case (through JSP) looks like this:
String flashVariables = "contextRoot=" + request.getContextPath() +
"&locale=" + request.getLocale().getLanguage();
What's the best way to externalize large quantities of HTML in a GWT app? We have a rather complicated GWT app of about 30 "pages"; each page has a sort of guide at the bottom that is several paragraphs of HTML markup. I'd like to externalize the HTML so that it can remain as "unescaped" as possible.
I know and understand how to use property files in GWT; that's certainly better than embedding the content in Java classes, but still kind of ugly for HTML (you need to backslashify everything, as well as escape quotes, etc.)
Normally this is the kind of thing you would put in a JSP, but I don't see any equivalent to that in GWT. I'm considering just writing a widget that will simply fetch the content from html files on the server and then add the text to an HTML widget. But it seems there ought to be a simpler way.
I've used ClientBundle in a similar setting. I've created a package my.resources and put my HTML document and the following class there:
package my.resources;
import com.google.gwt.core.client.GWT;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.TextResource;
public interface MyHtmlResources extends ClientBundle {
public static final MyHtmlResources INSTANCE = GWT.create(MyHtmlResources.class);
#Source("intro.html")
public TextResource getIntroHtml();
}
Then I get the content of that file by calling the following from my GWT client code:
HTML htmlPanel = new HTML();
String html = MyHtmlResources.INSTANCE.getIntroHtml().getText();
htmlPanel.setHTML(html);
See http://code.google.com/webtoolkit/doc/latest/DevGuideClientBundle.html for further information.
You can use some templating mechanism. Try FreeMarker or Velocity templates. You'll be having your HTML in files that will be retrieved by templating libraries. These files can be named with proper extensions, e.g. .html, .css, .js obsearvable on their own.
I'd say you load the external html through a Frame.
Frame frame = new Frame();
frame.setUrl(GWT.getModuleBase() + getCurrentPageHelp());
add(frame);
You can arrange some convention or lookup for the getCurrentPageHelp() to return the appropriate path (eg: /manuals/myPage/help.html)
Here's an example of frame in action.
In GWT 2.0, you can do this using the UiBinder.
<ui:UiBinder xmlns:ui='urn:ui:com.google.gwt.uibinder'>
<div>
Hello, <span ui:field='nameSpan’/>, this is just good ‘ol HTML.
</div>
</ui:UiBinder>
These files are kept separate from your Java code and can be edited as HTML. They are also provide integration with GWT widgets, so that you can easily access elements within the HTML from your GWT code.
GWT 2.0, when released, should have a ClientBundle, which probably tackles this need.
You could try implementing a Generator to load external HTML from a file at compile time and build a class that emits it. There doesn't seem to be too much help online for creating generators but here's a post to the GWT group that might get you started: GWT group on groups.google.com.
I was doing similar research and, so far, I see that the best way to approach this problem is via the DeclarativeUI or UriBind. Unfortunately it still in incubator, so we need to work around the problem.
I solve it in couple of different ways:
Active overlay, i.e.: you create your standard HTML/CSS and inject the GET code via <script> tag. Everywhere you need to access an element from GWT code you write something like this:
RootPanel.get("element-name").setVisible(false);
You write your code 100% GWT and then, if a big HTML chunk is needed, you bring it to the client either via IFRAME or via AJAX and then inject it via HTML panel like this:
String html = "<div id='one' "
+ "style='border:3px dotted blue;'>"
+ "</div><div id='two' "
+ "style='border:3px dotted green;'"
+ "></div>";
HTMLPanel panel = new HTMLPanel(html);
panel.setSize("200px", "120px");
panel.addStyleName("demo-panel");
panel.add(new Button("Do Nothing"), "one");
panel.add(new TextBox(), "two");
RootPanel.get("demo").add(panel);
Why not to use good-old IFRAME? Just create an iFrame where you wish to put a hint and change its location when GWT 'page' changes.
Advantages:
Hits are stored in separate maintainable HTML files of any structure
AJAX-style loading with no coding at all on server side
If needed, application could still interact with loaded info
Disadvantages:
Each hint file should have link to shared CSS for common look-and-feel
Hard to internationalize
To make this approach a bit better, you might handle loading errors and redirect to default language/topic on 404 errors. So, search priority will be like that:
Current topic for current language
Current topic for default language
Default topic for current language
Default error page
I think it's quite easy to create such GWT component to incorporate iFrame interactions
The GWT Portlets framework (http://code.google.com/p/gwtportlets/) includes a WebAppContentPortlet. This serves up any content from your web app (static HTML, JSPs etc.). You can put it on a page with additional functionality in other Portlets and everything is fetched with a single async call when the page loads.
Have a look at the source for WebAppContentPortlet and WebAppContentDataProvider to see how it is done or try using the framework itself. Here are the relevant bits of source:
WebAppContentPortlet (client side)
((HasHTML)getWidget()).setHTML(html == null ? "<i>Web App Content</i>" : html);
WebAppContentDataProvider (server side):
HttpServletRequest servletRequest = req.getServletRequest();
String path = f.path.startsWith("/") ? f.path : "/" + f.path;
RequestDispatcher rd = servletRequest.getRequestDispatcher(path);
BufferedResponse res = new BufferedResponse(req.getServletResponse());
try {
rd.include(servletRequest, res);
res.getWriter().flush();
f.html = new String(res.toByteArray(), res.getCharacterEncoding());
} catch (Exception e) {
log.error("Error including '" + path + "': " + e, e);
f.html = "Error including '" + path +
"'<br>(see server log for details)";
}
You can use servlets with jsps for the html parts of the page and still include the javascript needed to run the gwt app on the page.
I'm not sure I understand your question, but I'm going to assume you've factored out this common summary into it's own widget. If so, the problem is that you don't like the ugly way of embedding HTML into the Java code.
GWT 2.0 has UiBinder, which allows you to define the GUI in raw HTMLish template, and you can inject values into the template from the Java world. Read through the dev guide and it gives a pretty good outline.
Take a look at
http://code.google.com/intl/es-ES/webtoolkit/doc/latest/DevGuideClientBundle.html
You can try GWT App with html templates generated and binded on run-time, no compiling-time.
Not knowing GWT, but can't you define and anchor div tag in your app html then perform a get against the HTML files that you need, and append to the div? How different would this be from a micro-template?
UPDATE:
I just found this nice jQuery plugin in an answer to another StackOverflow question.