Tapestry dynamic generated image - java

My Tapestry5 application generate dynamically images with jFreeChart every day.
My problem is that i don't know how to show.
I have tried to save them into the webapp folder, but it seems impossible, no file is created inside.
I have tried a solution with StreamResponse without result.
Another one is about IEngineService but it seems to be only available for T4.
So, i would appreciate some help.
Thanks.

Ok i find where was the problem, here the solution, for the other class, please see Tapestry5: How To Stream An Existing Binary File.
public StreamResponse onImage() {
StreamResponse result = null;
if (graphic != null && graphic.getImage() != null) {
try {
InputStream input = new FileInputStream(graphic.getImage());
result = new PngInline(input, "test");
} catch (FileNotFoundException e) {
logger.error("Loading graphic image", e);
}
}
return result;
}
#Inject
private ComponentResources resources;
public Link getLink() {
return resources.createEventLink("image", new Object[]{});
}

Related

Update hashset from .txt while app is running

The goal is to block access to the page from the list of IP addresses. This list is in the file list.txt.
I made the service that checks IP from request and with HashSet of "unwanted" addresses, but subgoal is "catch on the fly" this list.txt. What I mean: if I add some IP to this file, it should be blocked without restarting application. And I have not ideas how to solve this, cause my app refreshes this list only after restart. My code is below
#Service
public class BlackListService {
public Set<String> loadBlackList() {
java.util.Set<java.lang.String> blackList = new HashSet<>();
InputStream resource = null;
try {
resource = new ClassPathResource(
"blacklist.txt").getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
try (BufferedReader reader = new BufferedReader(new InputStreamReader(resource))) {
blackList = reader.lines().collect(Collectors.toSet());
for (java.lang.String address:
blackList) {
System.out.println(address);
}
} catch (IOException e) {
e.printStackTrace();
}
return blackList;
}
public boolean isNowAllowedIP(Set<String> blackList, String requestIP) {
return blackList.contains(requestIP);
}
}
And controller:
#Controller
public class MainController {
private final BlackListService blackListService;
public MainController(BlackListService blackListService) {
this.blackListService = blackListService;
}
#GetMapping("/")
public String mainPage(HttpServletRequest request, Model model) {
Set<String> blackList = blackListService.loadBlackList();
if (blackListService.isNowAllowedIP(blackList, request.getRemoteAddr())) {
Logger logger = Logger.getLogger("Access logs");
logger.warning("Access disallowed");
model.addAttribute("message", request.getRemoteAddr() + ": Access disallowed");
return "index";
}
model.addAttribute("message", "Access allowed");
return "index";
}
}
Can someone help with this "subgoal"?
In loadBlackList() you are reading a resource from the classpath. Could this be picking up a file built into your jar file or build dir which is not the file you are editing? I would try changing loadBlackList() to use FileReader and a path on the file system rather than a path within the classpath instead of InputStreamReader.
What you need is a recurring background job that will reload your blacklist after you change it. This blog will discusses a "modern" approach for doing it with Spring.
Save the last modified time for the file when your program starts and you first load it. See this for checking the file modified time.
Schedule the background job to run every minute (or 5 or whatever is frequent enough for your needs).
When the job runs check the current last updated time on the file and if its different than the saved one, then its time to reload your list.

SnakeYAML loadAs() returns null

I attempted to create a Spigot plugin today and I'm coming up with an error that's hard to fix. When I was trying to create a file system to save some data I downloaded the source code for the library SnakeYAML and put it in my src. Then I followed this tutorial and created a config and followed all the instructions. I'm getting a NullPointerException. It turns out the config object is null. I'm not sure what's happening.
PlayerYML getConfig(File playerYml) {
try {
InputStream ymlStream = new FileInputStream(playerYml.getAbsolutePath());
System.out.println(ymlStream);
PlayerYML config = yaml.loadAs(ymlStream, PlayerYML.class);
return config;
} catch (Exception ex) {
System.out.println("getConfig() error");
ex.printStackTrace();
return null;
}
}
Here is my PlayerYML class:
import java.util.Map;
public class PlayerYML {
private int reputation;
private Map<String/*UUID*/, String/*Date*/> map;
public int getReputation() {
return reputation;
}
public void setReputation(int reputation) {
this.reputation = reputation;
}
public Map<String, String> getMap() {
return map;
}
public void setMap(Map<String, String> map) {
this.map = map;
}
}
I appreciate all help! Thank you :)
You are trying to load an empty file/stream as on object which will result in null using SnakeYAML.
If you want to handle the absense of the file properly instead of just creating an empty file, you should check if it exists and directly create a default instance of the object if the file doesn't exist. If you then want to create the file with defaults for the user to edit them, just store the default instance of the object using one of the Yaml.dump* methods. That way you avoid creating an empty object by yourself. You still have to handle empty files in case of user errors.
What happened to me was that my InputStream was already entirely consumed by a BufferedReader just above, so there was nothing left in the Stream to be treated.
What I had to do was to reset the InputStream or simply open a new one.

How to find which type a exchange Body in camel is?

I create a processor to download some files from an external source.
I do it, like this:
CamelContext context = exchange.getContext();
ProducerTemplate template=context.createProducerTemplate();
Object answer=null;
try {
answer=template.requestBodyAndHeaders(
uri,
"",
headers);
} catch (Exception e) {
....
} finally {
template.stop();
}
if (answer != null) {
/* Here I need to know, if it is a file, or an error-message */
}
The problem is, the request can be an error-message (String), or it is a stream (when file is found).
How can I check this?
Thank you for any help
UPDATE:
Code of the Route is easy:
from("http://domain.de/getDoc?Id=123")
to("file:docs")
Maybe just "instanceof" checks will help?

DownloadLink with an option to choose the directory where the file should be saved apache wicket

this is my download link I did from the wicket example site. I would like to alter it by letting the user choose the directory the file should be saved. Any way to implement it? Thanks in advance
add(new DownloadLink("generate_report", new AbstractReadOnlyModel<File>()
{
private static final long serialVersionUID = 1L;
#Override
public File getObject()
{
File tempFile;
try
{
tempFile = File.createTempFile("wicket-examples-download-link--", ".tmp");
InputStream data = new ByteArrayInputStream("some data".getBytes());
Files.writeTo(tempFile, data);
}
catch (IOException e)
{
throw new RuntimeException(e);
}
return tempFile;
}
}).setCacheDuration(Duration.NONE).setDeleteAfterDownload(true));
If you have preset paths then the user can choose which one they want to use by using the include_path function; however, the user will not be able to create their own directory/path.
EDIT: Couldn't put code in that comment lol but here is where I was going at.
$path1=set_include_path('file\whateveryouwant');
Then you can use multiple paths and let the user choose from the paths by calling the $path1 (wich would be the extension for the path you want them to use).
More info: http://php.net/manual/en/function.get-include-path.php

Building JCoServer without Properties-File

I got another JCo-related question and hopefully finding help.
With JCo you can easily build up a connection like it is explained in the example sheets which came with the JCo-library. Unfortunately, the only way building a connection is handled with a created property file. It wouldn´t be that bad, if there wasn´t any sensible data in it. But at least, the password for the SAP user stands in the file, so it is a lack of safety in this way of connection-handling. The manual of JCo says so, too :
"For this example the destination configuration is stored in a file that is called by the program. In practice you should avoid this for security reasons."
but couldn´t find a working solution after all. There are a palmful threads about this theme, like this
http://forums.sdn.sap.com/thread.jspa?messageID=7303957
but none of them are helpful. I really can´t figure out a solution and neither find one. Actually I solved the security-problem with deleting the file after building the connection, but this is not a satisfying solution. There have to be a better way getting the parameter for the connection, especially when it stands in the manual, but I have no glue how.
Anybody already worked with JCo 3.0 and knows this problem?
Yes, that's possible. You have to create your own implementation of DestinationDataProvider and register it using Environment.registerDestinationDataProvider(). However your DDP obtains the connection data and credentials is up to you. Take a look at net.sf.rcer.conn.connections.ConnectionManager, there's a working example in there.
You need to
copy the private class starting on line 66 and adapt it to your own needs (that is, fetch the connection data from wherever you want to)
perform the registration (line 204) somewhere during the startup of your application
get the connection using some string identifier that will be passed to your DestinationDataProvider.
It's a bit confusing, it was dificult to me how to figure this too.
All you need is an object of type java.util.Properties to fill the desired fields, but it's up to ou how to fill this object.
I dit it through a ValueObject, I can fill this VO from a file, database, web form...
JCOProvider jcoProvider = null;
SAPVO sap = new SAPVO(); // Value Object
Properties properties = new Properties();
if(jcoProvider == null) {
// Get SAP config from DB
try {
sap = SAPDAO.getSAPConfig(); // DAO object that gets conn data from DB
} catch (Exception ex) {
throw new ConexionSAPException(ex.getMessage());
}
// Create new conn
jcoProvider = new JCOProvider();
}
properties.setProperty(DestinationDataProvider.JCO_ASHOST, sap.getJCO_ASHOST());
properties.setProperty(DestinationDataProvider.JCO_SYSNR, sap.getJCO_SYSNR());
properties.setProperty(DestinationDataProvider.JCO_CLIENT, sap.getJCO_CLIENT());
properties.setProperty(DestinationDataProvider.JCO_USER, sap.getJCO_USER());
properties.setProperty(DestinationDataProvider.JCO_PASSWD, sap.getJCO_PASSWD());
properties.setProperty(DestinationDataProvider.JCO_LANG, sap.getJCO_LANG());
// properties.setProperty(DestinationDataProvider.JCO_TRACE, "10");
try {
jcoProvider.changePropertiesForABAP_AS(properties);
} catch (Exception e) {
throw new ConexionSAPException(e.getMessage());
}
The JCOProvider class:
import com.sap.conn.jco.ext.DestinationDataEventListener;
import com.sap.conn.jco.ext.DestinationDataProvider;
import com.sap.conn.jco.ext.Environment;
import es.grupotec.ejb.util.ConexionSAPException;
import java.util.Properties;
public class JCOProvider implements DestinationDataProvider {
private String SAP_SERVER = "SAPSERVER";
private DestinationDataEventListener eventListener;
private Properties ABAP_AS_properties;
public JCOProvider() {
}
#Override
public Properties getDestinationProperties(String name) {
if (name.equals(SAP_SERVER) && ABAP_AS_properties != null) {
return ABAP_AS_properties;
} else {
return null;
}
// if(ABAP_AS_properties!=null) return ABAP_AS_properties;
// else throw new RuntimeException("Destination " + name + " is not available");
}
#Override
public boolean supportsEvents() {
return true;
}
#Override
public void setDestinationDataEventListener(DestinationDataEventListener eventListener) {
this.eventListener = eventListener;
}
public void changePropertiesForABAP_AS(Properties properties) throws ConexionSAPException {
try {
if (!Environment.isDestinationDataProviderRegistered()) {
if (ABAP_AS_properties == null) {
ABAP_AS_properties = properties;
}
Environment.registerDestinationDataProvider(this);
}
if (properties == null) {
if (eventListener != null) {
eventListener.deleted(SAP_SERVER);
}
ABAP_AS_properties = null;
} else {
ABAP_AS_properties = properties;
if (eventListener != null) {
eventListener.updated(SAP_SERVER);
}
}
} catch (Exception ex) {
throw new ConexionSAPException(ex.getMessage());
}
}
}
Regards

Categories

Resources