I'm learning Java and sometimes I have some problem to retrieve the information I need from objects...
When I debug my code I can see in targetFile, a path property but I don't know how to get it in my code.
This is a screenshot:
(source: toile-libre.org)
This is my complete code:
package com.example.helloworld;
import com.github.axet.wget.WGet;
import com.github.axet.wget.info.DownloadInfo;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import java.io.File;
import java.io.IOException;
import java.net.URL;
public class HelloWorld {
public static void main(String[] args) throws IOException {
nodejs();
}
public static void nodejs() throws IOException {
// Scrap the download url.
Document doc = Jsoup.connect("http://nodejs.org/download").get();
Element link = doc.select("div.interior:nth-child(2) > table:nth-child(2) > tbody:nth-child(1) > tr:nth-child(1) > td:nth-child(3) > a:nth-child(1)").first();
String url = link.attr("abs:href");
// Print the download url.
System.out.println(url);
// Download file via the scraped url.
URL download = new URL(url);
File target = new File("/home/lan/Desktop/");
WGet w = new WGet(download, target);
w.download();
// Get the targetFile property
// ???
}
}
How can I get this value?
I do not know your code but the field you are interested in may be encapsulated and thus not accessible in your code, but the debugger can see it at runtime :)
Update:
https://github.com/axet/wget/blob/master/src/main/java/com/github/axet/wget/WGet.java
The field is default package, you can only access it from within the package.
This can be frustrating at times, but you should ask yourself why the designers of this class decided to hide this field.
Related
How do I declare the application credentials? I have my .json file which is the key.
package shyam;
// Imports the Google Cloud client library
import com.google.cloud.vision.v1.AnnotateImageRequest;
import com.google.cloud.vision.v1.AnnotateImageResponse;
import com.google.cloud.vision.v1.BatchAnnotateImagesResponse;
import com.google.cloud.vision.v1.EntityAnnotation;
import com.google.cloud.vision.v1.Feature;
import com.google.cloud.vision.v1.Feature.Type;
import com.google.cloud.vision.v1.Image;
import com.google.cloud.vision.v1.ImageAnnotatorClient;
import com.google.protobuf.ByteString;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class App {
public static void main(String[] args) throws Exception {
// Initialize client that will be used to send requests. This client only needs to be created
// once, and can be reused for multiple requests. After completing all of your requests, call
// the "close" method on the client to safely clean up any remaining background resources.
try (ImageAnnotatorClient vision = ImageAnnotatorClient.create()) {
// The path to the image file to annotate
String fileName = "./resources/wakeupcat.jpg";
// Reads the image file into memory
Path path = Paths.get(fileName);
byte[] data = Files.readAllBytes(path);
ByteString imgBytes = ByteString.copyFrom(data);
// Builds the image annotation request
List<AnnotateImageRequest> requests = new ArrayList<>();
Image img = Image.newBuilder().setContent(imgBytes).build();
Feature feat = Feature.newBuilder().setType(Type.LABEL_DETECTION).build();
AnnotateImageRequest request =
AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build();
requests.add(request);
// Performs label detection on the image file
BatchAnnotateImagesResponse response = vision.batchAnnotateImages(requests);
List<AnnotateImageResponse> responses = response.getResponsesList();
for (AnnotateImageResponse res : responses) {
if (res.hasError()) {
System.out.format("Error: %s%n", res.getError().getMessage());
return;
}
// for (EntityAnnotation annotation : res.getLabelAnnotationsList()) {
// annotation
// .getAllFields()
// .forEach((k, v) -> System.out.format("%s : %s%n", k, v.toString()));
// }
}
}
}
}
I'm getting the error
Application default credentials are not available
I have already set it in my cmd using set GOOGLE_APPLICATION_CREDENTIALS='key_path'. I have a lot initialized my Google Cloud Account in the cli. Hope someone can help me. Thank you.
I'm creating a PhpStorm plugin with IntelliJ IDEA Community Edition and I would like to know how to create a file on disk from a PSIFile or VirtualFile.
Here my code: (The context is an action from NewGroup)
I've tried to use the PsiDirectory.copyFileFrom method to create the file but I have an exception com.intellij.util.IncorrectOperationException: Cannot copy non-physical file: PHP file
package fr.florent.idea.zendgenerator.action.NewGroup;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.fileEditor.impl.LoadTextUtil;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiFileFactory;
import com.intellij.util.ResourceUtil;
import com.jetbrains.php.lang.PhpFileType;
import fr.florent.idea.zendgenerator.action.AbstractDumbAwareAction;
import icons.PhpIcons;
import org.jetbrains.annotations.NotNull;
import java.net.URL;
public class CreateQueryAction extends AbstractDumbAwareAction {
public CreateQueryAction() {
super("Query", "Create query", PhpIcons.Php_icon);
}
#Override
public void actionPerformed(#NotNull AnActionEvent e) {
URL url = ResourceUtil.getResource(getClass(), "templates", "query.php"); // it contains an empty PHP class
VirtualFile virtualFile = VfsUtil.findFileByURL(url);
PsiFile file = PsiFileFactory.getInstance(e.getProject()).createFileFromText(
virtualFile.getPath(),
PhpFileType.INSTANCE,
LoadTextUtil.loadText(virtualFile)
);
PsiDirectory directory = LangDataKeys.IDE_VIEW.getData(e.getDataContext()).getOrChooseDirectory();
directory.copyFileFrom("query.php", file);
System.out.println("Create query");
}
}
I would like to have the file created in the project folder from the context of my action.
It will be great if someone can explain the process of creating a file in a IntelliJ plugin. I think the docs is really light.
In my case I would like to have the process to edit the query.php file, rename the class name, add method, properties, doc block and save it to the disk but I don't understand the PSI element.
You might want to ask this also on JB forum, there's a similar question: https://intellij-support.jetbrains.com/hc/en-us/community/posts/360001787320-Create-VirtualFile-or-PsiFile-from-content
The answer is:
final PsiFileFactory factory = PsiFileFactory.getInstance(project);
final PsiFile file = factory.createFileFromText(language, text);
i need to created Azure function BlobTrigger using Java to monitor my storage container for new and updated blobs.
tried with below code
import java.util.*;
import com.microsoft.azure.serverless.functions.annotation.*;
import com.microsoft.azure.serverless.functions.*;
import java.nio.file.*;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import com.microsoft.azure.storage.*;
import com.microsoft.azure.storage.blob.*;
#FunctionName("testblobtrigger")
public String testblobtrigger(#BlobTrigger(name = "test", path = "testcontainer/{name}") String content) {
try {
return String.format("Blob content : %s!", content);
} catch (Exception e) {
// Output the stack trace.
e.printStackTrace();
return "Access Error!";
}
}
when executed it is showing error
Storage binding (blob/queue/table) must have non-empty connection. Invalid storage binding found on method:
it is working when added connection string
public String kafkablobtrigger(#BlobTrigger(name = "test", path = "testjavablobstorage/{name}",connection=storageConnectionString) String content) {
why i need to add connection string when using blobtrigger?
in C# it is working without connection string:
public static void ProcessBlobContainer1([BlobTrigger("container1/{blobName}")] CloudBlockBlob blob, string blobName)
{
ProcessBlob("container1", blobName, blob);
}
i didn't see any Java sample for Azure functions for #BlobTrigger.
After all, connection is necessary for the trigger to identify where the container locates.
After test I find #Mikhail is right.
For C#, the default value(in local.settings.json or in application settings in portal) will be used if connection is ignored. But unfortunately there's no same settings for java.
You can add #StorageAccount("YourStorageConnection") below your #FuncionName as it's another valid way to choose. And value of YourStorageConnection in local.settings.json or in portal's application settings is up to you.
You can follow this tutorial, use mvn azure-functions:add to find four(Http/Blob/Queue/TimerTrigger) templates for java.
I'm trying to create SPA, using Spark on server-side.
Here is my App.java:
package com.farot;
import java.util.HashMap;
import java.util.UUID;
import java.net.URL;
import java.net.URISyntaxException;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.nio.charset.Charset;
import java.io.IOException;
import com.google.gson.Gson;
import static spark.Spark.*;
import com.farot.utils.Path;
import com.farot.controllers.UserController;
import com.farot.controllers.AccountController;
import com.farot.controllers.MapController;
public class App
{
private static Gson gson = new Gson();
private static String renderIndex() {
try {
URL url = App.class.getResource("index.html");
return new String(Files.readAllBytes(Paths.get(url.toURI())), Charset.defaultCharset());
} catch (IOException | URISyntaxException e) {
System.out.println(e.getMessage());
}
return null;
}
public static void main( String[] args )
{
staticFiles.location("/public");
before((req, res) -> {
String path = req.pathInfo();
if (path.endsWith("/"))
res.redirect(path.substring(0, path.length() - 1));
});
// Site pages
get("/", "text/html", (req, res) -> renderIndex());
get("/login", "text/html", (req, res) -> renderIndex());
post(Path.Web.api.Account.DEFAULT, (req, res) -> {
return AccountController.create(req, res);
}, gson::toJson);
}
}
POST request at Path.Web.api.Account.DEFAULT works as expected, but request at /login returns 404. What can be wrong?
index.html's path is /resources/public/index.html.
The problem is in the function renderIndex(). After using the correct resource path (i.e. /public/index.html) the variable url is not null anymore, but according to what you said in the comments it's something weird (jar:file:/home/gorrtack/workspace/Farot/target/Farot-1.0-SNAPSHOT-jar-with-dependencies.jar!/public/index.html), something with no valid path.
When Paths.get() tries to resolve this path it fails and throws a NoSuchFileException (which is an IOException). Then, you catch it in the catch block, and returns null. The returning of null is wrong and it's the reason for the error 404 you're getting.
So you need:
To change something in the structure of your project so the path of index.html is right. Then you'll avoid the problems in this scenario.
Handle the exceptions correctly, means - don't return null. Decide what you want to do in these cases and then, if you want, you can still serve a normal error message to the client and/or use request.status() API or any any other response APIs to set a response status by yourself.
In the renderIndex() method, access the path as below:
URL url = App.class.getResource("/public/index.html");
I am trying to retrieve the owner of a file, using this code:
Path file = Paths.get( fileToExtract.getAbsolutePath() );
PosixFileAttributes attr = Files.readAttributes(file, PosixFileAttributes.class); //line that throws exception
System.out.println(attr.owner.getName());
taken from oracle's page (http://docs.oracle.com/javase/tutorial/essential/io/fileAttr.html)
but i always get a UnsupportedOperationException at the line i indicate above.
java.lang.UnsupportedOperationException
at sun.nio.fs.WindowsFileSystemProvider.readAttributes(WindowsFileSystemProvider.java:192)
at java.nio.file.Files.readAttributes(Files.java:1684)
I think that 'readAttributes' method is abstract and this cause the exception, but (if this is true) i don't know how to implement this method in order to give me the file attributes.
Does anyone know how to implement this method, or an alternative method (that is tested) to get the file owner?
Try this - works also on Windows
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileOwnerAttributeView;
import java.nio.file.attribute.UserPrincipal;
public class FileOwner {
public static void main(String[] args) throws IOException {
Path path = Paths.get("/tmp");
FileOwnerAttributeView ownerAttributeView = Files.getFileAttributeView(path, FileOwnerAttributeView.class);
UserPrincipal owner = ownerAttributeView.getOwner();
System.out.println("owner: " + owner.getName());
}
}
Use BasicFileAttributes instead.
BasicFileAttributes attr = Files.readAttributes(file, BasicFileAttributes.class);
Posix file attributes are not supported in Windows.
Here is is a sample for files permissions on UNIX/Linux platforms
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFileAttributes;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.Set;
class A {
public static void main(String[] args) throws Exception
{
//Make sure file exists e.g. Unix path structure
Path p = Paths.get("/a/b/Log.txt");
PosixFileAttributes posix = Files.readAttributes(p,
PosixFileAttributes.class);
//Set Permissions if needs be for the file Log.txt
Set<PosixFilePermission> perms =
PosixFilePermissions.fromString("rw-r--r--");
Files.setPosixFilePermissions(p, perms);
//Output the various attributes of the file named Log.txt
System.out.println(posix.group());
System.out.println(posix.permissions());
System.out.println(posix.owner());
}
}