I need help because i need to integrate JOSS in a existing code. My code uses the Consumer feature of Java 8.
Consumer<? super GHRepository> action = repo -> {
try {
if(github.getRateLimit().remaining > 0) {
Files.write(this.path, (repo.toString() + "\n").getBytes(), StandardOpenOption.APPEND);
totalIteration++;
} else {
logger.info("Time to pause for " + (github.getRateLimit().reset.getTime() - new Date().getTime()));
//wait until rate limit is ok.
do {
Thread.sleep(60000);
} while(github.getRateLimit().reset.after(new Date()));
}
} catch (Exception e) {
logger.error("Erreur d'écriture dans le fichier : " + e.getMessage());
}
};
This code works fine but disk space available on the machine is not enough. So i need to write the file directly on an OpenStack container.
I've read in the doc that JOSS uses this function to upload a file.
StoredObject object = container.getObject("dog.png");
object.uploadObject(new File("/dog.png"));
This is the method to upload a file already written. But I need to write the file directly on the container. The uploadObject function can receive a InputStream in parameter. So i want to use it. But i don't know how to integrate it with my existing code. Can you help me?
Ok, i find the way .
object.uploadObject(Files.newInputStream(Files.write(this.path, (repo.toString() + "\n").getBytes(), StandardOpenOption.APPEND)));
Related
In fact I am making a Minecraft plugin and I was wondering how some plugins (without using DB) manage to keep information even when the server is off.
For example if we make a grade plugin and we create a different list or we stack the players who constitute each. When the server will shut down and restart afterwards, the lists will become empty again (as I initialized them).
So I wanted to know if anyone had any idea how to keep this information.
If a plugin want to save informations only for itself, and it don't need to make it accessible from another way (a PHP website for example), you can use YAML format.
Create the config file :
File usersFile = new File(plugin.getDataFolder(), "user-data.yml");
if(!usersFile.exists()) { // don't exist
usersFile.createNewFile();
// OR you can copy file, but the plugin should contains a default file
/*try (InputStream in = plugin.getResource("user-data.yml");
OutputStream out = new FileOutputStream(usersFile)) {
ByteStreams.copy(in, out);
} catch (Exception e) {
e.printStackTrace();
}*/
}
Load the file as Yaml content :
YamlConfiguration config = YamlConfiguration.loadConfiguration(usersFile);
Edit content :
config.set(playerUUID, myVar);
Save content :
config.save(usersFile);
Also, I suggest you to make I/O async (read & write) with scheduler.
Bonus:
If you want to make ONE config file per user, and with default config, do like that :
File oneUsersFile = new File(plugin.getDataFolder(), playerUUID + ".yml");
if(!oneUsersFile.exists()) { // don't exist
try (InputStream in = plugin.getResource("my-def-file.yml");
OutputStream out = new FileOutputStream(oneUsersFile)) {
ByteStreams.copy(in, out); // copy default to current
} catch (Exception e) {
e.printStackTrace();
}
}
YamlConfiguration userConfig = YamlConfiguration.loadConfiguration(oneUsersFile);
PS: the variable plugin is the instance of your plugin, i.e. the class which extends "JavaPlugin".
You can use PersistentDataContainers:
To read data from a player, use
PersistentDataContainer p = player.getPersistentDataContainer();
int blocksBroken = p.get(new NamespacedKey(plugin, "blocks_broken"), PersistentDataType.INTEGER); // You can also use DOUBLE, STRING, etc.
The Namespaced key refers to the name or pointer to the data being stored. The PersistentDataType refers to the type of data that is being stored, which can be any Java primitive type or String. To write data to a player, use
p.set(new NamespacedKey(plugin, "blocks_broken"), PersistentDataType.INTEGER, blocksBroken + 1);
I'm using Java SDK 1.11.534
In my tool I declared a download named 'down' using TransferManager,
since the call:
down.waitForCompletion();
is a blocking call and stops the ProgressBar acknowledgement by ProgressListener I had to introduce a SwingWorker as follows:
SwingWorker worker = new SwingWorker<Void,Integer>(){
#Override
protected void process(List<Integer> chunks) {
int j = chunks.get(chunks.size()-1);
if (i<=fileNum) jLabel4.setText("Scaricamento file " + i+ " di " + fileNum + " del DCP "+ DCPname+" in corso, attendere....");
else jLabel4.setText("Scaricamento DCP "+ DCPname+" completato con successo.");
}
#Override
protected Void doInBackground(){
for (S3ObjectSummary file: fileList){
if((!isPresent(destination,file.getKey().substring(file.getKey().lastIndexOf("/") + 1),file.getSize())) && (!(file.getKey().substring(0, file.getKey().length()-1).equals(DCPname)))){
publish(i);
GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, file.getKey());
down = tx.download(getObjectRequest,new File(percorso+File.separator + file.getKey().substring(file.getKey().lastIndexOf("/") + 1)));
down.addProgressListener(progressListener);
try {
down.waitForCompletion();
} catch (AmazonClientException ex) {
ex.printStackTrace();
tx.shutdownNow(true);
//jButton4.setEnabled(true);
jButton4.doClick();
} catch (InterruptedException ex) {
ex.printStackTrace();
tx.shutdownNow(true);
//jButton4.setEnabled(true);
jButton4.doClick();
}
i++;
}
This is a portion of the code where doInBackground() shows the operations to do.
It happens sometimes to have an AmazonClientException reporting:
Not all bytes from S3inputstream were read
And this leads to have a corrupted file and a stop of the program itself upon exception.
At the beginning of my code (not reported here) before reaching the SwingWorker declaration, I stated that when the jButton4 is clicked the action starts checking if there's a size mismatch between files in the download folder and the ones on Amazon s3 and if there's a truncated file it gets deleted and the name is added to the download list again.
So the only solution I've found so far is to add the following line code:
jButton4.doClick();
In the exception code, meaning when an exception is hit the progress restarts and checks for truncated files and restarts downloads adding such a file too.
My question is:
Is there any way in the SDK to resume or better cancel and then download file again upon exception without restarting the program? I find the usage of:
jButton4.doClick();
is not a professional way of coding.
You could extract the content of the click action method into a new method and call that method instead.
I have a problem with a java based DXL import.
We want to maintain properties files via our Java framework. I am working with a temporary file on my filesystem (I am working on a local server). I am exporting the new properties file to my filesystem, generate a DXL file in the same folder and then try to import the DXL into my database.
I have done several options of the importer and we are creating the stream and the importer with sessionAsSignerWithFullAccess. The code is signed with the ID of the Server Admin who has Full Access to everything.
When importing the DXL I receive only the error message "DXL Import Operation failed", the error log of the importer says I am not authorized to perform this operation.
Do you have any idea what could be the problem? From my point of view I can't give my User any more rights on the server.
Here is the code for the import function:
private void importDXLFile(String filepath) {
String dxlPath = filepath.replaceAll(".properties", ".dxl");
DxlImporter importer = null;
Stream stream = null;
System.out.println("dxlPath: " + dxlPath);
try {
stream = BCCJsfUtil.getCurrentSessionAsSignerWithFullAccess(FacesContextEx.getCurrentInstance()).createStream();
if (!stream.open(dxlPath, "ISO-8859-1")) {
System.out.println("Cannot read " + dxlPath + " from server");
}
System.out.println("User: " + BCCJsfUtil.getCurrentSessionAsSignerWithFullAccess(FacesContextEx.getCurrentInstance()).getEffectiveUserName());
importer = BCCJsfUtil.getCurrentSessionAsSignerWithFullAccess(FacesContextEx.getCurrentInstance()).createDxlImporter();
importer.setReplaceDbProperties(false);
importer.setReplicaRequiredForReplaceOrUpdate(false);
importer.setDesignImportOption(DxlImporter.DXLIMPORTOPTION_REPLACE_ELSE_CREATE);
importer.setInputValidationOption(DxlImporter.DXLVALIDATIONOPTION_VALIDATE_NEVER);
importer.setExitOnFirstFatalError(false);
importer.importDxl(stream.readText(), BCCJsfUtil.getCurrentDatabase());
stream.close();
} catch (NotesException e) {
e.printStackTrace();
try {
System.out.println("Log: " + importer.getLog());
System.out.println("LogComment: " + importer.getLogComment());
} catch (NotesException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
As you can see I tried several options, hoping it would change anything, but it is always the same error message.
The generated DXL seems valid, as we can import it manually with Ytria.
I hope someone has an idea. Any help would be appreciated.
Thanks in advance.
Matthias
Please check your ACL settings:
Is "Maximum internet name and password" set to "Manager" or "Designer"?
I desperately need your expertise in resolving a Windows-7 issue.
Scenario: I have a frame-based Help package that is set up for context-sensitive help calls. A Java application is able to control what page the Help packages opens to by passing a tag representing the desired HTML named anchor to an HTML file called pophelp. This file has javascripting that reads the passed tag from the end of the URL and maps it to the appropriate HTML file in the help package and opens it.
Issue: The above scenario works in Windows XP, but no longer in Windows 7.
Calling mechanism from Java application: rundll32 url.dll,FileProtocolHandler file://filepath/pophelp.html?tag
Summary of findings so far: It appears that url.dll no longer allows parameters to be passed with URLs in Windows 7. Parameters are being stripped. I also tried the same type of call using Desktop.getDesktop().browse() from Java, but it too seems to strip off all parameters after .html.
Sample code:
Original call that works in Windows XP --
Running command: rundll32 url.dll,FileProtocolHandler file://C:\Program Files\App System\App-Editor-8.0.1\help\pophelp.html?TAG=callsubflow
Result: ?TAG=callsubflow is not passed.
New code using Desktop.getDesktop().browse() --
public static void main(String[] args) {
String url = "file:///C:/Program Files/App System/App-Editor-8.0.1/help/pophelp.html?TAG=callsubflow";
try {
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
if (desktop.isSupported(Desktop.Action.BROWSE)) {
desktop.browse(new URI(url.replace(" ", "%20")));
}
}
} catch (IOException e) {
System.out.println("Unable to open "+url+": "+e.getMessage());
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
Result: ?TAG=callsubflow is not passed.
Any assistance would be appreciated!
I really can't tell why Windows removes parameters on local files. As mentioned in the comments this seams to be some kind of weird restrictions for security. But I once had a similar problem and I found a workaround that fits in this situation as well.
Simply create a local temporary HTML file (without parameters) that redirects you to the desired one (with parameters).Have a look at these two methods:
// creates w3c conform redirect HTML page
public String createRedirectPage(String url){
return "<!DOCTYPE HTML>" +
"<meta charset=\"UTF-8\">" +
"<meta http-equiv=\"refresh\" content=\"1; url=" + url + "\">" +
"<script>" +
"window.location.href = \"" + url + "\"" +
"</script>" +
"<title>Page Redirection</title>" +
"<!-- Note: don't tell people to `click` the link, just tell them that it is a link. -->" +
"If you are not redirected automatically, follow the <a href='" + url + "'>link</a>";
}
// creates temporary file with content of redirect HTML page
public URI createRedirectTempFile(String url) {
BufferedWriter writer = null;
File tmpFile = null;
try {
// creates temporary file
tmpFile = File.createTempFile("pophelp", ".html", null);
// deletes file when the virtual machine terminate
tmpFile.deleteOnExit();
// writes redirect page content to file
writer = new BufferedWriter(new FileWriter(tmpFile));
writer.write(createRedirectPage(url));
writer.close();
}
catch (IOException e) {
return null;
}
return tmpFile.toURI();
}
Now you can use these like this:
String url = "file:///C:/Program Files/App System/App-Editor-8.0.1/help/pophelp.html?TAG=callsubflow";
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
if (desktop.isSupported(Desktop.Action.BROWSE)) {
desktop.browse(createRedirectTempFile(url.replace(" ", "%20")));
}
}
I have a solution, not a quick (or pretty) solution, but a solution nonetheless :)
rundll32 url.dll,FileProtocolHandler does pass params when using URLs with http/s protocol (try rundll32 url.dll,FileProtocolHandler http://www.google.com?q=google), so you can setup small http server (like Jetty i guess) to serve your help files and show them using
rundll32 url.dll,FileProtocolHandler http://localhost:[helpServerIp]/help/pophelp.html?TAG=callsubflow
I would like to be able to operate a scanner from my AIR application. Since there's no support for this natively, I'm trying to use the NativeProcess class to start a jar file that can run the scanner. The Java code is using the JTwain library to operate the scanner. The Java application runs fine by itself, and the AIR application can start and communicate with the Java application. The problem seems to be that any time I attempt to use a function from JTwain (which relies on the JTwain.dll), the application dies IF AIR STARTED IT.
I'm not sure if there's some limit about referencing dll files from the native process or what. I've included my code below
Java code-
while(true)
{
try {
System.out.println("Start");
text = in.readLine();
Source source = SourceManager.instance().getCurrentSource();
System.out.println("Java says: "+ text);
}
catch (IOException e)
{
System.err.println("Exception while reading the input. " + e);
}
catch (Exception e) {
System.out.println("Other exception occured: " + e.toString());
}
finally {
}
}
}
Air application-
import mx.events.FlexEvent;
private var nativeProcess:NativeProcess;
private var npInfo:NativeProcessStartupInfo;
private var processBuffer:ByteArray;
private var bLength:int = 0;
protected function windowedapplication1_applicationCompleteHandler(event:FlexEvent):void
{
var arg:Vector.<String> = new Vector.<String>;
arg.push("-jar");
arg.push(File.applicationDirectory.resolvePath("Hello2.jar").nativePath);
processBuffer = new ByteArray;
npInfo = new NativeProcessStartupInfo;
npInfo.executable = new File("C:/Program Files/Java/jre6/bin/javaw.exe");
npInfo.arguments = arg;
nativeProcess = new NativeProcess;
nativeProcess.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, onStandardOutputData);
nativeProcess.start(npInfo);
}
private function onStandardOutputData(e:ProgressEvent):void
{
tArea.text += nativeProcess.standardOutput.readUTFBytes(nativeProcess.standardOutput.bytesAvailable);
}
protected function button1_clickHandler(event:MouseEvent):void
{
tArea.text += 'AIR app: '+tInput.text + '\n';
nativeProcess.standardInput.writeMultiByte(tInput.text + "\n", 'utf-8');
tInput.text = '';
}
protected function windowedapplication1_closeHandler(event:Event):void
{
nativeProcess.closeInput();
}
]]>
</fx:Script>
<s:Button label="Send" x="221" y="11" click="button1_clickHandler(event)"/>
<s:TextInput id="tInput" x="10" y="10" width="203"/>
<s:TextArea id="tArea" x="10" width="282" height="88" top="40"/>
I would love some explanation about why this is dying. I've done enough testing that I know absolutely that the line that kills it is the SourceManager.instance().getCurrentSource(). I would love any suggestions. Thanks.
When calling Java add this -Djava.library.path=location_of_dll to the command line
I have 0 experience with Air, but this reminded me of a Java issue I once spent some time figuring out. I don't have a suggestion on why the scanning doesn't work, but I think a stack trace would be your best friend right now.
I'm guessing you're relying on this line to capture and display it?
nativeProcess.standardOutput.readUTFBytes(nativeProcess.standardOutput.bytesAvailable);
However, you are writing IOExceptions to System.err - is there a nativeProcess.standardError you could read in Air? Alternatively, output everything to System.out.